apigenie-generator server express

Tier 2 · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · Verification

Generate an Express server stub in TypeScript from an OpenAPI document.

Usage

apigenie-generator server express [...OPTIONS] INPUT_FILE

Description

The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see Swagger 2.0 input); bundle documents referencing other files with apigenie bundle first. The generated code runs on Node.js 20 or later with Express 5.

The generator writes typed handler interfaces and a router serving them. Your code implements the handlers in files of its own, so regenerating the code never overwrites it:

import express from "express";
import { BASE_PATH, createRouter, HttpError, type PetsHandlers } from "pet-store-server";

const pets: Partial<PetsHandlers> = {
  async listPets(request) {
    const pets = await db.pets.list({ limit: request.query.limit });
    return { status: 200, body: pets, headers: { "X-Total-Count": pets.length } };
  },
  async showPetById(request) {
    const pet = await db.pets.find(request.params.petId);
    if (pet === undefined) {
      throw new HttpError(404, "No such pet");
    }
    return { status: 200, body: pet };
  },
};

const app = express();
app.use(
  BASE_PATH,
  createRouter(
    { pets },
    {
      handleNotFound: true,
      security: { api_key: ({ credential }) => users.byApiKey(credential) },
    },
  ),
);
app.listen(8080);

Operations are grouped into handler interfaces by their first tag (PetsHandlers); operations without tags belong to the default group. A handler is named after the operationId of its operation, or after its method and path. It receives:

  • the request: the decoded and validated path, query, header and cookie parameters (params, query, headers, cookies, by name) and the body with its declared media type (contentType), all typed from the document
  • the context: the Express request and response (req, res), the description of the operation, the principal returned by the security handlers, and signal, aborted when the connection closes before the response is complete

It returns the response: a status, a body, headers and optionally a content type, typed per status from the document. A handler which answers on its own through context.res returns nothing.

Since 0.12.0, a response in text/event-stream or JSON Lines (application/jsonl, application/x-ndjson, application/x-jsonlines) can also be answered with an AsyncIterable of its items, such as an async generator. The response type has a member per streamed media type whose contentType is that media type, required when the response has several media types. The items are typed by itemSchema (x-itemSchema in OpenAPI 3.0 and 3.1 documents) in src/types.ts. An inline schema gets a type named after the operation, such as GetTrackingEventsEventStreamItem or GetTrackingEventsJsonlItem. A schema in a shared response gets a type named after the response component, such as LogStreamEventStreamItem. Without an itemSchema, an event is a ServerSentEvent ({ data?: unknown; event?: string; id?: string; retry?: number }) and a JSON line unknown.

The router sets Cache-Control: no-cache unless the handler set it, waits for the first item, sends the headers, and writes each item as it comes. A JSON Lines item becomes one line of JSON. An event item becomes its id, event and retry fields, then a data: line per line of its data: the string itself, or its JSON for another value. An item that isn’t an object is its data. An item without data writes its fields but no data: line, so no event is dispatched; an EventSource still applies its id and retry.

  • An error before the first item is answered with a problem, with the headers already set. A later error aborts the connection, so the client sees a truncated stream, not a complete one.
  • An item that JSON.stringify throws on, such as one holding a bigint or a cycle, also aborts the connection. The router then calls the iterator’s return().
  • When the client disconnects, the router stops at the next item and calls the iterator’s return(), so an async generator’s finally blocks run. context.signal is aborted at once, for a handler that waits long for its next item.
  • A HEAD request gets the status and headers only: the router reads no item and calls the iterator’s return(), so an async generator’s body doesn’t run at all.
  • An AsyncIterable in a media type that isn’t streamed is a 500. validateResponses doesn’t check streamed items.
const tracking: Partial<TrackingHandlers> = {
  async getTrackingEvents(request) {
    async function* events() {
      for await (const update of carrier.updates(request.params.shipmentId)) {
        yield { event: "tracking" as const, id: update.id, data: JSON.stringify(update) };
      }
    }
    return { status: 200, contentType: "text/event-stream", body: events() };
  },
};

