Created
March 16, 2024 03:54
-
-
Save mildronize/a5be19b9ef1be225cd3d072fa3a5d6af to your computer and use it in GitHub Desktop.
Example of Express + Zod + Zod to OpenAPI + Swagger UI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from 'express'; | |
import morgan from 'morgan'; | |
import swaggerUi from 'swagger-ui-express'; | |
import { extendZodWithOpenApi, OpenApiGeneratorV3, OpenAPIRegistry } from '@asteasolutions/zod-to-openapi'; | |
import { z } from 'zod'; | |
extendZodWithOpenApi(z); | |
const host = process.env.HOST ?? 'localhost'; | |
const port = process.env.PORT ? Number(process.env.PORT) : 3000; | |
const app = express(); | |
// parse json request body | |
app.use(express.json()); | |
// parse urlencoded request body | |
app.use(express.urlencoded({ extended: true })); | |
app.use(morgan('dev')); | |
export const registry = new OpenAPIRegistry(); | |
const UserSchema = z | |
.object({ | |
id: z.string().openapi({ example: '1212121' }), | |
name: z.string().openapi({ example: 'John Doe' }), | |
age: z.number().openapi({ example: 42 }), | |
}) | |
.openapi('User'); | |
registry.registerPath({ | |
method: 'get', | |
path: '/users/{id}', | |
summary: 'Get a single user', | |
request: { | |
params: z.object({ id: z.string() }), | |
headers: z.object({ 'x-api-key': z.string() }), | |
query: z.object({ fields: z.string() }), | |
}, | |
responses: { | |
200: { | |
description: 'Object with user data.', | |
content: { | |
'application/json': { | |
schema: UserSchema, | |
}, | |
}, | |
}, | |
}, | |
}); | |
const generator = new OpenApiGeneratorV3(registry.definitions); | |
const swaggerDocument = generator.generateDocument({ | |
openapi: '3.0.0', | |
info: { | |
version: '1.0.0', | |
title: 'My API', | |
description: 'This is the API', | |
}, | |
servers: [{ url: 'v1' }], | |
}); | |
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); | |
app.use('/', (req, res) => { | |
res.send('Hello World'); | |
}); | |
app.listen(port, host, () => { | |
console.log(`[ ready ] http://${host}:${port}`); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"dependencies": { | |
"@asteasolutions/zod-to-openapi": "^6.4.0", | |
"express": "~4.18.1", | |
"morgan": "^1.10.0", | |
"swagger-ui-express": "^5.0.0", | |
"zod": "^3.22.4" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment