Advertisement
Google Ad Slot: content-top
Laravel API Routes
Laravel makes it very easy to build REST APIs.
Unlike web routes, API routes are separated because APIs usually:
- Return JSON responses instead of HTML views.
- Do not use sessions or CSRF protection by default (stateless).
- Are mostly consumed by frontend apps (React, Vue, Angular, Mobile Apps).
Create Route:
Laravel don't have api.php file. You should create in routes folder
api.php (routes/api.php):
<?php
use Illuminate\Support\Facades\Route;
Route::get('/hello', function () {
return response()->json(['message' => 'Hello from API!']);
});
This means:
- No session state
- No CSRF token
- JSON response by default
Register Route:
you should register api.php file in bootstrap\app.php
app.php (bootstrap\app.php)
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();
Install Postman:
- Postman is a software tool used to test APIs (Application Programming Interfaces).
- It helps developers send requests (like GET, POST, PUT, DELETE) to an API and see the response.
- You can think of it like a browser for APIs.
- A browser is used to visit websites.
- Postman is used to visit and test APIs.
Install postman Link
Run route in Postman:
Run http://127.0.0.1:8000/api/hello in postman in prefix after url should come api