[Swagger] Components Section (OpenAPI 3.0)

Yuri Lee·2021년 9월 7일
0

Intro

최근 기존 프로젝트에서 추가된 요구사항을 위해 API와 Web 을 수정하는 작업을 하고 있다. 스웨거를 이용하여 API를 명세하는 것은 처음이여서 기존 코드를 이해하는 데 집중하고 있다. 🙂 그러던 중 Components Section 라는 개념을 발견하여 정리해보려고 한다.

Components Section

여러 API 작업은 공통 매개 변수를 가지거나 동일한 응답 구조를 반환하는 경우가 많다. 코드 중복을 방지하기 위해 글로벌 구성요소 섹션에 공통 정의를 배치하고 $ref를 사용하여 참조할 수 있다. 아래 예에서는 사용자 개체의 중복 정의가 단일 구성 요소 및 해당 구성 요소에 대한 참조로 대체된다.

Before:

paths:
  /users/{userId}:
    get:
      summary: Get a user by ID
      parameters:
        ...
      responses:
        '200':
          description: A single user.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: integer
                  name:
                    type: string
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: A list of users.
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    id:
                      type: integer
                    name:
                      type: string

After:

paths:
  /users/{userId}:
    get:
      summary: Get a user by ID
      parameters:
        ...
      responses:
        '200':
          description: A single user.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: A list of users.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string

Components Structure

구성 요소는 스키마(데이터 모델), 매개 변수, 응답, 예제 등 다양한 재사용 가능한 정의에 대한 컨테이너 역할을 한다. 구성요소의 정의는 구성요소의 외부로부터 명시적으로 참조하지 않는 한 API에 직접적인 영향을 미치지 않는다. 즉, 구성요소는 모든 작업에 적용되는 매개 변수와 응답이 아니며, 다른 곳에서 참조할 정보의 일부에 불과하다. 구성요소에서 정의는 스키마, 매개 변수 등의 유형별로 그룹화 된다. 다음은 사용 가능한 하위 섹션 목록이다. 모든 하위 섹션은 선택 사항이다.

components:
  # Reusable schemas (data models)
  schemas:
    ...
  # Reusable path, query, header and cookie parameters
  parameters:
    ...
  # Security scheme definitions (see Authentication)
  securitySchemes:
    ...
  # Reusable request bodies
  requestBodies:
    ...
  # Reusable responses, such as 401 Unauthorized or 400 Bad Request
  responses:
    ...
  # Reusable response headers
  headers:
    ...
  # Reusable examples
  examples:
    ...
  # Reusable links
  links:
    ...
  # Reusable callbacks
  callbacks:
    ...

TIL

코드 중복 제거는 언제나 중요하구나! 👍


https://swagger.io/docs/specification/components/

profile
Step by step goes a long way ✨

0개의 댓글