Laravel RESTful APIs best practices

Laravel RESTful APIs best practices

Laravel RESTful API Best Practices

Table of Contents

  • Introduction

  • Use Proper HTTP Methods

  • Leverage API Resource Routes

  • Use Eloquent API Resources

  • Return JSON Responses

  • Use Accurate HTTP Status Codes

  • Simplify Auth with Sanctum or Passport

  • Avoid Changing Endpoint Paths

Introduction

Building reliable APIs is essential for backend development, especially in modern apps like SPAs and mobile applications. Laravel provides excellent tools to structure APIs cleanly. This guide covers best practices, not API basics, so some experience is expected.

1. Use Proper HTTP Methods

Use HTTP verbs correctly to reflect the action being performed:

ActionHTTP Method
Read dataGET
Create dataPOST
Update dataPUT/PATCH
Delete dataDELETE

Example in Laravel:

Route::get('/posts', [PostController::class, 'index']); Route::get('/posts/{post}', [PostController::class, 'show']); Route::post('/posts', [PostController::class, 'store']); Route::put('/posts/{post}', [PostController::class, 'update']); Route::delete('/posts/{post}', [PostController::class, 'destroy']);

2. Leverage API Resource Routes

Laravel simplifies routing with apiResource, which generates only API-relevant routes (no create or edit):

Route::apiResource('photos', PhotoController::class);

For multiple resources:

Route::apiResources([ 'photos' => PhotoController::class, 'posts' => PostController::class, ]);

Use the --api flag to create an API-ready controller:

php artisan make:controller PhotoController --api

3. Use Eloquent API Resources

API Resources transform models into JSON structures. Create them with:

php artisan make:resource UserResource

Customize output using the toArray method:

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

Use resources in routes:

return new UserResource(User::findOrFail($id));

Or return collections:

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

4. Return JSON Responses

Laravel automatically formats resource responses as JSON. For manual JSON responses:

return response()->json(['foo' => 'bar']);

5. Use Accurate HTTP Status Codes

Use proper status codes to reflect the API's behavior:

StatusMeaning
200OK
201Created
204No Content (Deleted)
401Unauthorized (Login needed)
403Forbidden
404Not Found
500Internal Server Error

Examples:

return response(['message' => 'Created'], 201); response()->noContent(); // for 204 abort(404); // resource not found

6. Simplify Auth with Sanctum or Passport

Laravel Sanctum: Lightweight and ideal for SPAs or mobile apps.

Laravel Passport: OAuth2-based and suitable for large-scale or third-party authentication.

Start with Sanctum. If your app grows and needs OAuth, migrate to Passport.

7. Avoid Changing Endpoint Paths

Avoid using the route() helper in your tests. Why? If a route path changes, the test may still pass even though your frontend breaks.

Bad:

$this->get(route('foo'))->assertOk();

Good:

$this->get('/foo')->assertOk();

This way, if you rename /foo, your test will fail—helping you catch errors early.

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close