Skip to content
Mehedi Hasan Sagor

// blog

Contract‑First Laravel APIs: OpenAPI Specs, Validation, and Security for Startups

Mehedi Hasan Sagor Nov 21, 2026 2 min read
Contract‑First Laravel APIs: OpenAPI Specs, Validation, and Security for Startups

Why a Contract‑First Approach Matters

When a startup ships an API, the first thing the client‑side team asks for is a clear contract. Without it, front‑end developers waste time guessing payload shapes, and QA struggles to write reliable tests. A contract‑first workflow flips the process: you write an OpenAPI (Swagger) definition before any controller code. The benefits are concrete:

  • Single source of truth – the spec drives documentation, validation, and test generation.
  • Early feedback – API designers can share the spec with stakeholders, get sign‑off, and avoid costly re‑work.
  • Consistency – every endpoint follows the same conventions for naming, pagination, and error handling.

Laravel does not enforce a contract‑first style out of the box, but the ecosystem provides tools that make it painless.

Defining the OpenAPI Specification

Start with a minimal openapi.yaml in the repository root. Keep it version‑controlled and treat it like any other source file.

openapi: 3.1.0
info:
  title: Acme Inventory API
  version: 1.0.0
servers:
  - url: https://api.acme.com/v1
paths:
  /products:
    get:
      summary: List products
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: per_page
          in: query
          schema:
            type: integer
            default: 20
      responses:
        '200':
          description: A paginated list of products
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProductCollection'
components:
  schemas:
    Product:
      type: object
      required: [id, name, price]
      properties:
        id:
          type: integer
        name:
          type: string
        price:
          type: number
          format: float
    ProductCollection:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/Product'
        meta:
          type: object
          properties:
            current_page:
              type: integer
            total_pages:
              type: integer

This file captures a simple GET /products endpoint with pagination. As your API grows, split the spec into multiple files and reference them with $ref to keep it manageable.

Generating Validation and Controllers Automatically

Writing request validation by hand is error‑prone. The goldspecdigital/laravel-swagger package can generate Laravel Form Request classes directly from the OpenAPI spec.

composer require goldspecdigital/laravel-swagger
php artisan swagger:generate

The command reads openapi.yaml and creates a app/Http/Requests/GetProductsRequest.php that contains rules derived from the parameters section. A typical generated request looks like:

<?php
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class GetProductsRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'page' => ['integer', 'min:1'],
            'per_page' => ['integer', 'between:1,100'],
        ];
    }
}

You can now type‑hint this request in your controller, and Laravel will automatically return a 422 response if validation fails.

public function index(GetProductsRequest $request)
{
    $validated = $request->validated();
    // Use $validated['page'] and $validated['per_page'] to query the DB
}

Keeping Controllers Thin

Because the spec already defines response schemas, you can use spatie/laravel-fractal or league/fractal to transform models into the exact JSON shape described in components.schemas. This eliminates hand‑rolled toArray methods and guarantees that the output matches the contract.

use League\Fractal\Manager;
use League\Fractal\Resource\Collection;
use App\Transformers\ProductTransformer;

public function index(GetProductsRequest $request)
{
    $products = Product::paginate($request->validated()['per_page']);
    $resource = new Collection($products->items(), new ProductTransformer());
    $data = (new Manager())->createData($resource)->toArray();

    return response()->json([
        'data' => $data,
        'meta' => [
            'current_page' => $products->currentPage(),
            'total_pages' => $products->lastPage(),
        ],
    ]);
}

Now the response format is guaranteed by both the transformer and the OpenAPI spec.

Securing the API End‑to‑End

A contract‑first workflow does not replace security. It makes it easier to audit and enforce security policies.

1. Authentication Strategy

For public APIs, Laravel Sanctum provides token‑based authentication that works well with SPAs and mobile clients.

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Add the auth:sanctum middleware to routes that require a user context.

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/orders', [OrderController::class, 'index']);
});

2. Scope‑Based Authorization

Define scopes in the OpenAPI spec using the security object. This documents which endpoints need which permissions and lets you enforce them in a single place.

security:
  - bearerAuth: []
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

In Laravel, map scopes to policies:

public function authorize()
{
    return $this->user()->tokenCan('order:read');
}

3. Rate Limiting and Throttling

Laravel's RateLimiter can be configured per route name. Tie the limit to the API key or user ID to prevent a single client from exhausting resources.

use Illuminate\Support\Facades\RateLimiter;

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

Apply the limiter via the throttle:api middleware on the API group.

4. Input Sanitization & Header Hardening

Even with generated validation, always sanitize strings that may be stored or rendered. Use Laravel's built‑in e() helper when echoing user‑generated content.

Add security‑focused headers with fruitcake/laravel-cors and spatie/laravel-csp to protect against XSS and click‑jacking.

// config/csp.php
return [
    'policy' => [
        'default-src' => "'self'",
        'script-src' => "'self'",
        // ... other directives
    ],
];

CI/CD Integration and Automated Contract Tests

The contract‑first workflow shines when you embed spec validation into the pipeline.

  1. Validate the spec – use swagger-cli or openapi-generator-cli to ensure the YAML is syntactically correct.
  2. Generate code – run php artisan swagger:generate as part of the build step.
  3. Run contract tests – tools like pact-foundation/pact-php or Dredd can execute the spec against a running Laravel instance and flag mismatches.

Example GitHub Actions snippet:

name: API Contract CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'
      - run: composer install --no-interaction --prefer-dist
      - run: php artisan migrate:fresh --seed
      - run: vendor/bin/phpunit
      - name: Validate OpenAPI spec
        run: npx @redocly/openapi-cli lint openapi.yaml
      - name: Run Dredd contract tests
        run: dredd openapi.yaml http://localhost:8000 --language phpunit

If the contract test fails, the pipeline blocks the merge, guaranteeing that the live API never drifts from its documented contract.

Takeaway: A Practical Checklist

  • Write the OpenAPI spec first and keep it version‑controlled.
  • Generate Form Request validation with goldspecdigital/laravel-swagger.
  • Transform responses to match the spec using Fractal or a similar serializer.
  • Secure every endpoint with Sanctum, scope checks, rate limiting, and CSP headers.
  • Add spec linting and contract tests to CI to enforce fidelity.

By treating the API definition as the primary artifact, startups gain speed, reduce bugs, and provide a professional experience to partners and internal teams alike. The upfront effort pays off the moment you need to onboard a new front‑end developer or expose the API to a third‑party service – they get a reliable contract, and you get confidence that the implementation stays in sync.

  • Laravel
  • Api
  • Security
  • Best Practices
  • Openapi