API Development

Interview Questions: Resources, Sanctum, and Versioning

Q1: What are API Resources?

Concept: A transformation layer that sits between your Eloquent models and the JSON response returned to the API user.

Benefit: It allows you to format the output, rename keys, cast types, and include relationships conditionally, ensuring your internal database structure isn't exposed directly.

public function toArray($request) {
    return [
        'id' => $this->id,
        'full_name' => $this->first_name . ' ' . $this->last_name,
        'email' => $this->email,
    ];
}

Q2: Explain Laravel Sanctum vs Passport.

Sanctum: Lightweight authentication system for SPAs (using cookies) and simple mobile APIs (using tokens). It is the default and recommended for most use cases.

Passport: Full OAuth2 server implementation. Use it only if you need to support third-party clients (like "Login with Google" but for your own app).

Q3: How do you handle API Versioning?

URI Versioning: The most common approach (e.g., /api/v1/users).

Implementation: You can define route groups with prefixes in routes/api.php or separate route files entirely.

Q4: How do you implement Rate Limiting in Laravel?

Mechanism: Laravel uses the RateLimiter facade and middleware to restrict the number of requests a user can make within a given timeframe.

Configuration: Defined in App\Providers\AppServiceProvider (or RouteServiceProvider in older versions).

RateLimiter::for('api', function (Request $request) {
    return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});

Usage: Apply the throttle:api middleware to your routes.

Q5: How do you document your API?

Tools: The most popular tools are Scribe and L5-Swagger.

Scribe: Generates documentation automatically by analyzing your routes and docblocks. It creates a static HTML page that looks like Stripe's API docs.

Swagger/OpenAPI: Uses annotations in your controller methods to generate an OpenAPI spec file, which can be rendered via Swagger UI.

Q6: How do you handle API Exceptions consistently?

Problem: Default Laravel error pages (HTML) are not suitable for JSON APIs.

Solution: Modify the register method in bootstrap/app.php (Laravel 11) or the Handler.php file (older versions) to intercept exceptions and return JSON responses.

// Laravel 11 bootstrap/app.php
->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (NotFoundHttpException $e, Request $request) {
        if ($request->is('api/*')) {
            return response()->json(['message' => 'Record not found.'], 404);
        }
    });
})