Swagger — это программная среда с открытым исходным кодом, которая помогает разработчикам проектировать, создавать, документировать и использовать веб-сервисы RESTful. Он предоставляет набор инструментов, которые позволяют разработчикам описывать структуру API стандартным способом, упрощая их понимание и использование. Swagger позволяет разработчикам создавать документацию по API, которая является машиночитаемой и удобной для человека, что упрощает общение с другими разработчиками и заинтересованными сторонами.
Как мы можем добавить его в ваш проект?
Во-первых, в этом примере будет использоваться фиктивная модель под названием Publication, которая состоит из двух атрибутов: name и content.
Монтаж
Убедитесь, что в вашем проекте Node.js установлены и swagger-ui-express
, и swagger-jsdoc
:
npm install swagger-ui-express swagger-jsdoc
Конфигурация
Создайте файл с именем app.js
и добавьте следующий код:
const express = require('express'); const swaggerUi = require('swagger-ui-express'); const swaggerJsDoc = require('swagger-jsdoc'); const app = express(); // Swagger configuration options const swaggerOptions = { swaggerDefinition: { info: { title: 'Publication API', description: 'CRUD API for managing publications', version: '1.0.0', }, }, apis: ['./routes/*.js'], // Path to the API routes folder }; const swaggerDocs = swaggerJsDoc(swaggerOptions); app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs)); // Routes app.use('/publications', require('./routes/publications')); // Start the server app.listen(3000, () => { console.log('Server running on port 3000'); });
Документация
Создайте папку с именем routes
в том же каталоге, что и app.js
. Внутри папки routes
создайте файл с именем publications.js
и добавьте следующий код:
const express = require('express'); const router = express.Router(); /** * @swagger * /publications: * get: * summary: Get all publications * responses: * 200: * description: Returns all publications */ router.get('/', (req, res) => { // Implementation for getting all publications }); /** * @swagger * /publications/{id}: * get: * summary: Get a publication by ID * parameters: * - in: path * name: id * required: true * schema: * type: string * description: Publication ID * responses: * 200: * description: Returns the publication with the specified ID * 404: * description: Publication not found */ router.get('/:id', (req, res) => { // Implementation for getting a publication by ID }); /** * @swagger * /publications: * post: * summary: Create a new publication * parameters: * - in: body * name: publication * required: true * schema: * type: object * properties: * name: * type: string * content: * type: string * description: Publication object * responses: * 201: * description: Publication created successfully */ router.post('/', (req, res) => { // Implementation for creating a new publication }); /** * @swagger * /publications/{id}: * put: * summary: Update a publication by ID * parameters: * - in: path * name: id * required: true * schema: * type: string * description: Publication ID * - in: body * name: publication * required: true * schema: * type: object * properties: * name: * type: string * content: * type: string * description: Updated publication object * responses: * 200: * description: Publication updated successfully * 404: * description: Publication not found */ router.put('/:id', (req, res) => { // Implementation for updating a publication by ID }); /** * @swagger * /publications/{id}: * delete: * summary: Delete a publication by ID * parameters: * - in: path * name: id * required: true * schema: * type: string * description: Publication ID * responses: * 200: * description: Publication deleted successfully * 404: * description: Publication not found */ router.delete('/:id', (req, res) => { // Implementation for deleting a publication by ID }); module.exports = router;
Вот и все! Теперь у вас есть базовая реализация swagger-ui-express
и swagger-jsdoc
для документирования API CRUD для объекта Публикация. Вы можете запустить сервер, запустив node app.js
, а затем получить доступ к документации пользовательского интерфейса Swagger в http://localhost:3000/api-docs
.