API Developmentbeginner
Generate OpenAPI/Swagger documentation from code
API Documentation
Generate OpenAPI/Swagger documentation from code
Generate OpenAPI/Swagger documentation from existing code.
Instructions
- Install swagger tools:
npm install swagger-jsdoc swagger-ui-express # Express
# or use Zod-to-OpenAPI for Next.js
npm install @asteasolutions/zod-to-openapi
- Add JSDoc annotations to routes:
/**
* @openapi
* /api/users:
* post:
* summary: Create a new user
* tags: [Users]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CreateUser'
* responses:
* 201:
* description: User created
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* 400:
* description: Validation error
*/
- Generate the spec:
import swaggerJsdoc from 'swagger-jsdoc';
const spec = swaggerJsdoc({
definition: {
openapi: '3.0.0',
info: { title: 'My API', version: '1.0.0' },
servers: [{ url: '/api' }],
},
apis: ['./src/routes/*.ts'],
});
- Serve at /api/docs.
Rules
- Document every endpoint: method, params, body, responses, errors
- Include example request/response for each endpoint
- Keep docs in sync — regenerate on build