Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

API First Development Workflow

By Kokil Thapa | Last reviewed: September 2026

Your mobile app, admin dashboard, and partner integrations all need the same data. An API First Development Workflow solves that by designing the contract before anyone writes backend or frontend code. You agree on endpoints, request shapes, error formats, and auth early. That cuts rework when clients assume different field names. For teams on Laravel 13 or Symfony 8.1, this approach is practical—not theoretical.

In my experience on client projects, skipping the contract phase causes the worst integration delays. Payment callbacks, document uploads, and booking flows break when each team guesses the payload. Start with OpenAPI and pair it with contract tests from day one. If you need help scoping endpoints, see our API development service in Nepal.

What Is an API First Development Workflow?

API first means the specification is the source of truth. You write or generate an OpenAPI 3 document that describes paths, parameters, schemas, and error responses. Backend and frontend teams then build against that file—not against verbal agreements in Slack.

Code first is the opposite. A developer ships endpoints, then documents them afterward. That works for internal tools with one consumer. It fails when three clients need the same API and discover mismatches during QA.

The workflow has four repeating phases: design the contract, mock and review, implement with validation, then publish and version. Each release cycle revisits the spec before code changes land.

API First Development Workflow1. DesignOpenAPI spec2. MockPrism server3. BuildLaravel API4. PublishDocs + versionParallel consumers during mock phaseWeb appMobile appPartners
Four-phase API First Development Workflow: design, mock, build, and publish with parallel client development

On a legal-tech portal I built, the client portal, public site, and admin panel all consumed one API. Defining booking and document endpoints upfront let the Vue admin and Laravel backend progress in parallel. The alternative—building the admin against live endpoints that changed weekly—would have burned a sprint on rework.

API first also improves technical SEO for public JSON feeds and headless content. Search engines never crawl your API directly, but stable URL patterns and documented response shapes help partner integrations that drive referral traffic.

How Do You Design an API Contract Before Writing Code?

Start with user stories, then translate them into resources and operations. A booking system needs appointments, availability slots, and customers—not fifty random RPC-style endpoints named after internal class methods.

Follow REST naming conventions. Use nouns for resources, HTTP verbs for actions, and consistent plural paths. Keep error bodies uniform so every client parses failures the same way.

Define your OpenAPI file structure

Store the spec in version control at docs/openapi.yaml. Split large APIs into reusable component schemas. Reference them with $ref so you do not duplicate field definitions across endpoints.

openapi: 3.1.0
info:
  title: Booking API
  version: 1.0.0
paths:
  /v1/appointments:
    post:
      operationId: createAppointment
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AppointmentCreate'
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Appointment'
        '422':
          $ref: '#/components/responses/ValidationError'
components:
  schemas:
    AppointmentCreate:
      type: object
      required: [service_id, starts_at]
      properties:
        service_id:
          type: integer
        starts_at:
          type: string
          format: date-time

Validate the YAML in CI before merge. Use the official OpenAPI Specification as your reference. A broken spec blocks mock servers and codegen tools downstream.

Run a quick syntax check locally with a JSON formatter after converting YAML fragments. Small typos in nested schemas are easy to miss in a 400-line file.

Run a contract review meeting

Schedule a 60-minute review with backend, frontend, and QA. Walk through each endpoint with example payloads. Ask three questions for every route:

  • What happens when the resource does not exist?
  • What validation errors return 422, and what shape do they take?
  • Which fields are required at create vs update?

Document auth requirements in the same spec. Note whether routes need Bearer tokens, API keys, or session cookies. Ambiguity here causes the most production auth bugs I see on enterprise applications.

Contract Design FlowUser storiesWhat users needResourcesREST nouns + verbsOpenAPI YAMLSchemas + pathsTeam review checklistError shapesAuth scopePaginationIdempotencyVersion prefix
API contract design flow: user stories become REST resources, then an OpenAPI file reviewed against a team checklist

How Do You Implement API First Development in Laravel?

Laravel 13 on PHP 8.3 is a strong fit for contract-first work. You keep the OpenAPI file authoritative, then wire routes and Form Requests to match it. Laravel 12 on PHP 8.2 follows the same pattern if you have not upgraded yet.

Step 1: Stand up a mock server

Install Prism or Stoplight Mock. Point it at your spec and give frontend developers a base URL today—not next sprint.

npx @stoplight/prism-cli mock docs/openapi.yaml --port 4010

Frontend teams hit http://localhost:4010/v1/appointments with example responses from the spec. Backend work proceeds without blocking UI progress.

Step 2: Implement routes to match the contract

