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

Node.js (typescript) - Swagger UI 연동

개발참치 2021. 7. 28.
Node.js (typescript) 에 Swagger UI를 연동하는 법을 작성해보려 합니다.

 

1. 필요 패키지

필요한 패키지는 swagger 관련 패키지들이 있습니다.

 

Swagger 형식에는 yaml과 json으로 설정하는 방식이 있는데, Swagger에서는 yaml 방식을 정석으로 채택하고 있습니다. 

 

YAML 방식 필요 패키지

 

npm install swagger-cli swagger-ui-express yamljs
npm install -D @types/swagger-ui-express @types/yamljs

 

JSON 방식 필요 패키지

 

npm install swagger-cli swagger-ui-express
npm install -D @types/swagger-ui-express

 

위 둘중 편하신 걸로 설치 연동하시면 되겠습니다.

 

2. swagger 설정

설정 파일을 만들어 줍니다.

 

예시가 나와있는 Swagger Editor를 참조하시면 편하게 설정 파일을 생성하실 수 있습니다.

 

YAML의 경우 (아래는 예시일 뿐입니다.)

swagger: "2.0"
info:
  description: "This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters."
  version: "1.0.0"
  title: "Swagger Petstore"
  termsOfService: "http://swagger.io/terms/"
  contact:
    email: "apiteam@swagger.io"
  license:
    name: "Apache 2.0"
    url: "http://www.apache.org/licenses/LICENSE-2.0.html"
host: "petstore.swagger.io"
basePath: "/v2"
tags:
- name: "pet"
  description: "Everything about your Pets"
  externalDocs:
    description: "Find out more"
    url: "http://swagger.io"
- name: "store"
  description: "Access to Petstore orders"
- name: "user"
  description: "Operations about user"
  externalDocs:
    description: "Find out more about our store"
    url: "http://swagger.io"
schemes:
- "https"
- "http"
paths:
  /pet:
    post:
      tags:
      - "pet"
      summary: "Add a new pet to the store"
      description: ""
      operationId: "addPet"
      consumes:
      - "application/json"
      - "application/xml"
      produces:
      - "application/xml"
      - "application/json"
      parameters:
      - in: "body"
        name: "body"
        description: "Pet object that needs to be added to the store"
        required: true
        schema:
          $ref: "#/definitions/Pet"
      responses:
        "405":
          description: "Invalid input"
      security:
      - petstore_auth:
        - "write:pets"
        - "read:pets"

 

JSON의 경우 (아래는 예시일 뿐입니다.)

{
  "swagger": "2.0",
  "info": {
    "description": "This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters.",
    "version": "1.0.0",
    "title": "Swagger Petstore",
    "termsOfService": "http://swagger.io/terms/",
    "contact": {
      "email": "apiteam@swagger.io"
    },
    "license": {
      "name": "Apache 2.0",
      "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
    }
  },
  "host": "petstore.swagger.io",
  "basePath": "/v2",
  "tags": [
    {
      "name": "pet",
      "description": "Everything about your Pets",
      "externalDocs": {
        "description": "Find out more",
        "url": "http://swagger.io"
      }
    },
    {
      "name": "store",
      "description": "Access to Petstore orders"
    },
    {
      "name": "user",
      "description": "Operations about user",
      "externalDocs": {
        "description": "Find out more about our store",
        "url": "http://swagger.io"
      }
    }
  ],
  "schemes": [
    "https",
    "http"
  ],
  "paths": {
    "/pet": {
      "post": {
        "tags": [
          "pet"
        ],
        "summary": "Add a new pet to the store",
        "description": "",
        "operationId": "addPet",
        "consumes": [
          "application/json",
          "application/xml"
        ],
        "produces": [
          "application/xml",
          "application/json"
        ],
        "parameters": [
          {
            "in": "body",
            "name": "body",
            "description": "Pet object that needs to be added to the store",
            "required": true,
            "schema": {
              "$ref": "#/definitions/Pet"
            }
          }
        ],
        "responses": {
          "405": {
            "description": "Invalid input"
          }
        },
        "security": [
          {
            "petstore_auth": [
              "write:pets",
              "read:pets"
            ]
          }
        ]
      },
     }
    }
   }
  }
 }

 

3. swagger 적용

위 생성된 파일을 실행 루트 파일 (app.ts)에 적용해줍니다.

 

YAML의 경우

// 공통 사항
import swaggerUi from 'swagger-ui-express'

// yaml을 연동하기 위함
import YAML from 'yamljs'

...
// yaml 파일 연동
const swaggerYaml = YAML.load(path.join(__dirname, '../build/swagger.yaml'))

...
// yaml로 된 swagger 연동
app.use('/api-yaml', swaggerUi.serve, swaggerUi.setup(swaggerYaml))

JSON의 경우

// 공통 사항
import swaggerUi from 'swagger-ui-express'

// json 파일을 바로 불러오기
import swaggerJson from './swaggerJson'


...

// json으로 된 swagger 연동
app.use('/api-json', swaggerUi.serve, swaggerUi.setup(swaggerJson))

 

3. 설정 테스트

이후 실행 루트 파일에 있는 링크로 접속하여 Swagger가 잘 적용되었는지 테스트해줍니다.

 

swagger 연동 캡쳐

 

댓글