[NodeJs] - Swagger 기본 사용법, API 문서 자동화
작성자 정보
- MindSync 작성
- 작성일
본문
Swagger는 API 개발 및 관리를 위한 강력한 도구로, API 문서의 자동화 및 시각화를 제공합니다.
RESTful API의 명세를 기술하고, 해당 명세를 토대로 자동으로 API 문서를 생성하며, 테스트 및 디버깅을 용이하게 합니다.
Swagger를 사용하면 간단한 명세 작성을 통해 API의 엔드포인트, 매개변수, 응답 형식 등을 정의할 수 있습니다.
명세는 OpenAPI 스펙에 기반하여 작성되며, 현재 버전 3.0.0 이상을 지원합니다.
Swagger은 자동으로 API 문서를 사용합니다. API 엔드포인트, 매개변수, 응답 형식 등을 빠르게 확인할 수 있어 개발자가 쉽게 이해하고 사용할 수 있습니다!
또, 간단한 UI를 통해 API를 테스트할 수 있는 환경을 제공해서 요청을 직접 생성하고 실행하여 응답을 확인할 수 있습니다.
Spring, Python, NodeJs 등 다양한 언어를 지원하기 때문에 개발할 때 편리하여 여러분들이 사용해보기 좋을 것 같아 추천드립니다~!
node.js로 swagger을 사용하는 예시를 잠깐 설명드리자면,,
1. 프로젝트 시작
npm init -y
npm install express swagger-jsdoc swagger-ui-express body-parser
2. Express 애플리케이션 설정
- app.js
const express = require('express');
const bodyParser = require('body-parser');
const swaggerJSDoc = require('swagger-jsdoc');
const swaggerUI = require('swagger-ui-express');
const app = express();
const port = 3000;
app.use(bodyParser.json());
// Swagger 설정
const swaggerOptions = {
definition: {
openapi: '3.0.0',
info: {
title: 'API 문서',
version: '1.0.0',
},
},
apis: ['./routes/*.js'], // API 정의 파일들의 경로
};
const swaggerSpec = swaggerJSDoc(swaggerOptions);
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerSpec));
// API 정의
/**
* @swagger
* /api/greet:
* get:
* summary: 인사말 가져오기
* responses:
* 200:
* description: 성공적으로 가져옴
* content:
* application/json:
* example:
* message: '안녕하세요!'
*/
app.get('/api/greet', (req, res) => {
res.json({ message: '안녕하세요!' });
});
/**
* @swagger
* /api/user:
* post:
* summary: 사용자 생성
* requestBody:
* content:
* application/json:
* example:
* username: 'john_doe'
* email: 'john@example.com'
* responses:
* 201:
* description: 사용자 생성 성공
* content:
* application/json:
* example:
* id: 1
* username: 'john_doe'
* email: 'john@example.com'
*/
app.post('/api/user', (req, res) => {
const { username, email } = req.body;
// 사용자 생성 로직
const newUser = { id: 1, username, email };
res.status(201).json(newUser);
});
app.listen(port, () => {
console.log(`서버가 http://localhost:${port} 에서 실행 중입니다.`);
});
3. Swagger 설정 파일 작성
- 프로젝트 루트에 swagger.json 파일을 작성합니다.
{
"openapi": "3.0.0",
"info": {
"title": "API 문서",
"version": "1.0.0"
},
"paths": {
"/api/greet": {
"get": {
"summary": "인사말 가져오기",
"responses": {
"200": {
"description": "성공적으로 가져옴",
"content": {
"application/json": {
"example": {
"message": "안녕하세요!"
}
}
}
}
}
}
},
"/api/user": {
"post": {
"summary": "사용자 생성",
"requestBody": {
"content": {
"application/json": {
"example": {
"username": "john_doe",
"email": "john@example.com"
}
}
}
},
"responses": {
"201": {
"description": "사용자 생성 성공",
"content": {
"application/json": {
"example": {
"id": 1,
"username": "john_doe",
"email": "john@example.com"
}
}
}
}
}
}
}
}
}
4. API 문서 확인
프로젝트를 실행하고 브라우저에서 http://localhost:3000/api-docs로 접속해보세요~! Swagger UI에서 API 문서를 확인할 수 있습니다.
Swagger은 개발자간 협업 효율도 높일 수 있어서, 토이 프로젝트나 미니 프로젝트에 테스트해보시고
편하시다면 사용하시는 걸 추천드립니다~
관련자료
-
링크