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

ruthback's avatar

Guidelines for combining web.php and api.php routes?

Hello, I was just wondering if there are any guidelines for when to reach for an API endpoint vs a regular route. I tend to think about this in terms actions that don't necessarily require a page redirect or are asynchronous, like a "like" button, quick edit, avatar update, etc. Another way that I like to think about this is based on the expected response from the server, like the HTTP code to determine what to do next. How do you decide which file to use when creating routes? Cheers!

0 likes
6 replies
LaryAI's avatar
Level 58

Hello,

When deciding whether to use web.php or api.php for routing in Laravel, it's important to consider the nature of the interaction and the type of response you expect from the server. Here are some guidelines to help you decide:

Use web.php when:

  1. Session State is Required: Routes in web.php typically utilize session state, CSRF protection, and cookies. This is ideal for actions that are part of a web interface where user state is maintained.
  2. Returning HTML Views: If the route is meant to return a full HTML page (e.g., when a user navigates to a specific URL in your application), it should go in web.php.
  3. Form Submissions: Actions like submitting forms where a page refresh might occur and where you might want to leverage Laravel's session-backed error handling.

Use api.php when:

  1. Stateless: API routes are stateless by default and do not maintain session state between requests. This is suitable for mobile apps or external clients.
  2. Returning JSON: If the endpoint is meant to return JSON responses, especially for AJAX calls, it should be defined in api.php.
  3. Consumed by External Clients: If the endpoint is intended to be used by external clients (e.g., third-party services, mobile apps), it's better to place it in api.php to leverage API rate limiting and token authentication.

Practical Examples:

Example of web.php:

Route::get('/profile', function () {
    return view('profile');
});

Route::post('/profile', function () {
    // Handle the form submission
    return redirect('/profile')->with('status', 'Profile updated!');
});

Example of api.php:

Route::post('/like-post', function (Request $request) {
    // Assume the user is authenticated and the post ID is provided
    $post = Post::find($request->post_id);
    $post->likes += 1;
    $post->save();

    return response()->json(['message' => 'Post liked successfully', 'likes' => $post->likes]);
});

Conclusion:

Choose web.php for routes that are part of the regular web interface with session state and HTML views. Opt for api.php for stateless, JSON-returning routes that might be accessed externally or used asynchronously from within your web application. This separation not only adheres to Laravel's design but also helps in maintaining clear boundaries and better organization of routes.

Cheers!

gych's avatar

API routes are stateless, WEB routes are statefull.

API routes are used for front end application that are separated from the Laravel back-end like a Vue/React SPA or a mobile application and can also be used for ajax requests in your application to return a json response. For ajax requests in the same application its also possible to use WEB routes.

WEB routes include CSRF middleware and sessions. API routes have rate limiting but don't include CSRF protection and sessions.

When using api routes the route will have api/ as prefix

1 like
puklipo's avatar

The difference between web.php and api.php is only the difference in middleware groups.

https://github.com/laravel/laravel/blob/10.x/app/Http/Kernel.php#L31

    protected $middlewareGroups = [
        'web' => [
        ],

        'api' => [
        ],
    ];

https://github.com/laravel/laravel/blob/10.x/app/Providers/RouteServiceProvider.php#L31

        $this->routes(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });

A middleware group is applied to each.

In Laravel 11, these are hidden, so it's hard to understand.

1 like
ruthback's avatar

Thanks for the feedback!

The thing that bugs me about stateless requests is that the line gets a bit fuzzy when we start considering aspects like tokens that need to be stored somewhere in the database, even when there's no intention of making any 3rd-pty clients for the website. With Laravel in particular it seems much easier to use web.php most of the time as it will handle everything automatically, and can be used for most tasks anyway. But it just feels more appropriate to use API for certain tasks, if only just for organization purposes.

I haven't updated to Laravel 11 just yet but I will have to check the main differences and move on soon.

gych's avatar
gych
Best Answer
Level 29

@ruthback Its possible to use web routes for AJAX requests that are made within the same application but not for requests outside of your application. like when you use a front end or mobile app that is completely separated from your Laravel back end.

Please or to participate in this conversation.