Describing Responses

정민교·2023년 7월 11일
0

📒Describing Responses

API 명세서는 모든 API operations에 대한 responses를 명시해야 한다.

각 operation마다 하나의 response는 반드시 정의되어야 한다. 일반적으로 성공 응답은 반드시 포함되어야 한다.

response는 HTTP 상태 코드에 의해 정의며, 응답 데이터는 response body와 header에 포함된다.

paths:
  /ping:
    get:
      responses:
        '200':
          description: OK
          content:
            text/plain:
              schema:
                type: string
                example: pong

✔️Response Media Types

API 응답은 여러 media type으로 응답 가능하다.

JSON이 형식이 보통 사용되지만 다른 media type도 사용 가능하다.

response media type을 정의하기 위해 content 키워드를 operation level 에서 정의한다.

paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: A list of users
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ArrayOfUsers'
            application/xml:
              schema:
                $ref: '#/components/schemas/ArrayOfUsers'
            text/plain:
              schema:
                type: string
  # This operation returns image
  /logo:
    get:
      summary: Get the logo image
      responses:
        '200':
          description: Logo image in PNG format
          content:
            image/png:
              schema:
                type: string
                format: binary

✔️HTTP Status Codes

reponse 아래 각 응답의 정의를 status code로 시작한다.

Operation은 보통 하나의 성공 응답 코드와 여러 에러 응답 코드를 반환한다.

각 응답 상태는 description을 포함해야 한다. description은 마크다운 표기법 사용이 가능하다.

      responses:
        '200':
          description: OK
        '400':
          description: Bad request. User ID must be an integer and larger than 0.
        '401':
          description: Authorization information is missing or invalid.
        '404':
          description: A user with the specified ID was not found.
        '5XX':
          description: Unexpected error.

✔️Response Body

schema 키워드는 response body를 정의하는 사용된다. schema는 다음과 같이 정의할 수 있다.

  • object or array
  • primitive data type
  • a file
      responses:
        '200':
          description: A User object
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: integer
                    description: The user ID.
                  username:
                    type: string
                    description: The user name.

아니면 global components.schemas 섹션에 정의하고 $ref로 참조하도록 할 수도 있다.

같은 스키마로 여러 media type 형태를 사용해서 응답을 내릴 경우 유용하다.

      responses:
        '200':
          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.

✔️Response That Returns a File

API operation은 이미지나 pdf같은 파일을 응답으로 반환할 수 있다.

OpenAPI 3.0부터는 file input/output 컨텐츠를 type: string, format: binary or base64로 정의할 수 있다.

만약 응답하려는 파일이 하나인 경우 binary string schema를 사용하고 response content에 적합한 media type을 명시한다.

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

file은 JSON이나 XML에 base64-encoded 문자열로 포함될 수 있다. 이런 경우에는 다음과 같이 할 수 있다.

paths:
  /users/me:
    get:
      summary: Returns user information
      responses:
        '200':
          description: A JSON object containing user name and avatar
          content:
            application/json:
              schema:
                type: object
                properties:
                  username:
                    type: string
                  avatar:          # <-- image embedded into JSON
                    type: string
                    format: byte
                    description: Base64-encoded contents of the avatar image

✔️anyOf, oneOf

OpenAPI 3.0은 oneofanyOf를 지원한다.

      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'

✔️Empty Response Body

204 No Content 같은 몇몇 응답은 바디가 없다.

      responses:
        '204':
          description: The resource was deleted successfully.

✔️Response Headers

API 응답 결과에 대한 추가적인 정보를 위해 custom header가 포함될 수 있다.

예를 들면 rate-limited API는 다음과 같은 rate limit status를 response header에 포함시킬 것이다.

HTTP 1/1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 99
X-RateLimit-Reset: 2016-10-12T11:00:00Z
{ ... }

cuson header는 다음과 같이 작성할 수 있다.

paths:
  /ping:
    get:
      summary: Checks if the server is alive.
      responses:
        '200':
          description: OK
          headers:
            X-RateLimit-Limit:
              schema:
                type: integer
              description: Request limit per hour.
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: The number of requests left for the time window.
            X-RateLimit-Reset:
              schema:
                type: string
                format: date-time
              description: The UTC date/time at which the current rate limit window resets.

OpenAPI 명세는 서로 다른 응답에 대해 공통 response header를 정의할 수 없다. 각 API operation마다 개별적으로 header를 작성해야 한다.

✔️Default Response

operation은 서로 다른 HTTP status code로 여러 에러 응답을 내릴 수 있다.

같은 response structure 안에서 작성해야 한다.

      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        # These two error responses have the same schema
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
          description: Not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

또한 에러들을 집합적으로 설명하기 위한 default response를 사용할 수도 있다.

"Default"는 개별적으로 operation에 대해 응답이 작성되어 있는 경우가 아니라면,
모든 HTTP codes에 대해 이 응답이 사용될 거라는 뜻이다.

      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        # Definition of all error statuses
        default:
          description: Unexpected error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

✔️Reusing Responses

여러 operation들이 같은 response(status code and data)를 반환한다면, global components.responses 섹션에 정의하고 operation level에서 $ref를 통해 참조할 수 있다.

에러 응답이 같은 status codes 와 response body를 가진다면 유용하다.

paths:
  /users:
    get:
      summary: Gets a list of users.
      response:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ArrayOfUsers'
        '401':
          $ref: '#/components/responses/Unauthorized'   # <-----
  /users/{id}:
    get:
      summary: Gets a user by ID.
      response:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '401':
          $ref: '#/components/responses/Unauthorized'   # <-----
        '404':
          $ref: '#/components/responses/NotFound'       # <-----
# 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

components.responses는 자동으로 모든 operations에 적용되는 게 아니라 참조를 통해 재사용 할 수 있도록 하는 것이다.

✔️Linking Response Values to Other Operations

Certain values in the response could be used as parameters to other operations. A typical example is the "create resource" operation that returns the ID of the created resource, and this ID can be used to get that resource, update or delete it. OpenAPI 3.0 provides the links keyword to describe such relationships between a response and other API calls. For more information, see Links.

✔️FAQ

Can I have different responses based on a request parameter? Such as:

GET /something -> {200, schema_1}
GET /something?foo=bar -> {200, schema_2}

In OpenAPI 3.0, you can use oneOf to specify alternate schemas for the response and document possible dependencies verbally in the response description. However, there is no way to link specific schemas to certain parameter combinations.

profile
백엔드 개발자

0개의 댓글