Explain the web.php vs api.php routes files.

In Laravel, routes are defined in different files depending on their purpose.

The two most common files are web.php and api.php — both located in the routes/ folder.

1. web.php

Purpose: For routes that return HTML pages or views.

Middleware: Uses the web middleware group (handles sessions, CSRF protection, cookies, etc.).

Example:

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

When to Use:

Normal web pages

Forms with CSRF protection

Routes that need sessions


2. api.php

Purpose: For API routes that return data (usually JSON).

Middleware: Uses the api middleware group (stateless, no sessions or CSRF protection).

Example:

Route::get('/users', function () {
return ['name' => 'John', 'email' => 'john@example.com'];
});

When to Use:

REST APIs

Mobile app backends

Data exchange without views


Main Differences Table

Feature
web.php
api.php
Returns
HTML / Views
JSON / Data
Middleware
web (sessions, CSRF, cookies)
api (stateless)
CSRF Protection
Yes
No
Use For
Websites
APIs / Mobile Apps


Tip:

You can define API routes in web.php, but it’s better practice to keep them separate for cleaner code and security.

Comments