다양한 활동/인턴

[인턴/ko웹페이지] Node.js 환경에서 Swagger로 API 문서 자동화 설정

토끼개발자 조르디 2024. 10. 11. 18:30

API 명세서 관리 프레임워크

API 개발을 진행하기 전 코드에 항상 해두는 것이 있다. 바로 API 관리 설정 코드 추가!

난 항상 swagger 를 코드에 설정해두고 토큰이 필요한 API 테스트는 postman 을 사용해 진행했다. 

 

그런데 문득 다른 관리 도구는 없는건가? 라는 생각이 들어서 조사해보았다.

이런거 관심없고 빨리 swagger 설정이나 했으면 ,,, 이라는 생각을 한다면 아래로 스크롤 쫙 내려주세여🌸

 

문서화 관리 도구 / API 테스트 도구 종류

 

1. Swagger (OpenAPI):

: Swagger는 OpenAPI Specification(OAS)을 기반으로 하, API 문서를 자동으로 생성하고, 인터 UI를 제공

장점: 자동 문서화, 테스트 기능, 다양한 언어와 플랫폼에서의 호환성

 

-> 이거 진짜로 강력한 기능이다,,, 왜냐하면 개발하다가 오류 고치고 API 문서 고치고 다시 개발하다가,,,, 이러다보면 문서 업데이트 까먹기고 또 솔직히 따로 문서 작성하고 그러는거 진짜로 귀찮음,,, ㅎ-ㅎ

 

https://swagger.io/

 

API Documentation & Design Tools for Teams | Swagger

Swagger and OpenAPI go hand‑in‑hand. Swagger offers powerful and easy to use tools to take full advantage of the OpenAPI Specification. See how we do it

swagger.io

 

 

2. Postman:

 

설명: Postman API 개발 및 테스트 구 - API 문서화 기능도 제공

 

: 사용자 친적인 UI, API 테스트 및 모니터 기능, 팀 협업 기능

 

https://www.postman.com/

 

Postman API Platform | Sign Up for Free

Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster.

www.postman.com

 

 

3. RAML (RESTful API Modeling Language):

설명: RAML RESTful API를 정의하기 위한 언어, YAML 형식으로 API를 문서

장점: 간결한 문법, API 디자인 및 문서화에 적

 

https://raml.org/

 

Welcome

Model your endpoints with access information, HTTP verbs, parameters, example responses and more

raml.org

 

4. API Blueprint:

설명: API Blueprint는 Markdown 형으로 API를 문서화하는 도

장점: 간단한 문, 다양한 도구와의 통 가능

 

https://apiblueprint.org/

 

API Blueprint | API Blueprint

API Blueprint. A powerful high-level API description language for web APIs. API Blueprint is simple and accessible to everybody involved in the API lifecycle. Its syntax is concise yet expressive. With API Blueprint you can quickly design and prototype API

apiblueprint.org

 

 

5. GraphQL:

설명: GraphQL API 쿼리 언어로, API 문서화 도도 함께 제공

장점: 클라이언트가 필요한 데이터 요청할 수 있는 유연

 

https://graphql.org/

 

GraphQL | A query language for your API

Evolve your API without versions Add new fields and types to your GraphQL API without impacting existing queries. Aging fields can be deprecated and hidden from tools. By using a single evolving version, GraphQL APIs give apps continuous access to new feat

graphql.org

 

 

그렇다면 아래에서 본격적으로 swagger 설정을 해보도록 하자!!

GOGOGO !!

 

GABOJAGO

 


Nodejs 에 swagger 설정하기

1. 키지 설치(모듈 설치):

npm install swagger-jsdoc swagger-ui-express

 

 

2. Swagger 설정:

아래의 코드를 sever.js 파일에 알맞게 추가한다. 

   const express = require('express');
   const swaggerJsDoc = require('swagger-jsdoc');
   const swaggerUi = require('swagger-ui-express');

   const app = express();

   // Swagger 설정
   const swaggerOptions = {
     swaggerDefinition: {
       openapi: '3.0.0',
       info: {
         title: 'My KOWEB API',
         version: '1.0.0',
         description: 'API documentation',
       },
       servers: [
         {
           url: 'http://localhost:3000',
         },
       ],
     },
     apis: ['./routes/*.js'], // API 문서화할 파일 경로
   };

   const swaggerDocs = swaggerJsDoc(swaggerOptions);
   app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

   const PORT = process.env.PORT || 3000;
   app.listen(PORT, () => {
     console.log(`서버가 포트 ${PORT}에서 실행 중입니다.`);
   });

 

 

 

 

3. 서버 실행 후 확인:

아래의 코드로 서버 파일 실행

node backend/server.js

 

http://localhost:3000/api-docs/    에 접속합니다.

아래의 화면이 나왔다면 우선 코드에 잘 반영이 되었다는 것!

 

API 페이지 접속 화면

 

 

4. routes 코드에  Swagger 주석 추가:

API 코드가 있는 파일 맨 위에 컴포넌트 명시 코드를 작성합니다. 

아래는 제가 작성한 예시.

/**
 * @swagger
 * components:
 *   schemas:
 *     Report:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: The unique identifier for the report
 *         title:
 *           type: string
 *           description: The title of the report
 *         content:
 *           type: string
 *           description: The content of the report
 *         imageUrl:
 *           type: string
 *           description: The URL of the report's image
 *         status:
 *           type: string
 *           enum: [pending, answered]
 *           description: The status of the report
 *         password:
 *           type: string
 *           description: The password for the report
 *         views:
 *           type: integer
 *           description: The number of views for the report
 *         createdAt:
 *           type: string
 *           format: date-time
 *           description: The date and time when the report was created
 *         updatedAt:
 *           type: string
 *           format: date-time
 *           description: The date and time when the report was last updated
 */

 

 

5. routes 코드에  Swagger 주석 추가:

모델 구조를 반영하도록 API 코드 마다 주석 코드를 각각 작성합니다. 

- API 엔드포인트

- 응답 및 요청 형식 정의

아래는 내가 작성한 예시.

/**
 * @swagger
 * /api/reports:
 *   get:
 *     summary: 신고글 목록 조회
 *     description: 모든 신고글을 조회합니다.
 *     responses:
 *       200:
 *         description: 성공적으로 신고글 목록을 반환합니다.
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/Report'  # Report 모델 참조
 *       500:
 *         description: 서버 오류
 */

 

 

6. 서버재실행 후 API 문서화 결과 확인:

아래 코드로 서버를 재실행합니다.

node backend/server.js

 

그리고 저 페이지에 다시 접속하면, 아래와 같은 화면을 볼 수 있음.

 

반갑구만~

 

아이고 예뻐라 ~

 

 

만약에, 계속 API가 안뜬다??? 냉큼 2번으로 되돌아가서 경로설정을 확인하라.

 

apis: ['./routes/*.js'], // API 문서화할 파일 경로

 

위의 부분을 아주 조심해야 한다. 

경로 설정을 바꿔가면서 서버 재실행을 해봐라,,, 해결될지도,,, 내가그랬기때문

 

그렇게 Swagger 연결 및 API 리스트 확인 성공~

 

성공했뚜