Define versioned routes in routes/api.php. Use API resources for consistent response shapes. Align validation rules in Form Requests with OpenAPI constraints.

// routes/api.php
Route::prefix('v1')->middleware('auth:sanctum')->group(function () {
    Route::apiResource('appointments', AppointmentController::class)
        ->only(['index', 'store', 'show']);
});

// app/Http/Requests/StoreAppointmentRequest.php
public function rules(): array
{
    return [
        'service_id' => ['required', 'integer', 'exists:services,id'],
        'starts_at'  => ['required', 'date', 'after:now'],
    ];
}

Return errors in the shape your spec promises. Laravel's default 422 JSON works if you document it once and never change field names silently.

Step 3: Add contract tests in CI

Write feature tests that assert response structure—not just status codes. Better still, use Pact or Dredd to diff live responses against the OpenAPI file on every pipeline run.

public function test_store_appointment_matches_contract(): void
{
    $user = User::factory()->create();
    $service = Service::factory()->create();

    $response = $this->actingAs($user, 'sanctum')
        ->postJson('/api/v1/appointments', [
            'service_id' => $service->id,
            'starts_at'  => now()->addDay()->toIso8601String(),
        ]);

    $response->assertCreated()
        ->assertJsonStructure([
            'data' => ['id', 'service_id', 'starts_at', 'status'],
        ]);
}

Pair this with guidance from API contract testing with Pact and building RESTful APIs with Laravel. Contract tests catch drift before mobile teams file bugs.

For auth decisions, compare Passport vs Sanctum early. Changing token strategy after clients ship is expensive.

Laravel Implementation Pipelineopenapi.yamlGit repo rootPrism mockPort 4010Laravel 13PHP 8.3 APIGitLabCI testsDeployer 7 release on UbuntuComposer 2.10dep deploy prodPHP-FPM reloadOpcache clearLive API
Laravel API first pipeline: OpenAPI spec feeds mock and real servers, validated in GitLab CI before Deployer release

On sister sites I maintain with Deployer 7 and GitLab CI, the OpenAPI file lives beside application code. Pipeline stages lint the spec, run PHPUnit contract tests, then deploy. PHP-FPM reload after symlink swap keeps opcache from serving stale controllers.

Payment integrations need extra care. Define idempotency key headers in the spec before wiring eSewa or Khalti callbacks. See idempotency keys implementation for retry-safe POST patterns.

How Do You Test and Document APIs in an API-First Workflow?

Documentation is not a separate phase—it is an output of the same spec that drives development. When the YAML changes, docs and mocks update together.

Generate human-readable docs

Render the spec with Redoc, Swagger UI, or Scribe for Laravel. Host docs at a stable path like /api/docs. Link to it from your developer onboarding README.

Laravel teams often use Scribe for Laravel API documentation. You can annotate controllers and export OpenAPI, or treat your hand-written YAML as primary and generate static HTML in CI.

Layer your test pyramid

  1. Spec lint — validate YAML syntax and breaking-change rules on every pull request.
  2. Contract tests — assert live responses match schemas for happy paths and documented errors.
  3. Integration tests — exercise auth, database state, and third-party sandbox callbacks.
  4. Load smoke — hit critical endpoints under modest concurrency before major releases.

Postman collections generated from OpenAPI give QA a runnable suite. Export Newman jobs into CI for regression on staging. Our Postman and Newman testing guide covers the wiring.

Version every breaking change. Prefix paths with /v1 and document sunset dates in the spec info block. Read Laravel API versioning strategy and API deprecation best practices before you ship v2.

Monitor production with structured logs and response-time alerts. Prometheus and Grafana dashboards on 5xx rates catch contract violations that slip past tests. The API monitoring guide shows a practical setup on Ubuntu.

For public partner APIs, publish an SDK after the spec stabilises. SDK design principles reduce support tickets when integrators never touch raw HTTP.

API First vs Code First: Which Approach Should You Choose?

Neither approach wins every project. Choose based on consumer count, team structure, and how stable requirements are.

CriteriaAPI FirstCode First
Multiple clients (web, mobile, partners)Strong fit—one contract, parallel workWeak—consumers wait or guess shapes
Single internal admin on same repoOverhead may not pay offFaster to ship endpoints ad hoc
Changing requirements weeklySpec churn needs disciplineFlexible but docs lag code
Regulated or partner-facing APIsAudit trail from versioned specHard to prove compliance
Team sizeBest with 2+ parallel workstreamsWorks for solo or pair dev
Documentation qualityGenerated from source specOften outdated within weeks

