[Project] Swagger

Fortice·2021년 7월 28일
0

Project

목록 보기
6/8

Swagger

프로젝트를 시작하기 전에 우선 설계부터 하고 넘어가기로 했다. DB와 기능이 어느정도 나와 있으니, API문서를 Swagger를 이용해 작성해 보도록 한다.

OpenAPI 3.0

YAML 문법을 사용해 작성하는데, 한눈에 무엇을 나타내는지 알겠다.

openapi: 3.0.0
info:
  version: 1.0.0
  title: Sample API
  description: A sample API to illustrate OpenAPI concepts
paths:
  /list:
    get:
      description: Returns a list of stuff              
      responses:
        '200':
          description: Successful response

구성

아래와 같은 여러가지 정보를 설정할 수 있다.

  • Meta information
  • Path items (endpoints)
    • Parameters
    • Request bodies
    • Responses
  • Reusable components:
    • Schemas (data models)
    • Parameters
    • Responses
    • Other components

Meta Information

  • info로 버전, 제목, 문서 설명 등을 작성한다.
  • servers_url을 통해 서버의 기본 url을 설정한다.
  • security 설정으로 OAuth, 프로토콜 등에 대한 인증, 제약등을 걸 수 있다.
    • component_securitySchemes에 security scheme들을 설정해두고 특정 path에서 불러올 수 있다.
      • 모든 security는 여기에 정의되어 있어야 한다.
      • 4가지 type을 갖는다. (http, apiKey, oauth2, openIdConnect
    • security로 scheme들을 적용시킨다.
    • scope를 설정한다.
openapi: 3.0.0
info:
  version: 1.0.0
  title: Simple Artist API
  description: A simple API to illustrate OpenAPI concepts

servers:
  - url: https://example.io/v1

# Basic authentication
components:
  securitySchemes:
    BasicAuth:
      type: http
      scheme: basic
security:
  - BasicAuth: []

paths: {}

Path Items(Response)

기본

  • /path 형식으로 작성을 시작한다.
    • servers에 설정한 url + /path의 요청을 처리한다.
  • get, post와 같은 method를 설정한다.
  • response를 설정한다.
  • HTTP 상태코드를 설정한다.
    • 200, 404같이 명시적으로 지정할 수 있고, 2XX, 5XX 와 같이 범위로 지정할 수 있다.
    • 200 과 같은 명시적 코드가 우선된다.
    • 각 상태에서 어떤 조건에서 해당 상태가 되는지 description으로 명시해줘야한다.
    • default로 기본 처리를 할 수 있다.
  • content 하는 내용을 설정한다.
  • Media Type을 설정한다.
  • schema request/response body를 설정한다.
    • type schema의 타입을 설정한다.
      • array, object json과 xml을 위해 주로 사용된다.
      • primitive data type인 number, string도 사용 가능하다.
      • file image나 PDF같은 파일도 가능하다.
    • properties 넘겨줄 데이터의 이름, 타입을 설정한다.
      • {name}: type: 데이터 이름을 지정한 후 타입(string, integer, object, 파일 형식)을 설정한다.
paths:
  /artists:
    get:
      description: Returns a list of artists 
      responses:
        '200':
          description: Successfully returned a list of artists
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  required:
                    - username
                  properties:
                    artist_name:
                      type: string
                    albums_recorded:
                      type: integer
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                type: object
                properties:   
                  message:
                    type: string

파일

  • OpenAPI 3.0에서는 type: string + [format: binary|format: base64|format: byte]로 하여 설정 한다.
  • OpenAPI 2.0에서는 type: file로 하는 차이가 있다.
paths:
  /report:
    get:
      summary: Returns the report in the PDF format
      responses:
        '200':
          description: A PDF file
          content:
            application/pdf:
              schema:
                type: string
                format: binary

$ref

  • components에서 미리 설정한 schema를 불러와서 사용할 수 있다.
  • 같은 schema에서 multiple media types을 사용할 때 효율적이다.
paths:
  /artists:
    get:
      description: Returns a list of artists 
      responses:
        `201`: 
          description: A User object
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          description: The user ID.
        username:
          type: string
          description: The user name.

anyOf, oneOf

  • OpenAPI 3.0부터 대체 스키마를 지정할 수 있다.
      responses:
        '200':
          description: A JSON object containing pet information
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/Cat'
                  - $ref: '#/components/schemas/Dog'
                  - $ref: '#/components/schemas/Hamster'

Reusable Response

  • components를 사용해서 schema뿐만 아니라 response도 재사용 가능하다.
  • components 내부에서도 responses에 schemas로 지정해 놓은 Error schema를 재사용하는 것을 볼 수 있다.
# Descriptions of common components
components:
  responses:
    NotFound:
      description: The specified resource was not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Unauthorized:
      description: Unauthorized
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  schemas:
    # Schema for error response body
    Error:
      type: object
      properties:
        code:
          type: string
        message:
          type: string
      required:
        - code
        - message

Path Items(Parameter)

GET 요청의 경우 Query Parameter를 받을 수 있다.
이는 get: parameters:로 Query Parameter에 대한 설정을 할 수 있다.

  • name 파라미터의 이름을 설정한다.
  • in Query Parameter인지 Path Parameter인지 설정한다.
    • Query: in: query
    • Path: in: path
  • schema schema를 설정한다.
paths:
  /artists:
    get:
      description: Returns a list of artists
      parameters:
        - name: limit
          in: query
          description: Limits the number of items on a page
          schema:
            type: integer
        - name: offset
          in: query
          description: Specifies the page number of the artists to be displayed
          schema:
            type: integer

Path Items(Request)

PUT, POST, PATCH의 경우 Request Body에 데이터를 담아서 보낼 수 있다. 이제 Request에 대한 설정을 알아보도록 한다.

Request Body

  • requestBody 오브젝트를 생성한다.
  • response와 마찬가지로 content, media type, schema, schema type, properties들을 설정할 수 있다.
  • 차이점으로는 required로 Request Body가 필수인지 설정할 수 있고, body의 특정 속성을 필수로 지정할 수 있다.
paths:
  /artists:
    post:
      description: Lets a user post a new artist
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object 
              required:
                - username
              properties:
                artist_name:
                  type: string
                albums_recorded:
                  type: integer
                username:
                  type: string

Path Parameter

위에 Query Parameter와 다르게 Path로 데이터를 넘기는 Path Parameter를 처리하는 방법이다.

  • parametersin: path를 해주면 된다.
  • required: false로 하면 어떻게 될 지 모르겠다.
/artists/{username}:
    get:
      description: Obtain information about an artist from his or her unique username
      parameters:
        - name: username
          in: path
          required: true
          schema:
            type: string
profile
서버 공부합니다.

0개의 댓글