Interactive Learning Platform Nuxt layer

Isolated learning atmosphere · v4.x

← Back to writing
Step 8 of 9OpenAPI + Vitest

The Charger Contract: OpenAPI and Vitest

Turn the charger-agent routes into a generated OpenAPI 3.1 contract, serve Scalar and Swagger docs, and keep the contract honest with Vitest and serverFetch.

A charger is a client. It does not read your UI, your types, or your README. It reads the contract. Stage 8 makes the contract explicit: OpenAPI for the agents, Vitest for the humans.

ampyard / preview / 8
Live stage Open app ↗
Ampyard · live stageStage 8 / 9

What it is#

Nitro can generate an OpenAPI 3.1 specification from route metadata:

nitro.config.ts
export default defineConfig({
  experimental: {
    openAPI: true,
  },
  openAPI: {
    meta: {
      title: "Ampyard Charger API",
      description: "The public depot snapshot and the charger-agent contract.",
      version: "1.0.0",
    },
    production: "runtime",
  },
});

defineRouteMeta is a build-time macro. It is extracted when the app is built, so it adds no runtime cost to the handler.

With the flag on, Nitro serves:

EndpointWhat it is
/_openapi.jsonThe OpenAPI 3.1 specification
/_scalarThe Scalar API reference UI
/_swaggerThe Swagger UI

In development the docs are always available. In production they are off by default. production: "runtime" turns them on for the live demo; a real depot would put them behind operator auth.

Why you'd care#

The charger-agent routes are the part of Ampyard that other machines call:

  • POST /api/agents/heartbeat every 30 seconds.
  • POST /api/agents/start when a driver plugs in.
  • POST /api/agents/sessions/:id/meter for cumulative kWh.
  • POST /api/agents/sessions/:id/stop to settle.

Those routes have inputs, outputs, and failure modes. A typed frontend does not help a charger in a parking lot. An OpenAPI document does.

The same document is a test plan. The route metadata names the required fields, the test suite exercises the happy path, and the two stay in one file.

What we're building#

  • OpenAPI metadata on the depot, tariff, session, and agent routes.
  • A shared Stall, QueueEntry, Summary, and Session schema.
  • Scalar and Swagger UIs for the demo.
  • A Vitest suite that calls the app with serverFetch.

Before#

The agent routes worked, but the only description of the contract was the handler code and this series.

After#

Every route declares its own contract:

server/api/agents/heartbeat.post.ts
import { defineRouteMeta } from "nitro";

defineRouteMeta({
  openAPI: {
    tags: ["charger-agents"],
    description:
      "A charger agent reports its bay state. Agents call this on boot, every 30 seconds, and whenever a connector changes state.",
    requestBody: {
      required: true,
      content: {
        "application/json": {
          schema: {
            type: "object",
            required: ["stallId", "status"],
            properties: {
              stallId: { type: "string", example: "bay-03" },
              status: {
                type: "string",
                enum: ["available", "charging", "reserved", "offline"],
              },
              sessionId: { type: "string" },
              kwh: { type: "number" },
              note: { type: "string" },
            },
          },
        },
      },
    },
    responses: {
      200: { description: "Heartbeat accepted" },
      404: { description: "Unknown bay" },
    },
  },
});

export default defineHandler(async (event) => {
  // validate, write state, return the accepted state
});

Shared schemas live in $global so other routes can $ref them:

server/api/depot.get.ts
defineRouteMeta({
  openAPI: {
    tags: ["depot"],
    // ...
    $global: {
      components: {
        schemas: {
          Stall: {
            type: "object",
            properties: {
              id: { type: "string" },
              label: { type: "string" },
              status: {
                type: "string",
                enum: ["available", "charging", "reserved", "offline"],
              },
            },
          },
        },
      },
    },
  },
});

The tests use the same app:

test/seed.test.ts
import { expect, test } from "vitest";
import { serverFetch } from "nitro";

test("GET /api/tariffs returns the four bands", async () => {
  const response = await serverFetch("/api/tariffs");
  expect(response.status).toBe(200);
  const body = (await response.json()) as Array<{ id: string }>;
  expect(body.map((tariff) => tariff.id)).toEqual(["night", "day", "peak", "late"]);
});

serverFetch sends a request into the Nitro app without starting a dev server. The nitro() Vite plugin gives Vitest a nitro environment, so routes, plugins, runtime config, and D1 work the same as in production.

Do it yourself#

Start the app:

bash
pnpm --filter ampyard dev

Open the docs:

txt
http://localhost:4321/_scalar
http://localhost:4321/_swagger
http://localhost:4321/_openapi.json

Send a heartbeat from the Scalar UI, or with curl:

bash
curl -s -X POST http://localhost:4321/api/agents/heartbeat \
  -H 'content-type: application/json' \
  -d '{"stallId":"bay-07","status":"available","note":"manual check"}' | jq

Run the tests:

bash
pnpm --filter ampyard test

The first test is a unit test of the tariff bands. The second calls the real route through serverFetch.

The live stage#

The preview above is /preview/8. The Charger-agent contract section appears with a heartbeat example and links to Scalar, Swagger, and the raw JSON. The ops page already had the docs links from stage 6; stage 8 makes them part of the lesson.

Gotchas#

  • OpenAPI is experimental. The schema generation is stable enough for the series, but check the Nitro release notes before you depend on a specific shape.
  • Protect the docs in production. production: "runtime" is a demo choice. production: "prerender" is better when the spec is static and you can serve it from a CDN.
  • defineRouteMeta is a macro. It is extracted at build time. Do not compute the metadata at runtime or import it from a value that only exists in memory.
  • Tests run in Node. The Nitro test environment does not emulate Cloudflare bindings. A route that touches D1 needs a Node-compatible test setup, a mock, or NITRO_PRESET=node_server.
  • One contract, two consumers. The docs and the tests read the same route. If the handler changes and the metadata does not, the docs lie. Treat the metadata as part of the route.
  • Examples are not validation. example documents a value; it does not enforce it. Validate the body in the handler, as the route does with zod.

Recap#

Ampyard now has a machine contract: OpenAPI generated from the routes, Scalar and Swagger for humans, and Vitest tests that call the app through serverFetch. Stage 9 ships it.

Next: Ship It.