My default on multi-client Laravel projects is API first. On a small WordPress 7.1 site with one WooCommerce 11.1 theme, code first is fine—the REST layer is WordPress core plus plugin hooks, not a custom public API.

Hybrid approaches exist. Some teams code first for an MVP spike, then freeze the spec before external partners onboard. The mistake is staying hybrid forever without updating the YAML.

API First vs Code FirstHow many API consumers?One clientSame repo teamTwo or moreParallel teamsSingleMultipleCode first OKDocument laterAPI First WorkflowOpenAPI + mocks
Decision tree for API First Development Workflow: multiple parallel consumers favour contract-first design

Gateway layers sit outside this choice but depend on a stable contract. Kong, Traefik, or KrakenD route traffic once your paths and auth headers are fixed. Compare options in the API gateway comparison and Kong gateway guide.

Real proof matters. The Mijar Law Associates client portal and Adventure Third Pole Trek booking system both rely on structured APIs behind Livewire and mobile-friendly views. Contract clarity kept document upload and itinerary endpoints stable across releases.

Key Takeaways

  • Write docs/openapi.yaml before Laravel routes—treat the spec as the single source of truth.
  • Run a Prism mock server so frontend and mobile teams build against realistic responses immediately.
  • Validate every merge with spec lint plus PHPUnit or Pact contract tests in GitLab CI.
  • Version paths with /v1, document deprecation dates, and never rename JSON fields without a migration plan.
  • Generate docs from the same file that powers mocks—Scribe, Redoc, or Swagger UI all work.
  • Use API first when two or more teams consume the same endpoints; code first is fine for solo internal tools.

People Also Ask

What tools do you need for an API first workflow?

You need an OpenAPI editor (Stoplight, Swagger Editor, or VS Code with Redocly), a mock server like Prism, CI validation, and a doc renderer. Laravel teams add PHPUnit, Scribe or Redoc, and optionally Pact for consumer-driven contracts. Composer 2.10 and Node.js 26 LTS cover most toolchain installs on Ubuntu dev boxes.

How long does API first design add to a project?

Expect one to three days upfront for a medium REST API with ten to twenty endpoints. That time returns within the first sprint because frontend and backend work in parallel. Skipping design often costs a full week of integration fixes later.

Can you use API first with GraphQL?

Yes, but the contract is a GraphQL schema file instead of OpenAPI. The same principle applies: define types and operations first, mock with tools like GraphQL Faker, then implement resolvers. REST remains the default for most Laravel and Symfony projects I ship.

Does API first work with third-party integrations like OpenAI or Shopify?

Your public API should still be contract-first even when you consume external APIs. Document outbound dependencies separately. For Shopify Admin API 2026-07 or OpenAI integrations in Laravel, wrap vendor calls behind your own stable endpoints so frontend code never depends on vendor response quirks directly.

Start Your API First Development Workflow Today

An API First Development Workflow turns integration from a late surprise into an early agreement. Define the contract, mock it, implement against it, test it in CI, and publish docs from the same file. That sequence scales from a Kathmandu booking startup to a multi-region eCommerce platform.

If you are planning a new product or untangling a multi-client Laravel API, I can help scope the OpenAPI contract and delivery pipeline. Review our API development services, browse the portfolio, or read Laravel API best practices for deeper patterns. When you are ready to talk requirements, contact us and we will map the workflow to your stack.

Frequently Asked Questions

You define the REST contract in OpenAPI before writing backend or frontend code, then mock, implement, test against that spec, and publish docs from the same file so all clients share one source of truth.

You need an OpenAPI editor such as Stoplight, Swagger Editor, or VS Code with Redocly, plus a mock server like Prism or Stoplight Mock, CI validation, and a doc renderer such as Scribe, Redoc, or Swagger UI. Laravel teams typically add PHPUnit, optionally Pact for consumer-driven contracts, Composer 2.10, and Node.js 26 LTS on Ubuntu dev boxes. Store the spec at docs/openapi.yaml in version control and lint it on every pull request before merge.

Expect one to three days upfront for a medium REST API with ten to twenty endpoints. That time usually returns within the first sprint because frontend and backend teams work in parallel instead of waiting on live endpoints.

Choose API first when multiple clients—web, mobile, and partners—consume the same endpoints, requirements involve regulated or partner-facing APIs, or two or more teams work in parallel. Code first suits solo developers, single internal admin tools on the same repo, or small WordPress 7.1 sites with WooCommerce 11.1 where the REST layer is core plus plugins. Hybrid MVPs are acceptable if you freeze the OpenAPI spec before external partners onboard; staying hybrid without updating the YAML is the common mistake.

