0Pricing
PHP Academy · Lesson

API Routes and Resource Controllers

Register RESTful routes and generate resource controllers with Artisan.

API Routes and Resource Controllers is a free PHP Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

API Routes in Laravel

Define API routes in routes/api.php. These routes are automatically prefixed with /api and use the api middleware group (stateless — no session/cookies).

Basic API Route

Return JSON from a closure.

<?php
Route::get("/users/{id}", function (int $id) {
    $user = User::findOrFail($id);
    return response()->json($user);
});

API Resource Routes

Route::apiResource() registers 5 RESTful routes (skipping create and edit which render forms).

<?php
// routes/api.php
use App\Http\Controllers\Api\UserController;

Route::apiResource("users", UserController::class);
// GET /api/users           → index
// POST /api/users          → store
// GET /api/users/{user}    → show
// PUT /api/users/{user}    → update
// DELETE /api/users/{user} → destroy

Generating an API Controller

Use the --api flag to generate a controller without create and edit methods.

$ php artisan make:controller Api/UserController --api --model=User

API Controller Example

An API controller returns JSON responses.

<?php
namespace App\Http\Controllers\Api;

class UserController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json(User::paginate(15));
    }

    public function show(User $user): JsonResponse
    {
        return response()->json($user);
    }

    public function store(StoreUserRequest $request): JsonResponse
    {
        $user = User::create($request->validated());
        return response()->json($user, 201);
    }

    public function destroy(User $user): JsonResponse
    {
        $user->delete();
        return response()->json(null, 204);
    }
}

HTTP Status Codes

Return appropriate status codes: 200 (OK), 201 (Created), 204 (No Content), 400 (Bad Request), 401 (Unauthorized), 403 (Forbidden), 404 (Not Found), 422 (Unprocessable Entity).

Form Request Validation

Use Form Requests for clean, reusable validation rules.

$ php artisan make:request StoreUserRequest

StoreUserRequest Example

Define rules and authorization in the request class.

<?php
class StoreUserRequest extends FormRequest
{
    public function authorize(): bool { return true; }
    public function rules(): array {
        return [
            "name"  => "required|string|max:255",
            "email" => "required|email|unique:users",
        ];
    }
}

Grouped API Routes

Group API routes with prefix and namespace.

<?php
Route::prefix("v1")->middleware("auth:sanctum")->group(function () {
    Route::apiResource("posts", PostController::class);
    Route::apiResource("users", UserController::class);
});

except() and only()

Exclude or restrict specific routes from a resource registration.

<?php
Route::apiResource("users", UserController::class)->only(["index", "show"]);
Route::apiResource("posts", PostController::class)->except(["destroy"]);

Nested Resources

Register nested resource routes for related models.

<?php
Route::apiResource("users.posts", UserPostController::class);
// GET /api/users/{user}/posts/{post}

Summary

Use Route::apiResource() for RESTful API routes in routes/api.php. Generate controllers with --api. Return JSON with proper HTTP status codes. Validate with Form Requests.

Quick Check

How many routes does apiResource() register?

Frequently asked questions

Is the “API Routes and Resource Controllers” lesson free?

Yes — the full text of “API Routes and Resource Controllers” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “API Routes and Resource Controllers”?

Register RESTful routes and generate resource controllers with Artisan. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “API Routes and Resource Controllers” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. API Routes and Resource Controllers
  2. API Resources and JSON Responses
  3. Authentication with Laravel Sanctum
  4. Rate Limiting and API Versioning
← Back to PHP Academy