#swagger

swagger-ui-express 설치하기

1
npm i swagger-ui-express

package.json에 swagger-ui-express 추가하기

1
"swagger-ui-express": "latest" // or desired version

swagger js-doc 설치하기

기존에 있던 js 파일에서 api를 따오기 위해 swagger jsdoc을 설치한다.

1
npm install swagger-jsdoc --save

swagger-jsdoc 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var swaggerJSDoc = require('swagger-jsdoc');

var options = {
swaggerDefinition: {
info: {
title: 'Hello World', // Title (required)
version: '1.0.0', // Version (required)
},
},
apis: ['./routes.js'], // Path to the API docs
};

// Initialize swagger-jsdoc -> returns validated swagger spec in json format
var swaggerSpec = swaggerJSDoc(options);

app.js 세팅하기

1
2
3
4
5
6
const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = swaggerJSDoc(options)

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

document the api

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* @swagger
* /login:
* post:
* description: Login to the application
* produces:
* - application/json
* parameters:
* - name: username
* description: Username to use for login.
* in: formData
* required: true
* type: string
* - name: password
* description: User's password.
* in: formData
* required: true
* type: string
* responses:
* 200:
* description: login
*/
app.post('/login', function(req, res) {
res.json(req.body);
});

Model Definition을 통한 재사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* @swagger
* definitions:
* NewUser:
* type: object
* required:
* - username
* - password
* properties:
* username:
* type: string
* password:
* type: string
* format: password
* User:
* allOf:
* - $ref: '#/definitions/NewUser'
* - required:
* - id
* - properties:
* id:
* type: integer
* format: int64
*/

/**
* @swagger
* /users:
* get:
* description: Returns users
* produces:
* - application/json
* responses:
* 200:
* description: users
* schema:
* type: array
* items:
* $ref: '#/definitions/User'
*/
app.get('/users', function(req, res) {
res.json([ {
id: 1,
username: 'jsmith',
}, {1
id: 2,
username: 'jdoe',
} ]);
});

/**
* @swagger
* /users:
* post:
* description: Returns users
* produces:
* - application/json
* parameters:
* - name: user
* description: User object
* in: body
* required: true
* type: string
* schema:
* $ref: '#/definitions/NewUser'
* responses:
* 200:
* description: users
* schema:
* $ref: '#/definitions/User'
*/
app.post('/users', function(req, res) {
// Generate ID
req.body.id = Math.floor(Math.random() * 100) * 1
res.json(req.body);
});

swagger-ui-express 공식 문서
swagger-jsdoc 공식 문서

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×