Swagger UI 사용

tpids·2024년 7월 23일
0

project

목록 보기
5/26

Swagger UI

  • Swagger UI는 API를 시각적으로 표현하고 테스트할 수 있게 해주는 도구입니다.
  • API 문서화에 매우 유용하며, API의 엔드포인트와 요청/응답 형식을 시각적으로 보여줍니다.

swagger-jsdoc과 swagger-ui-express는 Node.js 환경에서 Swagger UI를 사용하여 API 문서화를 쉽게 설정하고 관리할 수 있게 해주는 라이브러리입니다.

npm install swagger-jsdoc swagger-ui-express

2. 설정

2.1. Swagger JSDoc 설정

  • swagger-jsdoc는 JSDoc 주석을 기반으로 Swagger 스펙을 생성하는 도구입니다. 다음은 기본적인 설정 예제입니다:

Swagger 설정 파일 예시

  • 아래 코드는 swagger-jsdoc과 swagger-ui-express를 사용하여 Express 애플리케이션에 Swagger UI를 통합하는 방법.
const express = require('express');
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const path = require('path');

const app = express();

// Swagger 설정
const swaggerOption = {
    swaggerDefinition: {
        openapi: '3.0.0',
        info: {
            title: 'API Documentation',
            version: '1.0.0',
            description: 'API Documentation for the application'
        },
        servers: [
            {
                url: 'http://localhost:5001',
                description: 'Development server'
            }
        ]
    },
    apis: [path.join(__dirname, 'routes/*.js')] // API 경로 수정 부분
};

const swaggerDocs = swaggerJsdoc(swaggerOption);

// Swagger UI 미들웨어 설정
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

// API 엔드포인트 예시
app.get('/api/hello', (req, res) => {
    res.json({ message: 'Hello, World!' });
});

// 서버 시작
const port = 5001;
app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`);
});

profile
개발자

0개의 댓글