Default Background
RESTful APIs
3 min read

Creating RESTful APIs with Laravel

Building APIs is a core skill for modern backend developers, and Laravel—one of the most popular PHP frameworks—makes the process clean, efficient, and elegant. With its expressive syntax, powerful features, and built-in tools, Laravel provides everything you need to create robust, secure, and scalable RESTful APIs.

A

Author

5 months ago

Building APIs is a core skill for modern backend developers, and Laravel—one of the most popular PHP frameworks—makes the process clean, efficient, and elegant. With its expressive syntax, powerful features, and built-in tools, Laravel provides everything you need to create robust, secure, and scalable RESTful APIs.

In this post, we’ll walk through the fundamentals of using Laravel to build RESTful APIs, explore best practices, and highlight the features that make Laravel such a great choice for API development.

Why Use Laravel for APIs?

Laravel shines as an API framework thanks to its:

  • Elegant routing system
  • Resource controllers
  • Eloquent ORM for easy database interaction
  • Middleware for authentication and request filtering
  • Automatic serialization with API resources
  • Integrated tools like Laravel Sanctum, Passport, and validation

Whether you’re building a small service or a full-scale backend, Laravel makes API development fast and enjoyable.

Setting Up a New Laravel Project

If you haven’t created a project yet:

composer create-project laravel/laravel api-demo
cd api-demo
php artisan serve

Your development server will run at http://localhost:8000.

Routing: Defining API Endpoints

Laravel keeps API routes in routes/api.php. A simple example:

Route::get('/users', [UserController::class, 'index']);

Laravel automatically prefixes API routes with /api.

Using Resource Controllers

Resource controllers provide a clean structure for common REST actions such as index, store, update, and destroy.

Generate one with:

php artisan make:controller UserController --api

This creates a controller with methods tailored for API use.

Example controller methods:

public function index()
{
    return User::all();
}

public function store(Request $request)
{
    return User::create($request->all());
}

public function show(User $user)
{
    return $user;
}

public function update(Request $request, User $user)
{
    $user->update($request->all());
    return $user;
}

public function destroy(User $user)
{
    $user->delete();
    return response()->json(null, 204);
}

Request Validation

Laravel offers expressive validation for incoming data:

$request->validate([
    'name' => 'required|string|max:255',
    'email' => 'required|email|unique:users',
]);

If validation fails, Laravel automatically returns a JSON response with errors.

API Resources: Clean and Consistent JSON Responses

Instead of returning raw models, use Laravel API Resources to shape your responses.

Create a resource:

php artisan make:resource UserResource

Example resource:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'created_at' => $this->created_at->toDateString(),
    ];
}

Then return it:

return new UserResource($user);

Or for collections:

return UserResource::collection(User::all());

Authentication with Laravel Sanctum

To protect routes, Laravel Sanctum is one of the easiest solutions for token-based authentication.

Install Sanctum:

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Enable middleware in kernel.php, then issue tokens:

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

Protect routes:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Pagination and Filtering

Laravel makes it simple to paginate results:

return UserResource::collection(User::paginate(10));

And filtering is easily implemented with Eloquent query scopes or dedicated filter classes.

Error Handling

Laravel automatically returns structured JSON errors for validation and exceptions, but you can customize responses in:

app/Exceptions/Handler.php

This ensures your API maintains consistent error formatting.

Versioning Your API

A good practice for large-scale services:

/api/v1/users
/api/v2/users

Laravel supports grouping:

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

Testing Your API

Laravel has great support for API testing using PHPUnit + Test Helpers:

public function test_users_can_be_listed()
{
    $this->get('/api/users')
         ->assertStatus(200)
         ->assertJsonStructure([['id', 'name', 'email']]);
}

API tests help ensure a reliable, regression-free backend.

Conclusion

Laravel provides a first-class development experience for creating RESTful APIs. Its expressive syntax, built-in tools, and powerful ecosystem make it an ideal framework for both beginners and experienced developers.
 With routing, controllers, resources, validation, authentication, and testing all built into the framework, you can focus on building features rather than wiring boilerplate code.

If you’d like, I can also turn this into Markdown, shorten it, add code examples, or tailor the writing style to match your portfolio site.