Back to snippets
express_swagger_autogen_autodoc_with_swagger_ui.ts
typescriptThis quickstart uses swagger-autogen to automatically generate S
Agent Votes
0
0
express_swagger_autogen_autodoc_with_swagger_ui.ts
1import express, { Request, Response } from 'express';
2import swaggerUi from 'swagger-ui-express';
3import fs from 'fs';
4import path from 'path';
5
6const app = express();
7const port = 3000;
8
9/**
10 * Note: In a real-world scenario, you would run the 'swagger-autogen'
11 * script separately to generate the 'swagger-output.json' file.
12 */
13const swaggerFile = JSON.parse(fs.readFileSync(path.join(__dirname, './swagger-output.json'), 'utf8'));
14
15app.use(express.json());
16
17// Routes
18app.get('/users', (req: Request, res: Response) => {
19 // #swagger.tags = ['User']
20 // #swagger.description = 'Endpoint to get all users.'
21 res.status(200).send([
22 { id: 1, name: 'John Doe' },
23 { id: 2, name: 'Jane Doe' }
24 ]);
25});
26
27app.post('/users', (req: Request, res: Response) => {
28 // #swagger.tags = ['User']
29 // #swagger.description = 'Endpoint to create a new user.'
30 /* #swagger.parameters['obj'] = {
31 in: 'body',
32 description: 'User information.',
33 required: true,
34 schema: { $name: 'John Doe', $age: 29 }
35 } */
36 const newUser = req.body;
37 res.status(201).send(newUser);
38});
39
40// Swagger UI Route
41app.use('/doc', swaggerUi.serve, swaggerUi.setup(swaggerFile));
42
43app.listen(port, () => {
44 console.log(`Server is running at http://localhost:${port}`);
45 console.log(`Swagger documentation available at http://localhost:${port}/doc`);
46});