2021-12-10
아래에 소개할 글은 서버의 종류에 상관 없이, swagger를 API문서 취급으로 사용 할때 필요한 내용이다.

일단 express, swagger-ui-express 모듈을 설치한다
$ npm i express swagger-ui-express --save

설치 디렉토리 위치에 index.js파일을 하나 만들고 아래와 같은 소스를 짠다

index.js
const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
// swagger.json: api 형식을 지정할 문서
const swaggerDocument = require('./swagger.json');

// 3300포트를 사용
app.listen(3300, () => {
	console.log('Server started at http://localhost:3300');
});

// http://localhost:3300/api-docs에 접속시 페이지 표시됨
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
보통은 swagger지정부분과 express부분을 각각 다른 파일에 만들고 참조 하기도 하는데, api문서로만 쓸 거라서 그냥 하나로 합쳤다

자 그럼 마지막으로 swagger.json문서를 하나 만들어 보자
참고(swagger.json 예제): https://github.com/OAI/OpenAPI-Specification/tree/main/examples/v2.0/json
참고(데이터타입): https://swagger.io/docs/specification/data-models/data-types/

swagger.json
{
	"swagger": "2.0",
	"info": {
		"version": "1.0.0", #버전
		"title": "제목",
		"description": "간단한 설명",
		"termsOfService": "http://swagger.io/terms/",
		"contact": {
			"name": "contact할 곳 이름",
			"email": "이메일",
			"url": "주소"
		},
		"license": {
			"name": "라이선스 이름",
			"url": "라이선스 주소"
		}
	},
	"host": "host 주소",
	"basePath": "/", #기본 주소
	"schemes": [
	"http"
	],
	"consumes": [
	"application/json"
	],
	"produces": [
	"application/json"
	],
	"paths": {
		"/auth/token": {
			"get": {
				"description": "접속 token을 획득",
				"parameters": [
					{
						"name": "id",
						"in": "query", # path, header, body, query
						"description": "아이디",
						"required": true,
						"type": "string" #string, boolean, integer, number, array
					}
				],
				"responses": {
					"200": {
						"description": "성공",
						"schema": {
							"$ref": "#/definitions/auth_token"
						}
					},
					"400": {
						"description": "실패",
						"schema": {
							"$ref": "#/definitions/default_error"
						}
					}
				}
			}
		}
	},
	"definitions": {
		"auth_token": {
			"type": "object",
			"properties": {
				"code": {
					"type": "integer",
					"format": "int32"
				},
				"data": {
					"type": "object",
					"properties": {
						"token": {
							"type": "string"
						}
					}
				}
			}
		},
		"default_error": {
			"type": "object",
			"properties": {
				"code": {
					"type": "integer",
					"format": "int32"
				},
				"data": {
					"type": "object",
					"properties": {
						"msg": {
							"type": "string"
						}
					}
				}
			}
		}
	}
}
.json파일에는 주석을 쓸 수 없기 때문에, #으로 된 주석은 소스에서 설명을 돕기 위해 추가 한 것이고, 실제로는 저렇게 쓰면 안된다.

마지막으로 node index.js 식으로 실행을 해보면, 보통은 CORS에러가 뜰 것이다
해당 기능은 엄연히 웹 페이지에서 API를 요청 하는 것이고, 위에서 언급 했듯이, 같은 서버가 아닌 다른 서버의 API를 문서화 해서 보여주는 기능이기 때문에, 실제로 해보면 크로스 브라우징 에러가 뜨게 될 것 이다.
그래서 API가 구현된 서버에서, swagger가 설치된 호스트를 허용 시켜주는 구문을 추가 시켜 주어야 한다.

php라면 아래와 같이 header값을 추가하면 된다.
<?php
header('Access-Control-Allow-Origin: {swagger가 구현 되어 있는 host url}');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Credentials: true');
?>