PHP Development | Tutorial 16 | Laravel as an API Backend

by | Oct 12, 2025 | PHP Development, Web App Development | 0 comments

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 limiting
  • auth:sanctum → Token authentication
  • bindings → 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.php and api.php routes 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

Submit a Comment

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