swagger란
API 명세를 설계하고 문서화를 해주는데 도움을 주는 기술(협업할 때 유용)
Open API Specification(OAS)를 위한 프레임워크
간단한 설정으로 프로젝트에서 지정한 URL들을 HTML 화면으로 확인할 수 있게 해주는 프로젝트
api명세가 필요한 이유
- 협업을 진행하거나 이미 만들어져 있는 프로젝트에 대해 유지보수를 진행하기 위해서 구축되어 있는 API가 어떤 스펙을 갖고 있는지 알아야 한다.
- API 명세서가 없다면, 코드를 전부 확인하는 과정에서 개발 시간이 너무 오래 걸린다.
- 프론트는 백앤드에게 API가 어떻게 동작하는지 물어보면서 개발해야 한다.
- 개발할 때는 시간이 적게 걸릴 수 있지만, 유지 보수를 할 때, 시간이 상당히 오래 걸린다.
api 명세를 작성하는 여러 방법
보통 프론트와 백앤드가 협업을 할 때 api 명세를 git이나 구글 doc, wiki 등 텍스트 문자를 통해 API 문서를 정의해 공유하는데 수정사항이 생기면 따로 문서를 수정해줘야 하는 번거로움이 있다.
Postman을 통해 API를 정의하고 공유하기도 하는데 이는 api 정보들이 postman에 저장되기 때문에 보안에 문제가 생길 수 있다.
swagger를 활용하면 자체 api서버에 연결하여 따로 문서를 만들고, 수정하는 것이 아닌 직접 코드로 만들어 공유하고, 정보들도 다른 서버에 저장하는 게 아니라 직접 구축한 서버에 저장하여 보안을 강화시켜줄 수 있다.
swagger 사용법
설치
npm i swagger-jsdoc swagger-ui-express --save-dev
swagger.js 파일 생성
app.js. 와 같은 위치에 생성(어디든 상관없다.)
swagger의 기본적인 옵션을 설정하고, 파일의 위치, 연결한 서버의 주소 등을 설정한다.
// swagger.js
const swaggerUi = require("swagger-ui-express");
const swaggereJsdoc = require("swagger-jsdoc");
const options = {
swaggerDefinition: {
components: {},
info: { // info 객체는 title, version, description을 설정
title: "TEST API",
version: "1.0.0",
description: "test api",
},
securityDefinitions: { // 헤더의 Authorization안에 값을 넣어줄수 있는 기능
Authorization: {
type: "apiKey",
name: "authorization",
scheme: "bearer",
in: "header",
},
},
security: [ // 헤더의 Authorization안에 값을 넣어줄수 있는 기능
{
Authorization: [],
},
],
host: "localhost:3000",
basePath: "/api/",
},
apis: ["./routes/*.js", "./swagger/*"], // api는 /routes 파일 아래 js 파일 내에 정의하고 있으며, /swagger 폴더 아래 swagger 설정을 정의하고 있다
};
const specs = swaggereJsdoc(options);
module.exports = { swaggerUi, specs };
app.js 설정
const { swaggerUi, specs } = require("./swagger");
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(specs)); // /api-docs라는 path로 등록
swagger 정의
swagger 폴더 생성 후 users.yaml 파일 생성(폴더는 routes와 같은 위치에 생성했다.)
// /swagger/posts.yaml
paths:
/post/:
get:
tags:
- post
description: 게시물 보여주기
responses:
200:
description: 게시물 보여주기
schema:
properties:
ok:
type: boolean
result:
type: array
items:
type: object
properties:
postId:
type: integer
title:
type: string
images:
type: string
category:
type: string
loginId:
type: string
400:
description: 게시물 보여주기 실패
schema:
properties:
ok:
type: boolean
errorMessage:
type: string
/post:
post:
# security:
# - Authorization: []
tags:
- post
description: 게시물 생성
parameters:
- in: body
name: body
required: true
schema:
properties:
title:
type: string
images:
type: string
category:
type: string
content:
type: string
responses:
200:
description: 게시물 생성 성공
schema:
properties:
ok:
type: boolean
message:
type: string
401:
description: 로그인이 안되어 있음
schema:
properties:
ok:
type: boolean
errorMessage:
type: string
400:
description: 유효성 검사 실패 / 게시물 생성 실패
schema:
properties:
ok:
type: boolean
errorMessage:
type: string
/post/{postId}:
get:
tags:
- post
description: 게시물 상세 조회
parameters:
- in: path
name: postId
required: true
schema:
type: integer
responses:
200:
description: 게시물 상세 조회
schema:
properties:
ok:
type: boolean
result:
type: object
properties:
postId:
type: integer
title:
type: string
images:
type: string
category:
type: string
loginId:
type: string
400:
description: 해당 게시물을 찾을 수 없습니다. / 게시물 상세 보여주기 실패
schema:
properties:
ok:
type: boolean
errorMessage:
type: string
/post/{postId}:
put:
tags:
- post
description: 게시물 수정
parameters:
- in: path
name: postId
required: true
schema:
type: integer
- in: body
name: body
required: true
schema:
properties:
title:
type: string
images:
type: string
category:
type: string
content:
type: string
responses:
200:
description: 게시물 수정 성공
schema:
properties:
ok:
type: boolean
message:
type: string
401:
description: 로그인이 안되어 있음
schema:
properties:
ok:
type: boolean
errorMessage:
type: string
400:
description: 유효성 검사 실패 / 해당 게시물을 찾을수 없습니다. / 작성자가 일치하지 않습니다. / 게시물 수정 실패
schema:
properties:
ok:
type: boolean
errorMessage:
type: string
식으로 swagger를 설정
swagger 사용법
swagger 페이지에 들어가 api명세를 확인할 수 있다.
api 마다 설정한 경로, 메서드, 요청 값, 응답 값 status 등 여러 정보들을 확인할 수 있다.
요청 값으로 파라미터 들어가는지, 바디에 무엇을 넣어주어야 하는지 등
응답 값으로 어떤 데이터들을 주는지 요청, 응답 값 모두 데이터 타입은 어떻게 되는지 확인할 수 있다.
Try it out을 누르면 실제로 동작하는 모습도 확인할 수 있다.
적절한 요청 값을 넣고 Execute를 눌러 실행한다.
실행 시 실제로 동작이 실행된다.(디비 저장이 되는 것이다.)
만약 로그인 절차 확인을 위해 토큰을 사용한다면
swagger 페이지 첫 부분에 Authorize 버튼을 눌러 토큰 값을 헤더의 Authorization에 넣어 api요청을 하게 된다.
이 부분은 처음 swagger.js에서 옵션으로 설정해주어야 가능하다.
필자는 Bearer 토큰 값을 확인하기 때문에 저렇게 넣어주었다.
이상으로 swagger 설치 및 설정, 사용법에 대해 작성했다.
아직 중복 코드를 줄일 수 있는 component의 개념이나 사용을 하지 못해서 다음에 정리해 보겠다.
Nodejs Swagger unable to add authorization header to requests
I am trying to add an authorization header to Swagger UI using Node.js Express server. Requests need to have x-auth-token as one of the headers for the API to get authenticated. Below is my app.js ...
stackoverflow.com
[Node.js] Swagger 사용하기
● Swagger 란? API 명세를 도와주는 도구 (협업을 할 때 유용) API 명세 : 프론트엔드와 백엔드 사이에서 어떤 방식으로 데이터를 주고 받을지에 대해 명세하는 것 ● 사용방법 0. 간단한 로그인 기능
chb2005.tistory.com
[협업] 협업을 위한 swagger 설정하기 (feat node.js)
들어가며 스타트업에서 서버 개발자로 일하면서, 불편한 점을 하나씩 해결하고자 노력하고 있습니다. 그중, 하나가 API 명세서 작성에 관한 부분이었습니다. 처음 팀에 합류하고 API 개발을 위해
overcome-the-limits.tistory.com
'coding > Node.js' 카테고리의 다른 글
express HTTPS 설정 (0) | 2022.08.20 |
---|---|
비밀번호 암호화 - bcrypt (0) | 2022.08.17 |
CORS 사용방법 (0) | 2022.08.14 |
Sequelize 시작, migrate 사용 관계 설정 (0) | 2022.08.13 |
node.js Controller, Service, Repository (1) | 2022.08.07 |