Join my Laravel for REST API's course on Udemy πŸ‘€

Difference between web and api routes in Laravel

July 21, 2022  ‐ 2Β min read

After creating a brand new Laravel (I'm using v9) project you'll find multiple files in the routes directory.

laravel-project $ tree routes/
routes/
β”œβ”€β”€ api.php
β”œβ”€β”€ channels.php
β”œβ”€β”€ console.php
└── web.php

The channels.php file is for broadcasting and console.php for command closures. The other two, api.php and web.php, are pretty similar and both for web routes. But how are they different? For this we need to reach for the RouteServiceProvider (see below).

In the boot() method of the RouteServiceProvider we see that both the api and web routes are registered. They are registered with a couple differences though.

As you can see below there are three notable differences:

  • There is rate limiting configured for api routes.
  • Api routes use the api middleware group where web routes use the web middleware group.
  • Api have the api prefix, thus routes from the api.php are prefixed with api/.

The different middleware groups can be found in app/Http/Kernel.php.

<?php

// ...

class RouteServiceProvider extends ServiceProvider
{
    // ..

    /**
     * Define your route model bindings, pattern filters, and other route configuration.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

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

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

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });
    }
}