Hi everyone, I'd watched a tutorial on how to write API. So I learnt that, one of advantages on using API is that all the resources can be consumed to different frontend be it SPA or mobile.
The question is, what about our internal or web route? can we reuse or consume the API route in the web route? I notice that if we are to build separately from the API route we have two different codebases with similar role or function.
API response, Usaully you send JSON formatted data as response. And you can send JSON from any route.
API routes in Laravel, The difference between api.php routes and web.php routes is the middleware group which each file uses. You can check each middleware group in App/Http/Kernal.php.
To answer your questions, If your application is using web middleware group, thus you need to declare your routes in web.php, if it uses api middleware group, then use api.php.
And with each type of these routes you can send whatever response you want including JSON.
I'm sorry I think that my question is confusing. But what I'm trying to ask is, in pursuit of API first web app. After all the logic coding in internal/web routes are done including the routes and controller for the API is done, New requirement are added so that the web app will also serve itself as a client instead of an API only web app.
By client I mean that using blade files in the same codebases. I found that I need to start all over again. Make new controllers so that I can use the blade files. The same logic need to reapply again, copy pasting from the api controllers.
They are all pretty the same. The differece is the API response is in JSON, and the web is just blade files. After sometime searching, I found about service class that we can use to contained the logic and reused it anywhere that we like. But is there any other better options or other best practice that is worth following?
@AfiqHamzah I guess is using Front-end framework so you can use your API routes. And try looking on sanctum to handle authentication from your front-end with session instead of tokens.