What Is a REST API in Laravel

A REST API is one of the most common ways applications communicate with each other. Modern web and mobile applications rely heavily on APIs for exchanging data. Whether you are building a mobile application, a JavaScript front-end, a third-party integration, or a microservice architecture, REST APIs are essential. Laravel, being one of the most powerful PHP frameworks, provides everything needed to create clean, scalable, and well-structured REST APIs.

This help you understand REST APIs deeply within the Laravel ecosystem. You will learn what REST means, how APIs work, how Laravel supports them, how to create routes, controllers, resources, validation, authentication, pagination, error handling, best practices, versioning, and more.

By the end of this article, you will know exactly how to build robust and scalable REST APIs using Laravel.

Understanding the Concept of REST

REST stands for Representational State Transfer.
It is an architectural style used for designing networked applications. REST APIs follow a set of constraints and use HTTP methods for communication.

Key concepts in REST:

  • Clients send requests
  • Server returns responses
  • Communication is stateless
  • Data is exchanged in formats like JSON
  • A uniform interface is used
  • Resources are identified by URLs

REST is not a protocol, but a design style.


What Is a REST API

A REST API is an application programming interface that uses HTTP requests to perform actions on server resources. Each endpoint represents a resource, and each HTTP method represents an action.

For example, the resource “posts” can be accessed at:

GET /api/posts

HTTP methods:

  • GET → fetch data
  • POST → create data
  • PUT → update data
  • PATCH → partial update
  • DELETE → delete data

REST APIs are widely used because they are:

  • Simple
  • Fast
  • Scalable
  • Stateless
  • Easy to integrate

Why Use Laravel for REST APIs

Laravel is highly suited for building REST APIs due to:

  • Clean routing
  • Eloquent ORM
  • Request validation
  • API resources
  • Middleware support
  • Built-in authentication (Sanctum, Passport)
  • Easy JSON handling
  • Exception handling
  • Simple controller structure

Laravel provides a robust foundation for developing professional APIs in very little time.


Folder Structure for Laravel REST APIs

When building APIs, focus on specific folders:

routes/api.php
app/Models
app/Http/Controllers
app/Http/Resources

Routes are defined in api.php, and controllers inside:

app/Http/Controllers/API

This structure helps separate API logic from web logic.


API Routes in Laravel

Laravel provides a dedicated file for API routes:

routes/api.php

Example route:

Route::get('/posts', [PostController::class, 'index']);

Routes in this file are automatically prefixed with /api.

This means:

/posts

becomes:

/api/posts

Creating a Model for REST API

Create a Post model for demonstration:

php artisan make:model Post -m

This creates:

  • Model: app/Models/Post.php
  • Migration file

Edit migration:

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

Run migrations:

php artisan migrate

Creating a Controller for REST API

Create an API controller:

php artisan make:controller API/PostController --api

This creates a controller with methods:

  • index
  • store
  • show
  • update
  • destroy

These match REST API operations.


Building RESTful Methods in the Controller

Let us build the POST CRUD API.


The Index Method (GET)

Fetch all posts:

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

Returns JSON:

[
{
    "id": 1,
    "title": "First Post",
    "content": "This is a test"
}
]

The Store Method (POST)

Create a new post:

public function store(Request $request)
{
$post = Post::create([
    'title' => $request->title,
    'content' => $request->content
]);
return response()->json($post, 201);
}

Make fields fillable:

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

API route:

Route::post('/posts', [PostController::class, 'store']);

The Show Method (GET)

Get a specific post:

public function show($id)
{
return Post::findOrFail($id);
}

Route:

Route::get('/posts/{id}', [PostController::class, 'show']);

The Update Method (PUT)

Update a post:

public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
$post->update([
    'title' => $request->title,
    'content' => $request->content
]);
return response()->json($post);
}

Route:

Route::put('/posts/{id}', [PostController::class, 'update']);

The Destroy Method (DELETE)

Delete a post:

