Modern applications are often split into frontend (React, Vue, Flutter, Angular) and backend (API services). Laravel isnโt just for building full-stack web appsโitโs also a powerful API backend framework.
With built-in tools for routing, JSON responses, authentication, and resource transformations, Laravel makes it easy to expose APIs that power web apps, mobile apps, and third-party integrations.
For interviews, API-related questions test your ability to design RESTful services, handle JSON responses, and manage authentication.
Why Use Laravel for APIs?
- Clean Routing System โ Simple API endpoints in
routes/api.php. - JSON Responses by Default โ No need to configure output formats.
- Authentication โ Sanctum & Passport provide token-based security.
- Resources & Transformers โ Consistent, structured API responses.
- Middleware โ Throttling, auth, logging made easy.
Setting Up API Routes
All API routes go into routes/api.php.
use App\Http\Controllers\Api\UserController;
Route::get('/users', [UserController::class, 'index']);
Route::get('/users/{id}', [UserController::class, 'show']);
Route::post('/users', [UserController::class, 'store']);
๐ Unlike web.php, these routes are stateless (no sessions, no CSRF tokens).
Returning JSON Responses
In controllers:
public function index() { $users = User::all(); return response()->json($users); }
Or shorthand:
return User::all();
๐ Laravel automatically converts Eloquent collections to JSON.
API Resources (Transformers)
Instead of returning raw models, you can format responses with Resources.
php artisan make:resource UserResource
Generated file:
class UserResource extends JsonResource {
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
}
Controller:
return UserResource::collection(User::all());
๐ Ensures consistent API responses.
Handling API Requests
public function store(Request $request) { $validated = $request->validate([ 'name' => 'required|string|max:50', 'email' => 'required|email|unique:users', ]); $user = User::create($validated); return response()->json($user, 201); }
๐ Automatically returns JSON errors if validation fails.
Middleware for APIs
throttleโ Rate limitingauth:sanctumโ Token authenticationbindingsโ Route model binding
Example:
Route::middleware(['auth:sanctum'])->group(function () {
Route::get('/profile', [UserController::class, 'profile']);
});
Pagination in APIs
return UserResource::collection(User::paginate(10));
๐ Response automatically includes pagination metadata (links, total, per page).
API Versioning
Best practice: version your APIs for backward compatibility.
Route::prefix('v1')->group(function () {
Route::get('/users', [UserController::class, 'index']);
});
Route::prefix('v2')->group(function () {
Route::get('/users', [UserV2Controller::class, 'index']);
});
Common Beginner Mistakes
- Returning raw models without formatting โ API responses become messy.
- Forgetting to use status codes (200, 201, 422).
- Not paginating โ sending thousands of rows at once.
- Mixing
web.phpandapi.phproutes incorrectly. - Forgetting to protect APIs with auth middleware.
Sample Interview Questions & Answers
Q: How do you create an API in Laravel?
A: Define routes in routes/api.php, build controllers, return JSON responses (or use Resources).
Q: Whatโs the difference between web.php and api.php?
A: web.php uses session state and CSRF protection; api.php is stateless and optimized for JSON APIs.
Q: How does Laravel handle JSON responses?
A: Automatically converts Eloquent models and collections to JSON.
Q: What is an API Resource in Laravel?
A: A transformer class that formats API responses consistently.
Q: How do you implement rate limiting in APIs?
A: Using the throttle middleware (throttle:60,1 for 60 requests/minute).
Q: Why should you version your APIs?
A: To maintain backward compatibility when introducing breaking changes.
Mini Project Idea
๐ Build a Simple Task API:
- Endpoints: GET /tasks, POST /tasks, GET /tasks/{id}.
- Use Resource classes for structured JSON.
- Add pagination for tasks list.
- Protect POST /tasks with auth middleware.
Closing Note
Laravel is more than a web frameworkโitโs a powerful API backend platform. With resources, middleware, and validation, it enables you to build scalable APIs that power modern apps.
Laravel Framework Mastery
Laravel Migrations & Database Management
โ Manage your database schema efficiently with Laravel migrations, seeders, and factories for smooth development and testing
Laravel Validation & Form Requests
โ Ensure secure and reliable user input by leveraging Laravelโs robust validation rules and custom form request classes
Laravel Authentication & Authorization
โ Secure your web applications effortlessly by implementing Laravelโs robust authentication and authorization features for users and roles
























0 Comments