How to Create a REST API in Laravel 13

Build a complete REST API in Laravel 13 from scratch โ€” Sanctum authentication, API resources, validation, and testing โ€” with working code for every step.

RH Raja HunainAuthor 21 Nov 2026 8 min read 25 views
Table of Contents
Share

A REST API lets other apps talk to your Laravel app. A mobile app, a JavaScript front-end, or another company's system cannot read your Blade pages โ€” they want data, in JSON. An API gives them exactly that.

Laravel 13 makes this easy. One command installs the API scaffolding with Sanctum, one route line creates all five CRUD endpoints, and API Resources shape the JSON for you. In this tutorial you will build a working REST API for blog posts โ€” with token authentication โ€” from an empty project.

What You Need

  • PHP 8.2 or higher
  • Composer installed globally
  • A fresh Laravel 13 project (or an existing one)
  • MySQL or SQLite for the database

Step 1: Create the Project and Install the API

Create a new Laravel project and enter its folder:

composer create-project laravel/laravel laravel-rest-api
cd laravel-rest-api

In Laravel 13, API routes do not exist by default โ€” install:api creates them and installs Laravel Sanctum for token authentication at the same time:

php artisan install:api
php artisan migrate

This creates routes/api.php and adds Sanctum's tables. From now on, every route in that file automatically gets the /api prefix and the api middleware group.

Step 2: Create the Model and Migration

Our API will manage blog posts. Generate a model with its migration:

php artisan make:model Post -m

Open the migration and add the fields a post needs:

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('body');
    $table->timestamps();
});

Run the migration, then allow mass assignment in app/Models/Post.php:

protected $fillable = ['title', 'body'];

Skip the $fillable line and Laravel throws a MassAssignmentException the first time you create a post through the API โ€” a very common beginner error.

Step 3: Shape the JSON with an API Resource

Never return a raw Eloquent model from an API โ€” it can leak internal fields. An API Resource decides exactly what leaves your app:

php artisan make:resource PostResource
public function toArray(Request $request): array
{
    return [
        'id' => $this->id,
        'title' => $this->title,
        'body' => $this->body,
        'created_at' => $this->created_at->toDateTimeString(),
    ];
}

Now every post your API returns looks the same.

Step 4: Validate Requests with a Form Request

Validation belongs in a dedicated Form Request class, not inside the controller:

php artisan make:request StorePostRequest
public function authorize(): bool
{
    return true;
}

public function rules(): array
{
    return [
        'title' => 'required|string|max:255',
        'body' => 'required|string',
    ];
}

Two details matter here. First, authorize() must return true โ€” if you leave the default false, every request fails with "This action is unauthorized". Second, when validation fails on an API route, Laravel automatically returns a clean 422 JSON response with the error messages.

Create an UpdatePostRequest the same way, with the same rules.

Step 5: Create the API Controller

Generate a controller built for APIs โ€” only the five methods an API needs, no create or edit, because APIs have no HTML forms:

php artisan make:controller Api/PostController --api
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePostRequest;
use App\Http\Requests\UpdatePostRequest;
use App\Http\Resources\PostResource;
use App\Models\Post;

class PostController extends Controller
{
    public function index()
    {
        return PostResource::collection(Post::latest()->paginate(10));
    }

    public function store(StorePostRequest $request)
    {
        $post = Post::create($request->validated());
        return new PostResource($post);
    }

    public function show(Post $post)
    {
        return new PostResource($post);
    }

    public function update(UpdatePostRequest $request, Post $post)
    {
        $post->update($request->validated());
        return new PostResource($post);
    }

    public function destroy(Post $post)
    {
        $post->delete();
        return response()->json(['message' => 'Post deleted.'], 200);
    }
}

Notice three things. Route model binding (Post $post) automatically returns a 404 JSON response when the id does not exist. paginate(10) keeps list responses small instead of dumping the whole table. And store() returns a 201 Created status automatically โ€” the correct status code for a successful POST.

Step 6: Register the Routes

One line in routes/api.php creates all five endpoints:

use App\Http\Controllers\Api\PostController;

Route::apiResource('posts', PostController::class);

That single line maps GET /api/posts, POST /api/posts, GET /api/posts/{id}, PUT /api/posts/{id} and DELETE /api/posts/{id}. Run php artisan route:list --path=api to see them all.

Version your API from day one, so you can change it later without breaking existing clients:

Route::prefix('v1')->group(function () {
    Route::apiResource('posts', PostController::class);
});