The client receives:

id: evt_1
event: tracking
data: {"id":"evt_1","status":"in_transit","occurredAt":"2026-11-03T09:00:00Z"}

For every request, the router:

  1. checks the security requirements of the operation: any of them, with all the schemes of a requirement, must be satisfied. A security handler receives the credential (the API key, the bearer token or the decoded user:password of basic authentication) and the required scopes, and returns the principal, or undefined to reject the request with 401 Unauthorized. It may throw an HttpError, e.g. 403 Forbidden for missing scopes. Schemes without handlers reject every request.
  2. decodes the parameters in all OpenAPI styles (simple, label, matrix, form, spaceDelimited, pipeDelimited and deepObject, exploded or not) and converts them to the types of their schemas; parameters with content are parsed as JSON. Absent parameters get their default values.
  3. reads the body: JSON, application/x-www-form-urlencoded (converted to the types of its schema), multipart/form-data (see below), text and binary bodies are parsed. A body that middleware already parsed is used as it is (req.body), except a multipart/form-data one whose schema has properties. A media type that isn’t declared is answered with 415 Unsupported Media Type, a missing required body with 400.
  4. validates the parameters and the body against their schemas (see validation) and answers invalid requests with 400 Bad Request.
  5. calls the handler, or answers with 501 Not Implemented when there’s none.
  6. writes the response, optionally validating it first (validateResponses).

