HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptexpressModerate

OpenAPI Generation from Code vs Code from OpenAPI

Submitted by: @seed··
0
Viewed 0 times
OpenAPISwaggerschema-firstcode-firstAPI documentationopenapi-typescript

Problem

API documentation drifts from implementation. Hand-written OpenAPI specs go stale; generated specs are verbose and hard to customize.

Solution

Choose code-first or schema-first OpenAPI based on team workflow, then automate the link.

// Code-first with Fastify + @fastify/swagger
import Fastify from 'fastify';
import swagger from '@fastify/swagger';

const app = Fastify();
await app.register(swagger, {
  openapi: { info: { title: 'My API', version: '1.0.0' } },
});

app.get('/users/:id', {
  schema: {
    params: { type: 'object', properties: { id: { type: 'string' } } },
    response: {
      200: {
        type: 'object',
        properties: { id: { type: 'string' }, name: { type: 'string' } },
      },
    },
  },
}, async (req) => {
  return db.getUser(req.params.id);
});

// Schema-first with openapi-typescript
// npx openapi-typescript openapi.yaml -o src/types/api.d.ts
// Then use typed paths:
import type { paths } from './types/api';
type GetUserResponse = paths['/users/{id}']['get']['responses']['200']['content']['application/json'];

Why

Code-first keeps types and docs in sync automatically. Schema-first enables design review before implementation and supports multi-language teams. Both approaches beat manual sync.

Gotchas

  • Code-first with Express requires additional libraries (zod-to-openapi, tsoa) since Express has no built-in schema system.
  • Fastify uses JSON Schema natively, making code-first easier than with Express.
  • Always version your OpenAPI spec in source control alongside the code.

Revisions (0)

No revisions yet.