# OpenAPI + NestJS: type-safe controllers from the contract

> NestJS is code-first by default meaning decorators describe your API, and the spec is generated from code. But decorators don't enforce anything at compile time. This post shows how to flip the flow to generate controller method types from an OpenAPI spec and let TypeScript catch contract drift before reaching production.

- Date: 2026-03-30T00:00:00.000Z
- Authors: Yuri Mikhin, Travis Turner
- Categories: DX
- URL: https://evilmartians.com/chronicles/openapi-nestjs-type-safe-controllers-from-the-contract

---

NestJS defaults to code-first: you write controllers, decorate them, and generate the spec from code. The spec is a byproduct. But those decorators are runtime metadata, so TypeScript doesn't check them against your actual return types. This article flips the flow. We generate controller method types from an OpenAPI spec and use `implements` to make the compiler enforce the contract.

This is part five of our contract-first series ([part one](https://evilmartians.com/chronicles/api-contracts-and-everything-i-wish-i-knew-a-frontend-survival-guide) | [part two](https://evilmartians.com/chronicles/contract-shock-therapy-the-way-to-api-first-documentation-bliss) | [part three](https://evilmartians.com/chronicles/lifes-too-short-to-hand-write-api-types-openapi-driven-react) | [part four](https://evilmartians.com/chronicles/openapi-fastify-backend-let-the-contract-build-your-server)), but works standalone if you're here to wire OpenAPI into a NestJS backend.

---

*We'll build your contract-first backend so integration becomes a non-event.* [Contact Evil Martians](https://evilmartians.com/contact-us)

---

**Table of contents**:

1. [NestJS teaches you code-first, and it works - until it doesn't](#nestjs-teaches-you-code-first-and-it-works-until-it-doesnt)
2. [The decorator layer is documentation, not enforcement](#the-decorator-layer-is-documentation-not-enforcement)
3. [What if the spec came first?](#what-if-the-spec-came-first)
4. [Generate controller method types from the spec](#generate-controller-method-types-from-the-spec)
5. [implements: the compiler becomes your contract enforcer](#implements-the-compiler-becomes-your-contract-enforcer)
6. [What this doesn't do (and why that's fine)](#what-this-doesnt-do-and-why-thats-fine)
7. [Where this fits in the contract-first stack](#where-this-fits-in-the-contract-first-stack)

## NestJS teaches you code-first, and it works (until it doesn't)

The NestJS way of doing OpenAPI starts with code. You write a DTO, add `@ApiProperty()` to every field, annotate your controller methods with `@ApiOperation()` and `@ApiResponse()`, then generate the spec with `@nestjs/swagger`. The spec falls out of the implementation:

```typescript
// The standard NestJS code-first flow
export class CreatePetDto {
  @ApiProperty({ description: 'Name of the pet' })
  @IsString()
  name: string;

  @ApiProperty({ required: false })
  @IsOptional()
  tag?: string;
}
```

For a single team on a single service this works. The spec is documentation. Nobody depends on it for code generation or contract enforcement. It gets served at `/api-docs` and that's it. But the moment a frontend team starts generating types from that spec, or a mobile team builds against it, or an external consumer integrates with it-the spec is a shared contract. And you have three artifacts that can drift: the actual controller code, the decorator metadata, and the generated spec. None of them is canonically "the truth". 

We covered the broader problems with code-first in [part one](https://evilmartians.com/chronicles/api-contracts-and-everything-i-wish-i-knew-a-frontend-survival-guide) of this series. NestJS makes them concrete: the gap between "what the code does" and "what the spec says" is bridged entirely by metadata that TypeScript doesn't type-check. This isn't hypothetical. The NestJS community has been [asking for contract-first support](https://github.com/nestjs/swagger/issues/302) since 2020, and the issue is still open.

## The decorator layer is documentation, not enforcement

Here's something that compiles and runs without a single TypeScript error:

```typescript
@Controller('pets')
export class PetsController {
  @Get()
  @ApiResponse({ status: 200, type: [PetDto] })
  async listPets() {
    return { oops: 'this is not an array of PetDto' };
  }
}
```

The `@ApiResponse` decorator says this endpoint returns `PetDto[]`. The method returns `{ oops: string }`. TypeScript doesn't care. The decorator is runtime metadata consumed by `@nestjs/swagger` to build the spec. It has no effect on the type system.

This means every `@ApiProperty()`, every `@ApiResponse()`, every `@ApiOperation()` you write is a promise you make to Swagger UI. Not to the compiler. You can break that promise and nothing catches it until a consumer hits the endpoint and gets unexpected data back.

Decorators in TypeScript are runtime functions. They run when the class is loaded. They can store metadata, modify prototypes, do whatever they want at runtime. What they cannot do is change the type signature of the thing they decorate. So `@ApiResponse({ type: PetDto })` on a method that returns `string` is perfectly valid TypeScript. The type system sees a method returning `string`. The decorator is just... there.

## What if the spec came first?

Parts [one](https://evilmartians.com/chronicles/api-contracts-and-everything-i-wish-i-knew-a-frontend-survival-guide) and [two](https://evilmartians.com/chronicles/contract-shock-therapy-the-way-to-api-first-documentation-bliss) of this series covered why writing the spec first changes things. We're not going to rehash that argument here.

The practical question for NestJS: if you already have an OpenAPI spec, how do you connect it to your controllers?

In [part four](https://evilmartians.com/chronicles/openapi-fastify-backend-let-the-contract-build-your-server) we did this with Fastify. The `fastify-openapi-glue` library read the spec and wired routes automatically. Handlers got full type coverage: params, body, response. NestJS doesn't have an equivalent. The framework owns routing through its decorator system. `@Get()`, `@Post()`, `@Controller('pets')`, that's how NestJS works and no codegen tool is going to replace it.

So we aim for something smaller but still valuable: compile-time type checking for controller method signatures. The spec defines what each method should accept and return. TypeScript checks that your controller matches.

## Generate controller method types from the spec

[Hey API](https://heyapi.dev/) is the OpenAPI codegen tool we've been using throughout this series. It didn't have NestJS support—so we built it. The [`nestjs` plugin](https://heyapi.dev/openapi-ts/plugins/nest) we contributed to Hey API generates controller method types from your spec. Adding it is one line in the config:

```typescript
// openapi-ts.config.ts
import { defineConfig } from '@hey-api/openapi-ts';

export default defineConfig({
  input: './openapi.json',
  output: {
    path: './src/client',
  },
  plugins: ['nestjs', '@hey-api/sdk'],
});
```

Run `npx openapi-ts` and the plugin generates a `nestjs.gen.ts` file. For a Petstore-style spec with `pets` and `store` tags, you get:

```typescript
// src/client/nestjs.gen.ts (auto-generated)
export type PetsControllerMethods = {
  listPets: (query?: ListPetsData['query']) => Promise;
  createPet: (body: CreatePetData['body']) => Promise;
  deletePet: (path: DeletePetData['path']) => Promise;
  showPetById: (path: ShowPetByIdData['path']) => Promise;
  updatePet: (
    path: UpdatePetData['path'],
    body: UpdatePetData['body'],
  ) => Promise;
};

export type StoreControllerMethods = {
  getInventory: () => Promise;
};
```

Each OpenAPI operation becomes a method. The `operationId` becomes the method name. Parameters are split by location (`path`, `query`, `body`) matching how NestJS extracts them with `@Param()`, `@Query()`, `@Body()`. Required parameters come before optional ones. Return types are wrapped in `Promise` because NestJS controller methods are async.

The types import from `types.gen.ts` which are the same generated types your frontend can use (see [part three](https://evilmartians.com/chronicles/lifes-too-short-to-hand-write-api-types-openapi-driven-react)). One spec, both sides of the stack.

Operations are grouped by their first OpenAPI tag. If an operation has no tag, it goes into `DefaultControllerMethods`. The tag name gets PascalCased and suffixed with `ControllerMethods`, so a tag called `pets` becomes `PetsControllerMethods`.

Notice what *isn't* in the generated file: no `import` from `@nestjs/common`. No decorators. No framework dependency at all. These are pure TypeScript types. The NestJS wiring stays in your controller where it belongs.

## implements: the compiler becomes your contract enforcer

Here's where NestJS gives us something Fastify couldn't. In [part four](https://evilmartians.com/chronicles/openapi-fastify-backend-let-the-contract-build-your-server), we typed Fastify handlers with a `RouteHandlers` interface on a plain object. Works. But NestJS controllers are classes. And TypeScript classes support `implements`:

```typescript
import {
  Body,
  Controller,
  Get,
  NotFoundException,
  Param,
  Post,
  Query,
} from '@nestjs/common';
import type { PetsControllerMethods } from '../client/nestjs.gen';
import type {
  CreatePetData,
  ListPetsData,
  Pet,
  ShowPetByIdData,
} from '../client/types.gen';

@Controller('pets')
export class PetsController
  implements
    Pick
{
  private readonly pets: Pet[] = [
    { id: '1', name: 'Fido', status: 'available', tag: 'dog' },
    { id: '2', name: 'Kitty', status: 'available', tag: 'cat' },
  ];

  @Get()
  async listPets(@Query() query?: ListPetsData['query']) {
    const limit = query?.limit ?? 20;
    return this.pets.slice(0, limit);
  }

  @Post()
  async createPet(@Body() body: CreatePetData['body']) {
    const pet: Pet = {
      id: crypto.randomUUID(),
      name: body.name,
      status: 'available',
      tag: body.tag,
    };
    this.pets.push(pet);
    return pet;
  }

  @Get(':petId')
  async showPetById(@Param() path: ShowPetByIdData['path']) {
    const pet = this.pets.find((p) => p.id === path.petId);
    if (!pet) {
      throw new NotFoundException(`Pet ${path.petId} not found`);
    }
    return pet;
  }
}
```

`Pick` selects only the methods this controller handles. You don't have to implement every operation from the spec. Maybe some operations live in a different controller. Maybe you haven't built them yet. `Pick` lets you adopt incrementally, so you can add methods to the union as you implement them.

Now, change the spec. Rename a response field. Add a required parameter. Change a return type. Regenerate. The compiler immediately tells you which controllers don't match:

```typescript
// If the spec changes showPetById to require a 'query' parameter:
// error TS2420: Class 'PetsController' incorrectly implements interface
//   'Pick'.
//   Property 'showPetById' is incompatible...
```

The build fails. *Before* you ever push to production or staging.

### The one thing that changes: parameter style

For `implements` to work, your controller methods need to match the generated signatures. That means switching from per-field parameter extraction to whole-object style:

```typescript
// BEFORE - the style most NestJS devs use
@Get(':petId')
async showPetById(@Param('petId') petId: string) {
  const pet = this.pets.find((p) => p.id === petId);
  // ...
}

// AFTER - whole-object style, works with implements
@Get(':petId')
async showPetById(@Param() path: ShowPetByIdData['path']) {
  const pet = this.pets.find((p) => p.id === path.petId);
  // ...
}
```

The change is small. Instead of `@Param('petId') petId: string` you write `@Param() path: ShowPetByIdData['path']` and access `path.petId`. Same for `@Query()` and `@Body()`. The [NestJS docs](https://docs.nestjs.com/controllers#request-payloads) cover this style—it's just less common than per-field extraction.

This is the tradeoff. You give up the convenience of named parameter decorators. You get compile-time contract enforcement in return. For us, it was worth it.

## What this doesn't do (and why that's fine)

The plugin generates types. That's it. It doesn't do routes, validation, or Swagger UI.

You'll still write `@Get()`, `@Post()`, `@Controller('pets')` yourself. NestJS owns routing through decorators. No codegen tool can replace that without replacing the framework. And if you need Swagger UI served from your NestJS app, you still use `@nestjs/swagger`. The plugin doesn't generate documentation, it generates type constraints.

Runtime validation is also outside the scope. So if a client sends `{ name: 123 }` instead of `{ name: "Fido" }`, the plugin won't catch it. That's still a job for `class-validator`, Zod pipes, or whatever validation layer you already have.

What the plugin does is narrow: compile-time contract compliance. Your controller method signatures must match the spec. If they don't, the build fails. NestJS already has good answers for routing and validation and documentation. The missing piece was "does my controller actually match the contract?" Now there's an answer for that too.

## Where this fits in the contract-first stack

Over this series we've built a contract-first workflow piece by piece. The spec lives in a [dedicated repository](https://evilmartians.com/chronicles/contract-shock-therapy-the-way-to-api-first-documentation-bliss) as the single source of truth. The frontend [generates TypeScript types, SDK functions, and MSW mocks](https://evilmartians.com/chronicles/lifes-too-short-to-hand-write-api-types-openapi-driven-react) from it. A Fastify backend can [wire routes and validate requests](https://evilmartians.com/chronicles/openapi-fastify-backend-let-the-contract-build-your-server) from the same spec. And now NestJS controllers can enforce method signatures against it at compile time.

Same spec. Different tools on each side. Change the spec, regenerate, fix the type errors. That's the whole workflow.

We built the NestJS plugin at [Evil Martians](https://evilmartians.com/) and [contributed it](https://github.com/hey-api/openapi-ts/pull/3573) to Hey API because the NestJS ecosystem didn't have a spec-first type enforcement tool. It's [open source](https://github.com/hey-api/openapi-ts) and [documented](https://heyapi.dev/openapi-ts/plugins/nest). The code-first flow is fine for many projects. But when the spec is a shared contract between teams, having the compiler verify your controllers against it saves a lot of late-night debugging.

---

**Ship faster** Hire Evil Martians to wire your OpenAPI spec into NestJS, Fastify, or React and make sure the compiler catches contract drift before your users do. [Contact Evil Martians](https://evilmartians.com/contact-us)
