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.
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');
});
Normal web pages
Forms with CSRF protection
Routes that need sessions
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'];
});
REST APIs
Mobile app backends
Data exchange without views
Main Differences Table
Feature | | |
|---|---|---|
Returns | HTML / Views | JSON / Data |
Middleware | | |
CSRF Protection | Yes | No |
Use For | Websites | APIs / Mobile Apps |
You can define API routes in web.php, but it’s better practice to keep them separate for cleaner code and security.