Labs ICT
Pro Login

Building APIs

JSON responses, resources, and routing.

Building APIs in Laravel

Laravel makes building APIs straightforward. Routes, controllers, and JSON responses work together seamlessly. You can build a full REST API without any extra packages.

Returning JSON Responses

Use the json method to return JSON from any route or controller. Laravel automatically sets the correct headers.


Route::get('/api/users', function () {
    return User::all();
});
    

You can also use response()->json() to set the status code and headers manually.


return response()->json([
    'data' => $users,
    'meta' => ['total' => $total],
], 200);
    

API Routes

Laravel separates API routes into the routes/api.php file. These routes are automatically prefixed with /api and don't use session or CSRF middleware.


use Illuminate\Support\Facades\Route;

Route::prefix('v1')->group(function () {
    Route::get('/posts', [PostController::class, 'index']);
    Route::get('/posts/{post}', [PostController::class, 'show']);
    Route::post('/posts', [PostController::class, 'store']);
});
    

The RouteServiceProvider loads this file and applies the /api prefix.

API Resources

Resources transform your models into clean JSON structures. They give you full control over what fields appear in the response.


php artisan make:resource PostResource
    

Define the toArray method to control the output.


class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'body' => $this->body,
            'created_at' => $this->created_at,
        ];
    }
}
    
Try it Yourself →

Rate Limiting

Protect your APIs from abuse with rate limiting. Define rate limits in the RouteServiceProvider or directly in your routes.


use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

Route::middleware('throttle:60,1')->group(function () {
    Route::get('/api/posts', [PostController::class, 'index']);
});
    

The throttle middleware limits each user to 60 requests per minute. Customize the limits based on your needs.