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
apimiddleware group where web routes use thewebmiddleware group. - Api have the
apiprefix, thus routes from theapi.phpare prefixed withapi/.
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());
});
}
}