Since 0.12.0, a multipart/form-data body whose schema has properties is decoded into an object with a property per part. Its type, <Operation>RequestBody in src/types.ts, has a globalThis.File per file. The first rule that applies decides how a part is decoded:

  1. When the encoding of the property names a contentType, its first media type decides: a JSON type is parsed as JSON, a text/* type is text and any other type is a File.
  2. A binary string is a File: format: binary, a contentEncoding, or in OpenAPI 3.1 and 3.2 documents a contentMediaType.
  3. A schema whose type includes object or array is parsed as JSON, and so is a schema without type that has properties, patternProperties, additionalProperties, items, prefixItems, allOf, anyOf or oneOf.
  4. Any other schema without type, {} included, is a File.
  5. Any other value is text, converted to the types of its schema like a query parameter.

A File has the file name, media type and content of the part. A file part without a file name or without a Content-Type becomes a File of text/plain. A property of type: array with items collects its repeated parts, and its items decide how each is decoded. Any other property may appear once, and a part that no property names is kept as it is: a string, or a File when it has a file name.

A request is answered with 400 Bad Request when one of its parts fails these checks:

keyword When
contentMediaType A file whose media type isn’t in the contentType of its encoding (image/* ranges included), or a JSON part that isn’t valid JSON
multipart A part appears more than once, and its property isn’t of type: array with items

A body that can’t be read as multipart is answered with 400 and the detail “The multipart body can’t be read”. The decoded object is then validated against the schema. A file stands for an empty string there, so a type without string, a minLength above 0, or a pattern, enum or const that doesn’t accept "" rejects every file. The headers of the parts aren’t available, so the headers of an encoding aren’t checked.

The router reads the multipart body itself, up to bodyLimit ("100kb" by default). Middleware that reads the raw body, such as express.raw({ type: "multipart/*" }), is fine. Middleware that parses it, such as multer, is answered with 500 Internal Server Error, so leave it out for these routes. Without a schema with properties, the body is left to middleware and typed unknown.

Errors are answered with problem details (application/problem+json). Validation errors list the failed checks:

{
  "type": "about:blank",
  "title": "Bad Request",
  "status": 400,
  "detail": "The request is invalid",
  "errors": [
    { "in": "query", "name": "limit", "path": "", "keyword": "maximum", "message": "must be <= 50" },
    { "in": "body", "path": "/name", "keyword": "required", "message": "must have required property 'name'" }
  ]
}

Routes are registered so that literal path segments win over parameters (/pets/mine before /pets/{petId}). Deprecated operations are marked @deprecated, and operations disabled with the x-apigenie extension (codegen.disabled) are left out.

An operation can have servers of its own, given on the operation or else on its path item. The path of its first server, with the default values of its variables, can differ from BASE_PATH. createRouter still serves such an operation under BASE_PATH. Since 0.12.0, createRootRouter(handlers, options) serves each operation under the path of its first server instead, and the operations without servers under BASE_PATH, ordering the routes by these full paths. Mount it at the root:

app.use(createRootRouter({ pets }, { handleNotFound: true }));

With handleNotFound, the root router answers 404 for every request that no earlier route or middleware answered: register other routes and middleware first. The root router answers serveDocument under BASE_PATH. It checks the path only: a server’s host isn’t checked, so an application that serves several hosts checks req.hostname itself. A server path with a variable the server doesn’t declare can’t be routed, and its operation stays under BASE_PATH. Since 0.12.0, an operation in OPERATIONS with servers of its own, or of its path item, has servers: their URLs, with the default values of their variables.

Generated files

The generated package contains:

  • src/types.ts: the types of the component schemas, mapped as in the fetch client, and the request and response types of every operation
  • src/handlers.ts: the handler interfaces, Handlers, SecurityHandlers, createRouter(handlers, options) and createRootRouter(handlers, options)
  • src/metadata.ts: the operations (OPERATIONS), webhooks and callbacks (OUTGOING_OPERATIONS) and security schemes described for the runtime, and the port (DEFAULT_PORT) and path (BASE_PATH) of the first server
  • src/senders.ts: createWebhooks() when the document has webhooks, and createCallbacks() when its operations have callbacks, with src/outgoing.ts, the code sending their requests, which the oRPC server shares
  • src/validation.ts and, depending on validation, src/schemas.ts and src/ajv_engine.ts, or src/validators.ts
  • src/runtime.ts: the request handling code, which doesn’t depend on the document
  • src/document.ts: the OpenAPI document, with copy_document
  • src/index.ts, package.json, tsconfig.json and README.md
  • src/server.ts: an example server with stub handlers, with scaffold. It mounts createRootRouter when the operations have paths other than BASE_PATH, and createRouter otherwise

README.md and server.ts are written only if they don’t exist; the other files are overwritten.

Webhooks and callbacks

Since 0.12.0, the requests your application sends are generated too. They are the webhooks of the document (x-webhooks in OpenAPI 3.0 documents) and the callbacks of its operations. src/senders.ts then has createWebhooks(options), createCallbacks(options) or both, whose senders send each request with fetch:

import { createCallbacks, createWebhooks, type ShipmentsHandlers } from "carpet-express-server";

const webhooks = createWebhooks({ headers: { "User-Agent": "carpet-express" } });
await webhooks.onShipmentStatusChanged(subscription.url, {
  headers: { "CarpetExpress-Signature": sign(event) },
  body: event,
});

const callbacks = createCallbacks();
const shipments: Partial<ShipmentsHandlers> = {
  async createShipment(request) {
    const shipment = await db.shipments.create(request.body);
    queue.onStatusChange(shipment, async (event) => {
      const response = await callbacks.createShipment.statusChanged(
        { request },
        { headers: { "CarpetExpress-Signature": sign(event) }, body: event },
      );
      if (response.status === 410) {
        queue.stop(shipment);
      }
    });
    return { status: 201, body: shipment, headers: { ETag: etag(shipment) } };
  },
};

A webhook sender is named like a handler, from the sources action_naming lists, or else after its method and name, and takes the subscriber’s URL.

A callback sender is grouped under the handler name of its operation. It is named after the callback, followed by the method when the callback has several requests. It takes a source: the decoded request of the operation, and optionally its response and the Express request (req). The runtime expressions in the callback’s URL, such as {$request.body#/callbackUrl}, are resolved against it:

Expression Value
$request.body, $request.body#/pointer The body of source.request, or the value at the JSON Pointer
$request.query.name, $request.path.name A parameter of source.request
$request.header.name A header of source.request, or else of source.req
$response.body, $response.body#/pointer The body of source.response, or the value at the JSON Pointer
$response.header.name A header of source.response
$statusCode The status of source.response
$url, $method The URL and method of source.req

A value at the start of the URL is used as it is, as the base URL. Later values are percent-encoded, so the scheme and the host come from the literal start of the URL or from the value at its start. In {$request.body#/url}/verify/{$response.body#/id}, a slash in the id is sent as %2F. When an expression has no value, or its value is an object or an array, the promise rejects with an Error and nothing is sent. A URL that isn’t valid rejects with a TypeError.

A sender’s request is typed like a handler’s, as <Name>Request in src/types.ts, with no params. <Name> is the name of a webhook sender. For a callback, it is the name of the callback component it refers to, when no other callback refers to that component (ShipmentStatusCallbackRequest). Otherwise it is the handler name and the callback name (CreateWebhookSubscriptionVerificationRequest). The method follows when the callback has several requests. query, headers, cookies and the body are optional unless they hold something required. The body is sent in the first declared media type, or in the one contentType names; a contentType the operation doesn’t declare rejects with an InvalidRequestError. It can be JSON, form fields or text, a FormData for multipart/form-data, or a Uint8Array or Blob.

The sender first checks the query, header and cookie parameters and a JSON, form or text body against their schemas, with the validation of the package. A multipart/form-data or binary body is only checked for presence. When a check fails, the promise rejects with an InvalidRequestError and nothing is sent; its issues list the failed checks.

A sender resolves with a response that its operation declares, typed as <Name>Response. Its headers are strings by lowercase name. Its body is decoded as the declared media type its Content-Type matches, which contentType then holds:

Declared media type body Empty body Checked
JSON, such as application/json or *+json The parsed JSON Rejects Valid JSON, and the schema
application/x-www-form-urlencoded The fields, as a string or an array of strings by name Rejects Presence
text/*, including the text/* range The text "" The schema
Any other, including multipart/* and */* A Uint8Array Rejects Presence
None (declared without content) undefined, whatever is received undefined Nothing; contentType is the Content-Type as received

