Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

orest's avatar
Level 13

web and api use cases

I am trying to wrap my head around the use cases of web routes and api routes.

So far, from what i understand

  1. Web routes, are used when we want to return views.

  2. Api routes, are used when we want to return json ( Api resource/collection ).

However both of these cases are referring to GET requests.

What about when we make a POST or PUT request, do we put these routes in api.php or web.php. Does it depend on whether the request is through an AJAX call ?

Additionally, i can't figure out in what cases should we use the api middleware and web middleware By default, the web.php uses web middleware, whereas the api.php uses the api middleware.

In the case where we are already signed in and we want to make an AJAX call, do we have to put that route in the api.php or web.php.

Do we use the api middleware only when we sign in using token based authentication ?

0 likes
3 replies
UhOh's avatar

My take: API and AJAX are not the same thing.

API is stateless, requires JWT, and is really for things ling mobile apps, micro-services and such, serving up resources. They can be consumed.

Ajax is really just a web route used for internal app purposes like interactive UIs. You simply apply a 'web' route to it. They can't be consumed. Only the app should be making the calls to these routes. So you can enforce CSRF, etc with web middleware, etc.

The way I do it, I break up my routes...

routes/web.php // web middleware

routes/ajax.php // web middleware

routes/api.php // api middleware

I prefix my Ajax routes to look like this /ajax/do-foo.

1 like
martinbean's avatar

@orest Use web routes for your web application and api routes for exposing an API for your application.

An API != “JSON responses”. An API could return other types of responses: XML, files, plain text. JSON just happens to be common.

If you’re planning on using AJAX, then AJAX requests would normally be made against an API rather than your web application. Your web application would serve HTML views, whilst AJAX requests data in a more, “raw” format (i.e. JSON), and then your client-side JavaScript would use a template to render that data back in your HTML view.

1 like
orest's avatar
Level 13

@uhoh @martinbean Thanks!

What about the middlewares that are applied on web.php and api.php ?

For example, on the client-side i make AJAX requests to either fetch or store data and the respective routes are stored in the api.php.

Which middleware should i use for that route ? It's not clear to me when should i use the web middleware and when should i use the api middleware.

Please or to participate in this conversation.