Skip to content

OpenAPI from controllers ​

Turn NestJS controller decorators and TypeScript types into an OpenAPI document, then generate a client from it.

A controller in your NestJS project, src/payment-notes.controller.ts:

ts
import { Controller, Get, Param } from '@nestjs/common';

interface PaymentNote {
  id: string;
  note: string;
}

@Controller('payment-notes')
export class PaymentNotesController {
  @Get(':id')
  public get(@Param('id') id: string): PaymentNote {
    return { id, note: 'Order 123' };
  }
}

@exprtlabs/golem-ts-openapi reads this file. It does not start Nest or call handlers. It supports the NestJS version in Compatibility.

Install ​

sh
npm install --save-dev @exprtlabs/golem-ts-openapi typescript@~7.1.0-beta
npm install @nestjs/swagger

An app that registers NestModelInterceptor imports @exprtlabs/golem-ts-openapi/nest at run time. Install @exprtlabs/golem-ts-openapi without --save-dev then, and add the nest extension to the ts-openapi block.

Describe a controller ​

The generator reads every *.controller.ts file under src/. Set suffixes in the docs job to use other endings, or list files under sources to choose them yourself. From the controller above it writes:

  • GET /payment-notes/{id} with a required string path parameter id
  • a JSON response with id and note
  • the operation ID PaymentNotesController_get, which becomes the client method paymentNotesController_get

The default document version is OpenAPI 3.2. The generator reads types and validation tags, not class-validator decorators. Put constraints on the types.

Configure and generate ​

Add golem.yaml beside the project's TypeScript configuration and run npx golem generate:

yaml
version: 1
ts-openapi:
  docs:
    - output: ./api/openapi.yaml
      info:
        title: Payments API
        version: '1'

You get api/openapi.yaml. Set openapiVersion: '3.1.2' in the docs job when a downstream tool does not support 3.2. That version handles whole query objects differently (query compatibility).

Models in a controller ​

ts
@Post()
@ApiOperation({ operationId: 'createPayment' })
@ApiBadRequestResponse({ description: 'Invalid payment input.' })
@ApiBadGatewayResponse({ description: 'The payment provider declined or is unavailable.' })
async create(@Body() input: TPaymentInput): Promise<TPayment> {
  const id = String(nextPaymentId++);
  const charge = await this.provider.charge(input.money, `payment-${id}`);
  const payment = { id, ...input, charge };
  payments.set(payment.id, payment);
  return payment;
}
ts
export type TMerchant = IObject<{ id: string; name: string & MinLength<2> }>;
// Amounts are decimal strings and currencies are ISO 4217 codes; no float carries money.
export type TMoney = IObject<{
  amount: string & Pattern<'^[0-9]+(?:\\.[0-9]{1,2})?$'>;
  currency: string & Pattern<'^[A-Z]{3}$'>;
}>;
export type TCharge = IObject<{ id: string; status: 'pending' | 'captured'; settlesOn: string }>;
export type TPayment = IModel<{
  id: string;
  merchant: TMerchant;
  billing: Omit<TMerchant, 'id'>;
  money: TMoney;
  note: string & MaxLength<140>;
  charge?: TCharge; // The provider's charge for this payment.
}, { exact: true }>;
export type TPaymentInput = IObject<Omit<TPayment, 'id' | 'charge'>, { exact: true }>;
ts
// Generated fields and conversion. Interceptor constructs this for class params.
export class Payment extends model<TPayment>() {}

Payment extends model<TPayment>() from @exprtlabs/golem/model with zero imports from generated files (Generate a client from the document). When ts-openapi (docs or extensions.nest) is configured beside model, Golem automatically discovers inline IObject and IModel declarations in controller files (*.controller.ts or configured controller sources/suffixes) and emits their codecs into .golem/models/, so you do not need to add .controller.ts to model.suffixes. @ApiOperation({ operationId: 'createPayment' }) replaces the default, so the client method is createPayment(). @ApiBadRequestResponse and @ApiBadGatewayResponse from @nestjs/swagger produce the 400 and 502 responses. The component name Payment follows the naming rules. The controller above produces this operation in api/openapi.yaml:

yaml
post:
  operationId: createPayment
  requestBody:
    content:
      application/json:
        schema:
          $ref: "#/components/schemas/TPaymentInput"
    required: true
  responses:
    "201":
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Payment"
      description: ""
    "400":
      description: Invalid payment input.
    "502":
      description: The payment provider declined or is unavailable.

To convert and validate the request at runtime, add the nest extension and register the interceptor.

Generate a client from the document ​

The docs job writes api/openapi.yaml. An SDK job reads that document and generates the client (Generate an SDK). The example runs it from web/golem.yaml. The ts-openapi block in server/golem.yaml, with the docs job and the nest extension:

yaml
ts-openapi:
  docs:
    - output: ./api/openapi.yaml
      info:
        title: Payments API
        version: '1'
      globalPrefix: api
  extensions:
    nest: {}

globalPrefix: api must match app.setGlobalPrefix(), because the generator reads controllers and not your bootstrap code. The models job in the same configuration emits the codecs and validators for Payment and any inline controller DTOs into .golem/models/.

Install the client and runtime packages:

sh
npm install --save-dev @exprtlabs/golem-openapi-ts @exprtlabs/golem-model typescript@~7.1.0-beta
npm install @exprtlabs/golem reflect-metadata
ts
import type { Payment, PaymentsClient, TPaymentInput } from '../sdk/index.js';

export async function submitPayment(client: PaymentsClient, draft: TPaymentInput): Promise<Payment | undefined> {
  const response = await client.createPayment().execute({ body: draft });
  // The client checks the body and returns a plain Payment; no conversion call is needed.
  return response.status === 201 ? response.body : undefined;
}

Full example: examples/payments.