public function destroy($id)
{
$post = Post::findOrFail($id);
$post->delete();
return response()->json(null, 204);
}

Route:

Route::delete('/posts/{id}', [PostController::class, 'destroy']);

Validating Requests in REST API

Use Laravel validation for secure APIs.

$request->validate([
'title' => 'required|min:3',
'content' => 'required'
]);

Add to store:

public function store(Request $request)
{
$request->validate([
    'title' => 'required',
    'content' => 'required'
]);
return Post::create($request->all());
}

Validation makes APIs reliable and secure.


Returning JSON Responses

Laravel automatically converts arrays and models to JSON.

Explicit JSON response:

return response()->json([
'message' => 'Post created successfully'
], 201);

Structured format example:

return [
'status' => true,
'data' => $post
];

Using API Resources for Clean Output

API Resources help format JSON responses.

Create a resource:

php artisan make:resource PostResource

Inside resource:

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

Use it:

return new PostResource($post);

For collection:

return PostResource::collection(Post::all());

This makes APIs structured and professional.


Handling Errors in REST APIs

Common error responses:

Not found:

return response()->json(['error' => 'Post not found'], 404);

Validation errors are automatic:

422 Unprocessable Entity

Unauthorized:

return response()->json(['error' => 'Unauthorized'], 401);

Laravel’s exception handler already returns JSON for API requests.


Authentication for REST APIs

REST APIs often need token-based authentication.

Laravel provides:

  • Sanctum (simple token auth)
  • Passport (OAuth2)

Using Sanctum:

composer require laravel/sanctum
php artisan sanctum:install
php artisan migrate

Generate token:

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

Protect routes:

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

Using Middleware in REST APIs

Middleware protects API endpoints.

Examples:

Authentication:

Route::middleware('auth:sanctum')->get('/posts', ...);

Throttle:

Route::middleware('throttle:60,1')->get('/posts', ...);

Custom middleware can also be applied.


Pagination in REST APIs

API responses should not return large datasets.

Laravel pagination:

return Post::paginate(10);

Responds with:

  • data
  • current_page
  • total
  • links

Resource pagination:

return PostResource::collection(Post::paginate(10));

Filtering, Searching, and Sorting

Add search:

Post::where('title', 'like', '%'.$request->search.'%')->get();

Sorting:

Post::orderBy('created_at', 'desc')->get();

Filtering:

Post::where('category', $request->category)->get();

APIs become powerful with filters.


API Versioning

Versioning helps maintain backward compatibility.

Routes:

Route::prefix('v1')->group(function () {
Route::get('/posts', ...);
});

Later:

Route::prefix('v2')->group(function () {
Route::get('/posts', ...);
});

Versioning prevents breaking old apps.


Rate Limiting in REST APIs

Protect your API from spam:

Route::middleware('throttle:100,1')->group(function () {
// API routes
});

Users can have different rate limits.


CORS for REST APIs

APIs often connect with front-end apps like React or Vue.

Enable CORS:

config/cors.php

Common settings:

'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],

API Security Best Practices

Secure your REST API by:

  • Using HTTPS
  • Enabling authentication
  • Validating all inputs
  • Limiting requests
  • Sanitizing data
  • Using API resources
  • Avoiding sensitive data exposure
  • Applying authorization policies
  • Logging important actions

Security should be treated seriously.


Using Collections in API Responses

Collections help transform many records:

return PostCollection::make(Post::all());

Large datasets need structured transformation.


Testing REST APIs

Laravel includes API testing tools.

Basic test example:

public function test_posts_list()
{
$response = $this->get('/api/posts');
$response->assertStatus(200);
}

Testing is crucial for maintaining quality.


Example of a Complete Laravel REST API Flow

Routes:

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

Controller methods:

  • index → list
  • store → create
  • show → fetch
  • update → update
  • destroy → delete

Resource for output formatting
Middleware for protection
Validation for security
JSON responses for consistency


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *