언어·프레임워크/Node.js

[Node.js] Swagger을 이용한 API 문서 생성

DandyNow 2024. 1. 24. 17:27
728x90
반응형

1. Swagger 설치

swagger-ui-express, swagger-autogen를 설치한다. swagger-ui-express는 서버 구동 시 API 문서를 볼 수 있게 해 주고, swagger-autogen는 API 문서 정보를 담고 있는 swagger-output.json을 자동으로 생성해 준다.

npm install swagger-ui-express swagger-autogen

 

2. ES Modules

ES Modules 방식은 아래와 같이 Swagger json 파일을 import 하면 된다. 이때 주의할 것은 assert { type: "json"}을 추가하지 않으면 TypeError가 발생한다.

// app.js

import swaggerFile from "./swagger/swagger-output.json" assert { type: "json" };
import swaggerUi from "swagger-ui-express";

그 외에는 Swagger Autogen 공식 문서(https://swagger-autogen.github.io/docs/getting-started/quick-start)를 참고하면 된다.

 

3. API Base 경로 설정

[그림 1] Try it out > Excute로 API 호출 테스트

 

나의 경우 베이스 경로가 "/api/v1"에 API의 유형에 따라 "/ap" 또는 "/promo"를 각각 추가하는 형태로 되어 있었다. 여기에 개별 API의 경로가 추가되는 형태이다. 아래는 예시이다.

http://localhost:3000/api/v1/promo/promo-list

이런 경로를 감안하지 않고 Swagger UI에서 API 호출 테스트를 하기 위해 [그림 1]과 같이 "Try it out" 버튼을 눌러 API를 호출하면 아래와 같은 경로로 호출하여 에러가 발생한다.

http://localhost:3000/promo-list     // 잘못된 요청 에러

나의 경우 각 API별로 # swagger.path 속성을 추가해 주어 이러한 문제를 해결했다.

// route/v1_promo.js
import express from "express";
const router = express.Router();
import { queryPromo } from "../mysql/index.js";

router.get("/promo-list", async (req, res) => {
  /*
    #swagger.tags = ['홍보 관련']
    #swagger.summary = '홍보 리스트 조회'
    #swagger.description = 'Client에서 홍보리스트를 요청하고, Server는 홍보리스트를 응답한다.'
    #swagger.path = "/promo/promo-list"
    }
  */
  const result = await queryPromo("promotions");
  res.send(result);
});

export { router };

 

참고로 swagger.js에서의 베이스 경로 설정은 아래와 같다.

// swagger.js

import swaggerAutogen from "swagger-autogen";
import * as dotenv from "dotenv";
dotenv.config();

const doc = {
  info: {
    // (생략)
  },
  host: "localhost:3000",
  basePath: `/api/${process.env.ROUTE_VERSION}`,
  schemes: ['http'] // 기본값 http
};

// (생략)

 

schemes의 기본 값이 http이기 때문에 생략 가능하다. 하지만 https로 변경해야 한다면 schemes 속성을 반드시 추가해주어야 한다.

 

4. swagger-output.json 생성

프로젝트 실행전 아래 명령어로 swagger-out.json을 생성한다.

npm run swagger
728x90
반응형