A REST API lets mobile apps, React or Vue frontends and other servers use your data as JSON. Laravel makes APIs very easy.
Set up
In Laravel 11 and later, run php artisan install:api. It creates routes/api.php and installs Sanctum for token login. Every route in this file gets the /api prefix.
API resource routes
Route::apiResource('posts', PostController::class); creates five routes — like resource, but without the create and edit form pages:
GET /api/posts— listPOST /api/posts— createGET /api/posts/{post}— show onePUT /api/posts/{post}— updateDELETE /api/posts/{post}— delete
Returning JSON
Return a model or collection and Laravel converts it to JSON. Use response()->json($data, 201) to set a status code. Common codes: 200 OK, 201 Created, 204 No Content, 404 Not Found, 422 validation failed.
Protecting the API
Wrap routes in auth:sanctum and send the token in the Authorization: Bearer <token> header. Test endpoints with Postman or curl.
Example
<?php
// routes/api.php
Route::apiResource('posts', PostController::class)->only(['index', 'show']);
Route::middleware('auth:sanctum')->group(function () {
Route::apiResource('posts', PostController::class)->except(['index', 'show']);
});
// app/Http/Controllers/PostController.php
public function index()
{
return Post::latest()->paginate(10);
}
public function store(Request $request)
{
$data = $request->validate(['title' => 'required|max:255', 'body' => 'required']);
$post = $request->user()->posts()->create($data);
return response()->json($post, 201);
}
public function destroy(Post $post)
{
$post->delete();
return response()->noContent(); // 204
}
GET /api/posts returns JSON like {"data":[{"id":1,"title":"Hello Eloquent",...}],"current_page":1,...}. Creating and deleting need a Sanctum token; invalid input returns status 422 with the errors as JSON.