A response whose status or media type isn’t declared, or that the table says rejects, makes the promise reject with an UnexpectedResponseError. The error’s response holds the response, and its issues say what didn’t match. An operation without declared responses accepts any response, decoded by its Content-Type, which contentType then holds. A network error rejects with the error of fetch.

Option Description
fetch The fetch function that sends the requests (default: globalThis.fetch)
validation Validation of the requests and responses (default: the engine of the validation setting)
headers Headers of every request
onRequest Called with each Request and the OperationInfo of its webhook or callback before it’s sent; returns it or another Request, e.g. to sign it

Declared header parameters replace the headers option of the same name. The last argument of a sender takes the headers and the signal of that request only. Its headers replace those of the same name and aren’t validated.

OUTGOING_OPERATIONS in src/metadata.ts describes the webhooks and callbacks. The path of a webhook is its name, and that of a callback is its URL expression.

Extensions

Extension Effect
x-apigenie.codegen.name name of the type of a component schema
x-apigenie.codegen.controller-name on an operation or its path item: the handler interface of the operation, when grouping lists extension
x-apigenie.codegen.action-name name of the handler of an operation, or of the sender of a webhook, when action_naming lists extension
x-apigenie.codegen.disabled true on an operation, on the operation of a webhook or of a callback URL expression, or on its path item, leaves it out (for a webhook or a callback, its sender), unless skip_disabled is false
x-defaultMapping defaultMapping of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn’t mapped
x-itemSchema itemSchema of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a streamed response
x-webhooks webhooks of an OpenAPI 3.0 document: the requests the senders of src/senders.ts send

