Express에서 Swagger를 이용한 API DOC 만들기
2020-01-12 20:21:33

팀원에 의해 알게 된 swagger! 궁금해서 한 번 도전해봣다.

설치

1
yarn add swagger-ui-express

swagger document 작성

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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217

module.exports = {
openapi: '3.0.1',
info: {
version: '0.0.1',
title: 'swagger 적용해보기.',
description: 'example API',
termsOfService: 'http://api_url/terms/',
contact: {
name: 'delryn',
email: 'hidelryn@gmail.com',
url: 'https://hidelryn@github.io'
},
license: {
name: 'Apache 2.0',
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
}
},
servers: [
{
url: 'http://localhost:3000/',
description: 'Local server'
},
{
url: 'https://api_url_testing',
description: 'Testing server'
},
{
url: 'https://api_url_production',
description: 'Production server'
}
],
security: [
{
ApiKeyAuth: []
}
],
tags: [
{
name: 'test operations'
}
],
paths: {
'/getUser': {
get: {
tags: ['test operations'],
description: '유저 데이터 불러오기',
operationId: 'getUser',
parameters: [
{
name: 'id',
in: 'query',
"schema": {
"$ref": "#/components/schemas/userid"
},
required: true
},
],
responses: {
'200': {
description: '유저 데이터 불러오기',
content: {
'application/json': {
schema: {
$ref: '#/components/schemas/User'
}
}
}
},
'400': {
description: '파라미터가 생략 돠었음',
content: {
'application/json': {
schema: {
$ref: '#/components/schemas/Error'
},
example: {
message: 'id가 생략 되었음',
internal_code: 'missing_parameters'
}
}
}
}
}
},
},
"/createUser": {
post: {
tags: ['test operations'],
description: '유저 데이터 생성',
operationId: 'createUser',
parameters: [
{
"name": "name",
"in": "body",
"description": "유저 이름",
"schema": {
"$ref": "#/components/schemas/username"
},
required: true
},
{
"name": "age",
"in": "body",
"description": "유저 나이",
"schema": {
"$ref": "#/components/schemas/userage"
},
required: true
}
],
requestBody: {
content: {
'application/json': {
schema: {
$ref: '#/components/schemas/reqUser'
},
required: true,
}
},
},
responses: {
'200': {
description: '유저 생성 완료',
content: {
'application/json': {
schema: {
$ref: '#/components/schemas/User'
},
}
}
},
'400': {
description: '파라미터가 생략 되었음',
content: {
'application/json': {
schema: {
$ref: '#/components/schemas/Error'
},
example: {
message: '이름 또는 나이가 생략 되었다',
internal_code: 'invalid_parameters'
}
}
}
}
}
},
},
},
components: {
schemas: {
userid: {
type: 'string',
description: '유저 고유 아이디',
example: 'qjrkqnek23nvie'
},
username: {
type: 'string',
description: '유저 이름',
example: 'delryn'
},
userage: {
type: 'integer',
description: '유저 나이',
example: 33,
},
reqUser: {
type: 'object',
properties: {
name: {
$ref: '#/components/schemas/username'
},
age: {
$ref: '#/components/schemas/userage'
}
}
},
User: {
type: 'object',
properties: {
id: {
$ref: '#/components/schemas/userid'
},
name: {
$ref: '#/components/schemas/username'
},
age: {
$ref: '#/components/schemas/userage'
}
}
},
// Users: {
// type: 'object',
// properties: {
// users: {
// type: 'array',
// items: {
// $ref: '#/components/schemas/User'
// }
// }
// }
// },
Error: {
type: 'object',
properties: {
message: {
type: 'string'
},
internal_code: {
type: 'string'
}
}
}
},
}
};

코드로 api 문서를 정의한다고 생각하면 됨.

어플리케이션 적용

간단한 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

const express = require('express');
const bodyParser = require('body-parser');
const redis = require('redis');
const nanoid = require('nanoid');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.js');

const app = express();
const PORT = process.env.PORT || 3000;
const redisClient = redis.createClient();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.get('/getUser', (req, res) => {
const userId = req.query.id;
if (!userId) {
return res.json({ code: 400, message: 'Missing parameters' });
}
redisClient.hget('swaggerUser', userId, (err, data) => {
if (err) return res.json({ code: 500, message: 'System error' });
if (!data) return res.json({ code: 403, message: 'None user' });
const parse = JSON.parse(data);
return res.json({ code: 200, data: parse });
});
});

app.post('/createUser', (req, res) => {
const { name, age } = req.body;
if (!age || !name) {
return res.json({ code: 500, message: 'Missing parameters' });
}
const id = nanoid();
const data = {id, name, age};
redisClient.hset('swaggerUser', id, JSON.stringify(data), (err) => {
if (err) return res.json({ code: 500, message: 'System error' });
return res.json({ code: 200, data });
});
});

app.listen(PORT, () => {
console.log('server is listening');
});

실제 swagger 적용한 코드는 이러하다.

1
2
3
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.js');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

어플리케이션을 기동 시 localhost:3000/api-doc로 접속을 하게 되면 적용된 화면이 나옴.

결과