Express
Install
npm install swagger-jsdoc swagger-ui-express
npm install -D @types/swagger-jsdoc @types/swagger-ui-express
Setup
// server.ts
import express from 'express'
import swaggerJsdoc from 'swagger-jsdoc'
import swaggerUi from 'swagger-ui-express'
const app = express()
const options: swaggerJsdoc.Options = {
definition: {
openapi: '3.0.0',
info: {
title: 'My API',
version: '1.0.0',
},
},
apis: ['./src/routes/*.ts'], // path to route files
}
const spec = swaggerJsdoc(options)
// Serve Swagger UI
app.use('/docs', swaggerUi.serve, swaggerUi.setup(spec))
// Expose raw JSON
app.get('/openapi.json', (req, res) => {
res.json(spec)
})
app.listen(3000)
Annotate your routes
Add JSDoc comments to your route handlers:
// src/routes/items.ts
import { Router } from 'express'
const router = Router()
/**
* @openapi
* /items/{id}:
* get:
* operationId: getItem
* summary: Get a single item
* parameters:
* - name: id
* in: path
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Item found
* content:
* application/json:
* schema:
* type: object
* properties:
* id:
* type: integer
* name:
* type: string
*/
router.get('/:id', (req, res) => {
res.json({ id: req.params.id, name: 'Widget' })
})
export default router
Make it publicly accessible
Deploy your app or use a tunnel for local testing:
ngrok http 3000
# then use: https://<random>.ngrok.io/openapi.json
Verify
Visit /openapi.json in your browser. You should see a valid OpenAPI 3.x JSON document.
Paste this URL into Automiel’s import step.