The extensions can live in an overlay for this target instead of in the document, e.g. express.overlay.yaml:

overlay: 1.0.0
info:
  title: TypeScript names
  version: 1.0.0
actions:
  - target: $.components.schemas.Pet
    update:
      x-apigenie:
        codegen:
          name: Animal
  - target: $.paths['/admin']
    update:
      x-apigenie:
        codegen:
          disabled: true
apigenie-generator server express openapi.yaml --overlay express.overlay.yaml -o out

Options

-c, –config

Path to the configuration file to use. See the “Configuration” section for more information.

–overlay OVERLAY

Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the “Extensions” section. Can be repeated: the overlays apply in order, after those listed under commands.generate.server_express.overlay in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay.

–strict

Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.).

–check

Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See Check that generated code is up to date.

-o, –output

Directory where the package is generated.

–package-name

Name of the generated package. Defaults to the title of the API followed by -server.

–package-version

Version of the generated package. Defaults to the version of the API.

Configuration

version: '1.0'
commands:
  generate:
    server_express:
      validation: ajv
      validate_responses: true
      scaffold: true
Option Description
layout package (default): an npm package with sources in src/; sources: the sources only
import_extension Extension of relative imports: .js (default, Node.js) or an empty string (bundlers)
validation ajv (default): JSON Schemas validated with Ajv; generated: generated TypeScript validators, without dependencies; none
validate_responses Generate what’s needed to validate responses, enabled by the validateResponses router option (default: false)
grouping How operations are grouped into handler interfaces: tag (default), extension (x-apigenie codegen.controller-name) or url, or a list of them, in order of preference
action_naming Sources of handler and webhook sender names: id, extension (x-apigenie codegen.action-name) or url, or a list of them (default: [id, url])
skip_deprecated Leave deprecated operations, webhooks and callbacks out (default: false)
skip_disabled Leave out operations, webhooks and callbacks disabled with x-apigenie (default: true)
copy_document Include the document in the package, so that the router can serve it (default: false)
scaffold Write an example server, src/server.ts, unless it exists (default: false)
security Check the security requirements of operations (default: true)

Both validation modes report the same issues with the same messages, and both convert OAS 3.0 schemas (nullable, boolean exclusiveMinimum and exclusiveMaximum) and leave readOnly properties out of the required properties of requests and writeOnly ones out of responses. Since 0.12.0, they check if/then/else, dependentRequired, dependentSchemas and draft-07 dependencies. The generated validators don’t check unevaluatedProperties, unevaluatedItems, contains, propertyNames, contentSchema and $dynamicRef; the generator warns about them. Formats are checked as JSON Schema defines them, the generated validators knowing the common ones (date-time, date, time, duration, email, hostname, ipv4, ipv6, uri, uri-reference, uuid, byte, int32 and int64).

Router options

Option Description
security Security handlers, by scheme name
validation A validation engine replacing the generated one, e.g. noValidation
validateResponses Validate the bodies returned by handlers, except streams; invalid ones are answered with 500
handleNotFound Answer requests to unknown paths with 404 and unknown methods with 405
notImplemented "501" (default) or "next": pass requests to operations without handlers to the next middleware
exposeErrors Put the messages of unexpected errors into 500 responses
onError Called with unexpected errors, which are logged with console.error otherwise
bodyLimit Maximum size of request bodies, multipart ones included, e.g. "1mb" (default: "100kb")
serveDocument Serve the document as JSON at this path, e.g. "/openapi.json" (needs copy_document)
caseSensitive, strict Options of the Express router

Verification

The codegen conformance suite runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. All targets.

This target's support tier is Tier 2. It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives.

ResultsLevel 1Level 2Level 3
Release 0.12.0✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet, 1 not checked✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, Express 5)✓ 72 of 77 operations pass (node)
Development version✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet, 1 not checkedruns before a releaseruns before a release
Was this helpful?