BE
Domain: Documentation / Coding
Difficulty: Difficult
Description:
The API lacks interactive documentation. Set up Swagger (OpenAPI 3.0) to provide:
- Auto-generated API documentation from code annotations
- Interactive Swagger UI endpoint (/api-docs)
- ReDoc documentation alternative (/redoc)
- Try-out functionality in Swagger UI
- Clear parameter and response documentation
- Authentication scheme documentation (if applicable)
- Download API specification in JSON/YAML format
Install and configure:
- swagger-ui-express - Swagger UI for Express
- swagger-jsdoc - JSDoc to OpenAPI converter
- Create swagger.config.ts with OpenAPI definition
- Annotate controller endpoints with OpenAPI decorators
Expected Outcome:
- Interactive API documentation at /api-docs.
- Swagger UI with try-it-out functionality
- OpenAPI specification in JSON format
- All endpoints documented with parameters and responses
- Clear error response documentation
- Frontend developers can easily understand the API
- Better developer experience and onboarding
Setup Steps:
- Install packages: npm install swagger-ui-express swagger-jsdoc.
- Install types: npm install --save-dev @types/swagger-ui-express.
- Create src/swagger.config.ts with OpenAPI 3.0 definition
- Define basic API info, servers, and security schemes
- Add JSDoc comments to all controller endpoints:
`typescript /**- @swagger
- /actors/search:
- get:
- summary: Search for actors by name
- parameters:
- - name: name
- in: query
- required: true
- schema:
- type: string
- responses:
- 200:
- description: Array of actor results
- 400:
- description: Missing name parameter
- 500:
- description: Server error */ `
- Create routes for Swagger UI in src/server.js:
`javascript import swaggerUi from 'swagger-ui-express'; import swaggerDocument from './swagger.config.js'; app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); `
- Test at http://localhost:3001/api-docs
- Verify all endpoints appear in the UI
- Test try-it-out functionality
Links/References:
- Swagger UI: swagger-ui-express npm package
- Swagger JSDoc: swagger-jsdoc npm package
- OpenAPI 3.0 Specification: https://spec.openapis.org/oas/v3.0.3
- Create: src/swagger.config.ts
- Update: All controller files with JSDoc
- Update: src/server.js to mount Swagger UI