본문 바로가기

FrontEnd

OpenAPI 3.0 튜토리얼

반응형

아래 문서를 번역 및 요약한 글 

https://support.smartbear.com/swaggerhub/docs/tutorials/openapi-3-tutorial.html

 

OpenAPI 3.0 Tutorial | SwaggerHub Documentation

OpenAPI 3.0 is an open-source format for describing and documenting APIs. In this tutorial, we will write a simple API definition in the OpenAPI 3.0 format. If you are using OpenAPI 2.0 (Swagger 2.0), see this tutorial instead. OpenAPI Specification (forme

support.smartbear.com

OpenAPI란?

OpenAPI specification(이전의 Swagger specification)은 API를 설명하고 문서화하기 위한 오픈 소스 포맷입니다.
RESTful API를 설계하고 설명하기 위한 사실상의 표준입니다.
 
OpenAPI의 최신 버전은 3.0이며,
OpenAPI 정의는 JSON 또는 YAML로 작성할 수 있습니다.
읽고 쓰기 더 쉽기 때문에 YAML을 권장합니다.
 
간단한 OpenAPI 3.0 사양은 아래처럼 생겼습니다.
지금은 이해가 안될테지만, 이 글을 다 읽고나면 쉽게 이해하실 수 있을 것입니다.
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

yaml을 모르겠으면 해당 글 참조

API를 만들며 OpenAPI 3.0 배우기

음반사(레이블)를 위한 API를 설계할 것입니다.
레이블에 다음 정보가 포함된 아티스트 데이터베이스가 있다고 가정해 보겠습니다.
  • 아티스트 명
  • 아티스트 장르
  • 아티스트 닉네임
  • 해당 아티스트가 레이블에서 발매한 앨범 수
API를 통해 컨슈머는 데이터베이스에 저장된 아티스트 목록을 조회할 수 있고, 새 아티스트를 데이터베이스에 추가할 수 있습니다.
OpenAPI 사양을 사용하여 정의한 API는 3가지 주요 섹션으로 구성됩니다.
  • 메타정보(Meta information)
  • 경로 항목;Path items (endpoints):
    • 파라미터들
    • 요청 본문들
    • 응답들
  • 재사용 가능한 컴포넌트 :
    • 스키마(데이터 모델)
    • 파라미터들
    • 응답들
    • 다른 컴포넌트

메타정보(Meta information)

API 제목, 버전, 서버 URL 및 기타 설명적인 정보와 같은 메타 정보만 포함하는 간단한 API 정의부터 시작하겠습니다.
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: {}
  • 각 API 정의는 이 정의가 사용하는 OpenAPI 사양 버전으로 시작합니다.
    • 이 예에서는 openapi: 3.0.0입니다.
  • info 객체
    • required인 version, title
    • optional인 discription이 있습니다.
  • servers 배열
    • 하나 이상의 서버 URL
    • 엔드포인트 path가 해당 url 뒤에 추가됨
    • 샌드박스, 프로덕션과 같이 환경에 따라 다양한 url
  • security
    • Authentication 문서 참조
    • 인증된 사용자만 API를 사용할 수 있음을 나타냄

경로 항목(Path items)

경로 항목은 원하는 방식으로 리소스를 조작하기 위해 HTTP 동사를 지정할 수 있는 API의 엔드포인트입니다.

아래는 /artist 엔드포인트에 get 메서드를 지정한 모습입니다.

description은 항상 선택적입니다.

openapi: 3.0.0
info:
  version: 1.0.0
  title: Simple API
  description: A simple API to illustrate OpenAPI concepts

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

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

#  ----- Added lines  ----------------------------------------
paths:
  /artists:
    get:
     description: Returns a list of artists 
#  ----- Added lines  ----------------------------------------

응답(Response)

모든 응답에는 소비자가 예상할 수 있는 응답 유형을 설명하기 위해 적어도 하나의 HTTP 상태 코드가 필요합니다.
여기(here)에서 HTTP 상태 코드에 대한 자세한 정보를 찾을 수 있습니다.
description은 API 응답에 대한 세부 정보를 제공합니다.
성공적인 응답은 아티스트 이름, 장르, 아티스트 닉네임 및 앨범 갯수를 반환합니다.
실패한 요청은 400 HTTP 코드 아래에 설명되어 있으며 응답이 잘못된 이유를 자세히 설명하는 해당 오류 메시지가 있습니다.
더 자세한 정보는 Describing Responses를 확인하세요.
openapi: 3.0.0
info:
  version: 1.0.0
  title: Simple API
  description: A simple API to illustrate OpenAPI concepts

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

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

paths:
  /artists:
    get:
      description: Returns a list of artists 
      #  ----- Added lines  ----------------------------------------
      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
                    artist_genre:
                      type: string
                    albums_recorded:
                      type: integer
                    username:
                      type: string

        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                type: object
                properties:   
                  message:
                    type: string
      #  ---- /Added lines  ----------------------------------------​

파라미터(Parameters)

RESTful한 파라미터는 사용자가 작업하는 리소스의 변수 부분을 지정합니다.
더 자세한 정보는 Describing Parameters를 확인하세요
 

쿼리 파라미터(Query Parameters)

Query parameters는 가장 흔한 타입의 파라미터입니다.

물음표 뒤의 URL 끝에 나타납니다.
쿼리 매개변수는 선택 사항이며 유니크하지 않으므로 URL에서 여러 번 지정할 수 있습니다.
URL의 비계층적 컴포넌트입니다.
  • in : query 주의
GET https://example.io/v1/artists?limit=20&offset=3
이러한 변수는 OpenAPI 정의의 parameters 객체 아래에 정의됩니다. 
openapi: 3.0.0
info:
  version: 1.0.0
  title: Simple API
  description: A simple API to illustrate OpenAPI concepts

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

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

paths:
  /artists:
    get:
      description: Returns a list of artists 
      #  ----- Added lines  ----------------------------------------
      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
      #  ---- /Added lines  ----------------------------------------         
      
      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
                    artist_genre:
                      type: string
                    albums_recorded:
                      type: integer
                    username:
                      type: string

        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                type: object
                properties:   
                  message:
                    type: string

요청 본문(Request body)

POST, PUT 및 PATCH 요청에는 일반적으로 요청 본문이 포함됩니다.
요청 본문은 requestBody 객체를 통해 정의됩니다.
 
openapi: 3.0.0
info:
  version: 1.0.0
  title: Simple API
  description: A simple API to illustrate OpenAPI concepts

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

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

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
      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
                    artist_genre:
                      type: string
                    albums_recorded:
                      type: integer
                    username:
                      type: string
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                type: object
                properties:   
                  message:
                    type: string

    #  ----- Added lines  ----------------------------------------
    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
                artist_genre:
                  type: string
                albums_recorded:
                  type: integer
                username:
                  type: string

      responses:
        '200':
          description: Successfully created a new artist

        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                type: object
                properties:   
                  message:
                    type: string
    #  ---- /Added lines  ----------------------------------------​

경로 파라미터(Path parameters)

경로  파라미터는 클라이언트가 작업 중인 데이터의 특정 부분을 분리하는 데 사용할 수 있습니다
경로 매개변수는 URL의 계층적 구성요소의 일부이므로 순차적으로 쌓입니다.
주의할 점은 경로 매개변수는 required : true 설정이 필요하다는 점입니다.
  •  in : path
  • required : true
이전 코드 맨 아래에 추가
  #  ----- Added lines  ----------------------------------------
  /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
          
      responses:
        '200':
          description: Successfully returned an artist
          content:
            application/json:
              schema:
                type: object
                properties:
                  artist_name:
                    type: string
                  artist_genre:
                    type: string
                  albums_recorded:
                    type: integer
                
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                type: object 
                properties:           
                  message:
                    type: string
  #  ---- /Added lines  ----------------------------------------

재사용 가능한 컴포넌트(Reusable components)

지금까지 만든 것은 2개의 엔드포인트와 3개의 액션입니다.
이것은 약 130줄의 사양이었고 사양은 API가 커질수록 길어질 것입니다.
지금까지 우리가 가지고 있는 사양에서 알 수 있는 것 중 하나는 다양한 200 및 400 응답에서 반복되는 동일한 아티스트 스키마(아티스트 이름, 장르, 사용자 이름 및 게시된 앨범)가 있다는 것입니다.
더 큰 API는 많은 동일한 사양을 재작성하고 재사용해야 하므로 더 복잡한 API를 작성하는 것은 지루한 작업이 될 것입니다.
 
OpenAPI 사양에는 동일한 API의 여러 끝점에서 사용할 수 있는 재사용 가능한 컴포넌트가 있습니다.
이러한 컴포넌트는 전역 컴포넌트 섹션에서 정의된 다음 개별 끝점에서 참조됩니다.
사양은 다양한 타입의 재사용 가능한 컴포넌트를 정의합니다.
  • Schemas (data models)
  • Parameters
  • Request bodies
  • Responses
  • Response headers
  • Examples
  • Links
  • Callbacks

이 중에서 Schema와 Parameters, Request bodies를 통해 컴포넌트를 사용하는 방법을 알아봅니다.
기타 항목에 관한 자세한 설명은 여기(here)을 참조하세요

스키마(데이터 모델)

전역 컴포넌트 섹션의 스키마의 하위 섹션에는 API에서 사용하고 반환하는 다양한 데이터 모델이 포함될 수 있습니다.
다음은 컴포넌트를 사용하여 HTTP 200 OK 응답에 대한 스키마를 지정하는 방법입니다.
우리의 API 정의에는 이미 securitySchemes를 포함하는 구성 요소 섹션이 있습니다.
이제 컴포넌트 객체를 맨 아래로 이동하고 스키마 하위 섹션을 추가했습니다.
Added line 주석을 참조하세요!
openapi: 3.0.0
info:
  version: 1.0.0
  title: Simple API
  description: A simple API to illustrate OpenAPI concepts

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

security:
  - BasicAuth: []

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
      responses:
        '200':
          description: Successfully returned a list of artists
          content:
            application/json:
              schema:
                type: array
                items:
                  #  ----- Added line  ----------------------------------------
                  $ref: '#/components/schemas/Artist'
                  #  ---- /Added line  ----------------------------------------
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                type: object
                properties:   
                  message:
                    type: string

    post:
      description: Lets a user post a new artist
      requestBody:
        required: true
        content:
          application/json:
            schema:
              #  ----- Added line  ----------------------------------------
              $ref: '#/components/schemas/Artist'
              #  ---- /Added line  ----------------------------------------
      responses:
        '200':
          description: Successfully created a new artist
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                type: object
                properties:   
                  message:
                    type: string

  /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
          
      responses:
        '200':
          description: Successfully returned an artist
          content:
            application/json:
              schema:
                type: object
                properties:
                  artist_name:
                    type: string
                  artist_genre:
                    type: string
                  albums_recorded:
                    type: integer
                
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                type: object 
                properties:           
                  message:
                    type: string

components:
  securitySchemes:
    BasicAuth:
      type: http
      scheme: basic

  #  ----- Added lines  ----------------------------------------                
  schemas:
    Artist:
      type: object
      required:
        - username
      properties:
        artist_name:
          type: string
        artist_genre:
            type: string
        albums_recorded:
            type: integer
        username:
            type: string
  #  ---- /Added lines  --------------​

파라미터와 응답

파라미터와 응답 자체를 컴포넌트로 만들어 통째로 치환할 수 있습니다.

이는 여러 엔드포인트에서 동일한 파라미터와 응답을 사용할 수 있게 해줍니다.

바로 위의 문서와 비교해 보세요

openapi: 3.0.0
info:
  version: 1.0.0
  title: Simple API
  description: A simple API to illustrate OpenAPI concepts

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

security:
  - BasicAuth: []

paths:
  /artists:
    get:
      description: Returns a list of artists 
      parameters:
        #  ----- Added line  ------------------------------------------
        - $ref: '#/components/parameters/PageLimit'
        - $ref: '#/components/parameters/PageOffset'
        #  ---- /Added line  ------------------------------------------
      responses:
        '200':
          description: Successfully returned a list of artists
          content:
            application/json:
              schema:
                type: array
                items:
                  #  ----- Added line  --------------------------------
                  $ref: '#/components/schemas/Artist'
                  #  ---- /Added line  --------------------------------
        '400':
          #  ----- Added line  ----------------------------------------
          $ref: '#/components/responses/400Error'
          #  ---- /Added line  ----------------------------------------

    post:
      description: Lets a user post a new artist
      requestBody:
        required: true
        content:
          application/json:
            schema:
              #  ----- Added line  ------------------------------------
              $ref: '#/components/schemas/Artist'
              #  ---- /Added line  ------------------------------------
      responses:
        '200':
          description: Successfully created a new artist
        '400':
          #  ----- Added line  ----------------------------------------
          $ref: '#/components/responses/400Error'
          #  ---- /Added line  ----------------------------------------    

  /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
          
      responses:
        '200':
          description: Successfully returned an artist
          content:
            application/json:
              schema:
                type: object
                properties:
                  artist_name:
                    type: string
                  artist_genre:
                    type: string
                  albums_recorded:
                    type: integer
                
        '400':
          #  ----- Added line  ----------------------------------------
          $ref: '#/components/responses/400Error'
          #  ---- /Added line  ----------------------------------------     

components:
  securitySchemes:
    BasicAuth:
      type: http
      scheme: basic

  schemas:
    Artist:
      type: object
      required:
        - username
      properties:
        artist_name:
          type: string
        artist_genre:
            type: string
        albums_recorded:
            type: integer
        username:
            type: string

  #  ----- Added lines  ----------------------------------------
  parameters:
    PageLimit:
      name: limit
      in: query
      description: Limits the number of items on a page
      schema:
        type: integer
      
    PageOffset:
      name: offset
      in: query
      description: Specifies the page number of the artists to be displayed
      schema:
        type: integer

  responses:
    400Error:
      description: Invalid request
      content:
        application/json:
          schema:
            type: object 
            properties:
              message:
                type: string
  #  ---- /Added lines  ----------------------------------------

See also

full OpenAPI 3.0 specification

 

OpenAPI Specification - Version 3.0.3 | Swagger

OpenAPI Specification Version 3.0.3 The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 RFC2119 RF

swagger.io

how-to guide

요건 꼭 읽어보자

 

Basic Structure

OAS 3 This page is about OpenAPI 3.0. If you use OpenAPI 2.0, visit OpenAPI 2.0 pages. Basic Structure You can write OpenAPI definitions in YAML or JSON. In this guide, we use only YAML examples but JSON works equally well. A sample OpenAPI 3.0 definitio

swagger.io

Getting Started

 

Getting Started | SwaggerHub Documentation

 

support.smartbear.com

OpenAPI 3.0 Support

 

OpenAPI 3.0 Support | SwaggerHub Documentation

SwaggerHub supports OpenAPI 3.0 (OAS3), a major revision of OpenAPI 2.0 (formerly known as Swagger). OpenAPI 3.0 introduced many new features, including multiple servers, callbacks, links, better content negotiation, new authentication types, and more. Swa

support.smartbear.com

 

반응형