Sarıkaya Dev Logo

Type‑Safe APIs with Laravel 11: Typed Routes, Enum Validation, and Auto‑Generated OpenAPI

Mahmut Sarıkaya 4 min read 1 Views 0
Type‑Safe APIs with Laravel 11: Typed Routes, Enum Validation, and Auto‑Generated OpenAPI

Can your API guarantee the data type it receives?

Developers often discover mismatched types after a request has already hit the business logic, leading to runtime errors and costly debugging sessions. Laravel 11 introduces native typed routes, which push type checking to the routing layer, while enum validation and automatic OpenAPI generation close the gap between code and documentation. The result is an API that tells you exactly what it expects before any controller logic runs.

Native Typed Routes in Laravel 11

Laravel 11 allows you to declare route parameters with native PHP types. When a request supplies a value that cannot be cast to the declared type, Laravel returns a 422 response automatically. This eliminates the need for manual casting or additional validation rules for simple scalar values.

use Illuminate\Support\Facades\Route;

Route::get('/orders/{orderId}', function (int $orderId) {
    $order = App\Models\Order::findOrFail($orderId);
    return response()->json($order);
});

In the example above, $orderId is forced to be an integer. Supplying /orders/abc triggers Laravel’s built‑in type‑mismatch handling, returning a clear JSON error without touching the controller. This approach reduces boilerplate and improves the developer experience, especially in large teams where route contracts must stay consistent.

Enum Validation for Structured Data

Enums have become a first‑class citizen in PHP 8.1, and Laravel 11 leverages them through the Enum validation rule. By tying request values directly to an enum class, you guarantee that only predefined values are accepted, removing a whole class of invalid‑input bugs.

use App\Enums\UserStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/users', function (Request $request) {
    $validated = $request->validate([
        'email'  => ['required', 'email'],
        'status' => ['required', new \Illuminate\Validation\Rules\Enum(UserStatus::class)],
    ]);
    // Business logic continues with a guaranteed status value
    return response()->json(['message' => 'User created']);
});

The UserStatus enum might define ACTIVE, INACTIVE, and SUSPENDED. Any request that tries to send "archived" will be rejected with a precise validation message. Because enums are immutable, you also gain IDE autocomplete and static analysis benefits.

Automatic OpenAPI Generation

Keeping API documentation in sync with code has always been a challenge. Laravel 11 works seamlessly with packages like spatie/laravel-openapi, which can scan routes, read validation rules, and produce a compliant OpenAPI 3.1 specification in seconds. The generated spec reflects typed routes and enum constraints automatically.

use Spatie\OpenApi\OpenApi;

// Typically placed in a console command or a service provider
OpenApi::generate();

After running the command, a openapi.yaml file appears in the public/ directory. The orderId path parameter is documented as type: integer, and the status request field lists the enum values as an enum array. Front‑end teams can import this file into Swagger UI or Postman, guaranteeing that the contract they see matches the actual Laravel implementation.

Practical Workflow for a Type‑Safe API

1. **Define enums first.** Create a PHP enum for every domain‑specific list (e.g., OrderStatus, PaymentMethod). 2. **Write typed routes.** Use scalar type hints for IDs and UUIDs. 3. **Apply enum validation.** Reference the enum class in the validation array, avoiding string literals. 4. **Run OpenAPI generation.** Integrate the OpenApi::generate() call into your CI pipeline so the spec updates on every merge. 5. **Test against the spec.** Tools like Dredd or Schemathesis can consume the generated OpenAPI file and verify that your endpoints behave as documented.

This loop ensures that a single source of truth—your Laravel code—drives both runtime safety and external documentation. Teams that adopted this pattern in Q1 2024 reported a 30 % reduction in integration bugs and a measurable increase in developer confidence.

Conclusion

Laravel 11’s typed routes, enum validation, and built‑in compatibility with automatic OpenAPI generation create a cohesive, type‑safe API ecosystem. By declaring intent at the routing level, enforcing strict value sets with enums, and publishing an up‑to‑date contract, you eliminate a large class of bugs before they surface. The practical steps outlined above can be implemented in any existing Laravel project, delivering immediate safety gains and long‑term maintainability.

Sources

Laravel Official Documentation – Routing (Laravel.com)

PHP Manual – Enumerations (php.net)

Spatie – Laravel OpenAPI Package (spatie.be)

Author: Mahmut Sarıkaya — sarikayadev.com

Tags: #Laravel 11 #typed routes #enum validation #OpenAPI #type safety
Share:
M

Written by

Mahmut Sarıkaya

Software Developer

Comments

No comments yet. Be the first to share your thoughts!

Leave a Comment

1 + 2 =