Your endpoints then live under /api/v1/posts.

Step 7: Test the API

Start the server with php artisan serve and create a post with curl:

curl -X POST http://localhost:8000/api/posts \
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  -d '{"title": "Hello API", "body": "My first post through the API."}'

You should get a 201 response with your post as JSON. Now list all posts:

curl http://localhost:8000/api/posts -H "Accept: application/json"

Try sending an empty title and you will get a 422 response listing the validation error; try GET /api/posts/999 and you get a 404. These status codes are the API's tone of voice โ€” 200 for reads and updates, 201 for a successful create, 404 when the resource is missing, 422 when the data fails validation.

Step 8: Protect the API with Sanctum Tokens

Public read endpoints are fine, but creating, updating and deleting posts should require a login. Sanctum issues a personal API token after login, which the client sends back as a Bearer token.

First, add the HasApiTokens trait to the User model:

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

Then create an AuthController with register and login methods. Login checks the password and issues a token:

public function login(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    $user = User::where('email', $request->email)->first();

    if (! $user || ! Hash::check($request->password, $user->password)) {
        return response()->json(['message' => 'Invalid credentials.'], 401);
    }

    $token = $user->createToken('api-token')->plainTextToken;

    return response()->json(['token' => $token, 'user' => $user]);
}

Register the auth routes as public, and wrap the write routes in the auth:sanctum middleware:

Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('posts', PostController::class);
    Route::post('/logout', [AuthController::class, 'logout']);
});

A request without a token gets 401 Unauthenticated; one with Authorization: Bearer <token> passes through. Logout deletes the current token with $request->user()->currentAccessToken()->delete().

Common Errors and Their Fixes

Error Cause Fix
Route [login] not defined Laravel tried to redirect to a web login page Always send the header Accept: application/json with API requests
MassAssignmentException The field is not in $fillable Add the field to $fillable in the model
401 Unauthenticated Missing or expired token Log in again and send Authorization: Bearer <token>
This action is unauthorized Form Request authorize() returns false Return true from authorize()
404 Not Found The id does not exist, or the route is wrong Check the id, and run php artisan route:list
405 Method Not Allowed Wrong HTTP verb for the route Use GET for reading, POST for creating, PUT for updating, DELETE for deleting

The first error in this table confuses almost every beginner. It is not a routing problem โ€” Laravel treated your request as a browser request and tried to send you to a login page that does not exist. The Accept: application/json header tells Laravel this is an API call, and it answers with JSON instead.

Best Practices Worth Following

  • Always return Resources, never raw models. You control exactly which fields leave the server.
  • Paginate every list endpoint. Post::all() on a table with ten thousand rows is a slow response and a big bill.
  • Version your API (/api/v1/...) from the first release, so breaking changes never break existing apps.
  • Use the right status codes. 200 for success, 201 for created, 422 for validation errors, 404 for missing resources, 401 for missing authentication.
  • Keep validation in Form Requests and business rules out of controllers.

Frequently Asked Questions

Do I need Sanctum for a public API? No. If anyone may read the data, leave the GET routes outside the auth:sanctum group and protect only the write routes.

Sanctum or Passport? Sanctum for first-party SPAs, mobile apps and simple token APIs. Passport only when you need a full OAuth2 server with third-party clients.

How do I test an API without Postman? Use curl from the terminal, as shown above, or Laravel's built-in feature tests with $this->postJson('/api/posts', [...]).

Can one controller serve both web and API? Technically yes, but do not. Web controllers return views and redirects; API controllers return JSON and status codes. Mixing them makes both harder to maintain.

Conclusion

A complete REST API in Laravel 13 needs only a handful of pieces: php artisan install:api for the scaffolding and Sanctum, a model with a migration, an API Resource to shape the JSON, Form Requests for validation, an --api controller, and one apiResource route line. Add token authentication with auth:sanctum and test every endpoint with curl.

Build this posts API once, and you have the pattern for every resource your app will ever need: the same five endpoints, the same validation, the same token protection, just a different model.

Was this helpful? 0 likes Login to like & bookmark
RH

Written by

Raja Hunain

Full Stack Developer at Raja Dev Solutions โ€” writes about real development work, the errors he faced and exactly how he fixed them, plus practical Laravel, PHP, JavaScript and MySQL tutorials.

More about the author

Comments (0)

No comments yet. Be the first to comment.

Leave a comment

Comments are moderated and appear after approval.

Keep reading

Related Articles