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.
What it is#
Nitro can generate an OpenAPI 3.1 specification from route metadata:
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:
| Endpoint | What it is |
|---|---|
/_openapi.json | The OpenAPI 3.1 specification |
/_scalar | The Scalar API reference UI |
/_swagger | The 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/heartbeatevery 30 seconds.POST /api/agents/startwhen a driver plugs in.POST /api/agents/sessions/:id/meterfor cumulative kWh.POST /api/agents/sessions/:id/stopto 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, andSessionschema. - 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:
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:
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:
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:
pnpm --filter ampyard dev
Open the docs:
http://localhost:4321/_scalar
http://localhost:4321/_swagger
http://localhost:4321/_openapi.json
Send a heartbeat from the Scalar UI, or with curl:
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:
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. defineRouteMetais 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.
exampledocuments 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.