[[:oktatas:web:back-end_framework:express:swagger|< Swagger]]
====== Express - Swagger JSON fájl ======
* **Szerző:** Sallai András
* Copyright (c) 2023, Sallai András
* Szerkesztve: 2024
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]]
* Web: https://szit.hu
===== Projekt =====
mkdri app01
cd app01
npm init -y
Függőségek:
pnpm install --save express nodemon morgan
pnpm install --save-dev swagger-jsdoc swagger-ui-express
Script:
{
"scripts": {
"start":"nodemon app --watch app"
}
}
===== Szerver =====
const express = require('express')
const app = new express()
const morgan = require('morgan')
const router = require('./routes/api')
const PORT = process.env.PORT || 8000;
app.use(express.json())
app.use(morgan('tiny'))
app.use(router)
app.listen(PORT, () => {
console.log('Server is running on port: ', PORT)
})
===== Swagger hozzáadása =====
const express = require('express')
const app = new express()
const morgan = require('morgan')
const router = require('./routes/api')
const swaggerUi = require('swagger-ui-express')
const swaggerDocument = require('../swagger.json')
const PORT = process.env.PORT || 8000;
app.use('/swagger', swaggerUi.serve)
app.get('/swagger', swaggerUi.setup(swaggerDocument))
app.use(express.json())
app.use(morgan('tiny'))
app.use(router)
app.listen(PORT, () => {
console.log('Server is running on port: ', PORT)
})
===== Router =====
const router = require('express').Router();
router.get('/ping', async (req, res) => {
res.send({message: 'Helló'})
})
module.exports = router
===== swagger.json fájl =====
{
"swagger": "2.0",
"paths": {
"/ping": {
"get": {
"operationId": "pingEndpoint",
"description": "Egyszerű elérés ellenőrzés",
"responses": {
"200": {
"description": "Siker"
}
}
}
}
}
}
Nézzük meg az eredményt:
* http://localhost:8000/api-docs/
===== Read művelet =====
{
"swagger": "2.0",
"basePath": "/api",
"paths": {
"/employees": {
"get": {
"description": "Dolgozók lekérése",
"responses": {
"200": {
"description": "Siker"
}
}
}
}
}
}