<aside> <img src="/icons/list_gray.svg" alt="/icons/list_gray.svg" width="40px" /> 목차

</aside>

👉 Swagger 란?

API Documentation & Design Tools for Teams | Swagger

Swagger는 RESTful API를 설계, 빌드, 문서화 및 사용하는 데 도움이 되는 Open API 사양을 중심으로 구축된 오픈 소스 도구입니다.

프로젝트를 만들 때 혼자 다 만들 수 있는 것은 아니잖아요? 프론트엔드와 백엔드, 디자이너, PM 등 다른 많은 팀원들과 함께 하나의 프로젝트를 완성해 나갑니다.

특히 저희는 어떤 방식으로 통신해야 할 지, 어떠한 API를 만들었고 그것이 어떻게 동작하는 지를 알려줘야 하며, 프론트엔드가 어떻게 사용하면 될 지의 정보를 알려줘야 합니다. 이에 대해서 다양한 방법으로 명세를 진행하는데요. Swagger는 이러한 API 명세를 도와주는 도구입니다.

👉 Swagger 관련 라이브러리 설치

npm add \\
  swagger-autogen \\
  swagger-ui-express

2개의 라이브러리를 설치해 사용할 예정인데요, 용도는 아래와 같아요!

👉 Swagger 세팅

이제 src/index.js 파일을 수정해 Swagger UI가 렌더링 되도록 설정하도록 할게요.

import swaggerAutogen from "swagger-autogen";
import swaggerUiExpress from "swagger-ui-express";

// ...

app.use(
  "/docs",
  swaggerUiExpress.serve,
  swaggerUiExpress.setup({}, {
    swaggerOptions: {
      url: "/openapi.json",
    },
  })
);

app.get("/openapi.json", async (req, res, next) => {
  // #swagger.ignore = true
  const options = {
    openapi: "3.0.0",
    disableLogs: true,
    writeOutputFile: false,
  };
  const outputFile = "/dev/null"; // 파일 출력은 사용하지 않습니다.
  const routes = ["./src/index.js"];
  const doc = {
    info: {
      title: "UMC 7th",
      description: "UMC 7th Node.js 테스트 프로젝트입니다.",
    },
    host: "localhost:3000",
  };

  const result = await swaggerAutogen(options)(outputFile, routes, doc);
  res.json(result ? result.data : null);
});

// ...

/docs 경로에 들어가면 Swagger UI가 렌더링되고, 여기에서 /openapi.json 을 다시 동적으로 호출하여 API 서버의 라우트 및 파라미터 정보들을 불러오게 됩니다.

Swagger UI는 아래와 같이 보여야 합니다! 이제 저희의 Node.js 서버에 어떤 API들이 존재하는지 목록을 볼 수 있게 되었습니다 🙌

CleanShot 2024-09-14 at 00.20.58@2x.png