Start with user stories, translate them into REST resources and operations, and follow noun-based plural paths with consistent HTTP verbs and uniform error bodies. Store docs/openapi.yaml in version control, split large APIs into reusable component schemas referenced with $ref, and validate YAML syntax in CI before merge. Schedule a 60-minute contract review with backend, frontend, and QA. For every route, confirm missing-resource behaviour, 422 validation error shapes, required fields at create versus update, and whether auth uses Bearer tokens, API keys, or session cookies.

On Laravel 13 with PHP 8.3—or Laravel 12 on PHP 8.2—treat the OpenAPI file as authoritative. Stand up a Prism or Stoplight mock server with npx @stoplight/prism-cli mock docs/openapi.yaml --port 4010 so frontend teams hit realistic responses immediately. Define versioned routes in routes/api.php, align Form Request validation with OpenAPI constraints, and use API resources for consistent response shapes. Return 422 errors in the documented format and add PHPUnit feature tests asserting JSON structure, optionally paired with Pact or Dredd in GitLab CI before Deployer 7 release.

Documentation is an output of the same spec that drives mocks—not a separate phase. Generate human-readable docs with Scribe, Redoc, or Swagger UI at a stable path like /api/docs. Layer your test pyramid: spec lint on every pull request, contract tests matching live responses to schemas, integration tests covering auth and database state, and modest load smoke before major releases. Export Postman collections from OpenAPI and run Newman in CI on staging. Monitor production with structured logs, Prometheus and Grafana on 5xx rates, and publish an SDK once the spec stabilises for partner APIs.

Yes, but the contract is a GraphQL schema file instead of OpenAPI. Define types and operations first, mock with tools like GraphQL Faker, then implement resolvers against that schema. The same design-before-build principle applies. REST with OpenAPI remains the default for most Laravel and Symfony projects because tooling, mock servers, and contract testing around OpenAPI are more mature in typical PHP stacks.

Your public API should still be contract-first even when you consume external APIs. Document outbound dependencies separately. For Shopify Admin API 2026-07 or OpenAI integrations in Laravel, wrap vendor calls behind your own stable endpoints so frontend code never depends directly on vendor response quirks. Define idempotency key headers in the spec before wiring payment callbacks such as eSewa or Khalti. That isolation keeps third-party changes from breaking mobile or admin clients.

Store the spec in version control at docs/openapi.yaml alongside application code. On sister sites I maintain with Deployer 7 and GitLab CI, the OpenAPI file lives beside the Laravel application. Pipeline stages lint the spec, run PHPUnit contract tests, then deploy. Split large APIs into reusable component schemas with $ref so field definitions are not duplicated across endpoints. Treat this file as the single source of truth—not Slack agreements or post-hoc documentation.

Install Prism or Stoplight Mock and point it at your OpenAPI spec. Run npx @stoplight/prism-cli mock docs/openapi.yaml --port 4010 locally, then give frontend developers http://localhost:4010 as the base URL. They can POST to /v1/appointments and receive example responses from the spec while backend implementation proceeds on a separate track. This removes the common blocker where UI teams wait until Laravel routes exist before building screens.

Design the contract, mock and review, implement with validation, then publish and version. Each release cycle revisits the spec before code changes land.

Validate OpenAPI YAML syntax and breaking-change rules on every pull request before merge. Write PHPUnit feature tests that assert response structure—not just HTTP status codes—and optionally use Pact or Dredd to diff live responses against the OpenAPI file on every pipeline run. Contract tests catch field renames and shape changes before mobile teams file bugs. Pair spec lint with integration tests covering auth, database state, and third-party sandbox callbacks so documented error formats stay accurate in production.

Compare Passport versus Sanctum early during contract design and document auth requirements directly in the OpenAPI spec—whether routes need Bearer tokens, API keys, or session cookies. Ambiguity here causes the most production auth bugs on enterprise applications. Changing token strategy after clients ship is expensive because mobile apps, partner integrations, and admin dashboards all embed the chosen flow. Decide before implementation, not after QA discovers mismatched auth headers.

Prefix paths with /v1 and document sunset dates in the spec info block. Version every breaking change explicitly and never rename JSON fields without a migration plan. Read Laravel API versioning strategy and API deprecation best practices before shipping v2. When requirements change weekly, spec churn needs discipline—update docs/openapi.yaml before code lands, not after. Gateway layers such as Kong, Traefik, or KrakenD route traffic once paths and auth headers are fixed, but they depend on a stable contract underneath.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: