Describing Parameters

정민교·2023년 7월 11일
0

📒Describing Parameters

OpenAPI 3.0부터 paramters는 operation 혹은 path section의 parameters에 정의한다.

paramter 정의를 위해 'name', 'in'(location), 'schema or content'(data type) description, required attribute들을 명시해야 한다.

parameters는 배열 yaml 파일에서 배열 형태로 작성한다.

paths:
  /users/{userId}:
    get:
      summary: Get a user by ID
      parameters:
        - in: path
          name: userId
          schema:
            type: integer
          required: true
          description: Numeric ID of the user to get

✔️Parameter Types

OpenAPI 3.0은 파라미터 위치에 따라 파라미터들을 구분한다. in attribute로 파라미터의 위치를 표현할 수 있습니다. (in: query, in: path 등)

  • path parameters: such as /users/{id}
  • query parameters: such as /users?role=admin
  • header parameters: such as X-MyHeader: Value
  • cookie parameters: which are passed in the Cookie header, such as Cookie: debug=0; csrftoken=BUSe35dohU3O1MZvDCU

📌Path Parameters

Path Parameter는 URL path의 변수 부분이다. collection안의 resource를 특정하기 위해 보통 사용한다.

하나의 URL에 여러 path parameter들이 있을 수 있으며 중괄호({})로 표시한다.

GET /users/{id}
GET /cars/{carId}/drivers/{driverId}
GET /report.{format}

각 path parameter는 클라이언트에서 api 호출 시 작성한 값으로 대체 되어야한다.

OpenAPI에서 하나의 path parameter는 in: path를 사용해서 path parameter를 정의한다.

path parameter의 name은 path에서 명시된 이름과 같아야 한다.

path parameter는 반드시 값이 필요하기 때문에 required: true를 붙여줘야 한다.

paths:
  /users/{id}:
    get:
      parameters:
        - in: path
          name: id   # Note the name is the same as in the path
          required: true
          schema:
            type: integer
            minimum: 1
          description: The user ID

path parameters가 배열 혹은 객체를 포함하는 경우 각 다른 방법으로 직렬화된다.

  • path-style expansion (matrix) – semicolon-prefixed, such as /map/point;x=50;y=20
  • label expansion – dot-prefixed, such as /color.R=100.G=200.B=150
  • simple-style – comma-delimited, such as /users/12,34,56

직렬화 방법은 style 그리고 explode 키워드에 의해 정해진다.

📌Query Parameters

Query parameters는 요청 URL 끝에 물음표(?)뒤에 키:값 쌍(name=value) 형태로 짝을 이루며, 엠퍼센드(&)로 구분된다.

Query parameters는 필수값 혹은 선택값일 수 있다.

query parameter는 in: query에 정의한다.

     parameters:
        - in: query
          name: offset
          schema:
            type: integer
          description: The number of items to skip before starting to collect the result set
        - in: query
          name: limit
          schema:
            type: integer
          description: The numbers of items to return

🚨API key를 query parameter로 전달하기 위해서는 securitySchemessecurity를 사용해야 한다.

Query parameter는 원시값, 배열, 혹은 객체일 수도 있다.

OpenAPI 3.0에서는 queyr parameter로 사용되는 객체와 배열을 serialize 하기 위해 다양한 방법들을 제공한다.

  • 배열은 다음과 같이 직렬화된다.

    • form/products?color=blue,green,red or /products?color=blue&color=green, depending on the explode keyword
    • spaceDelimited (same as collectionFormat: ssv in OpenAPI 2.0) – /products?color=blue%20green%20red
    • pipeDelimited (same as collectionFormat: pipes in OpenAPI 2.0) – /products?color=blue|green|red
  • 객체는 다음과 같이 직렬화된다.

    • form/points?color=R,100,G,200,B,150 or /points?R=100&G=200&B=150, depending on the explode keyword
    • deepObject/points?color[R]=100&color[G]=200&color[B]=150

직렬화 방법은 style 그리고 explode 키워드에 의해 결정된다.

📌Reserved Characters in Query Parameters

RFC 3986에서는 :/?#[]@!$&'()*+,;= 이 문자들은 URI component delimiter로 사용하기 위한 예약어로 정의하고 있다.

이런 예약어들이 query parameter에서 값으로서 사용되면 보통 percent-encoded 된다.

예를 들면 /%2F(%2f) 인코딩 되기 때문에 quotes/h2g2.txtGET /file?path=quotes%2Fh2g2.txt 이렇게 전송된다.

만약 query parameter가 percent-encoded 되지 않게 하기 위해서는 allowReserved: true를 parameter 정의에 추가해야 한다.

      parameters:
        - in: query
          name: path
          required: true
          schema:
            type: string
          allowReserved: true    # <-----
GET /file?path=quotes/h2g2.txt

📌Header Parameters

API 호출시 custom header를 HTTP request에 포함해야 하는 경우도 있다.

OpenAPI는 custom request headers를 in: header 에 정의할 수 있도록 했다.

예를 들어 GET /pingX-Request_id 커스텀 헤더를 포함해야 하는 경우

GET /ping HTTP/1.1
Host: example.com
X-Request-ID: 77e1c83b-7bb0-437b-bc50-a7a58e5660ac

request header는 아래와 같이 작성할 수 있다.

paths:
  /ping:
    get:
      summary: Checks if the server is alive
      parameters:
        - in: header
          name: X-Request-ID
          schema:
            type: string
            format: uuid
          required: true

이와 비슷하게 custom response headers도 정의할 수 있다.

Header parameter는 원시값, 배열, 혹은 객체일 수도 있다.

배열, 객체는 simple 스타일을 이용해서 직렬화된다.

🚨Header parameter는 custom header를 정의하기 위해 있다. header parameter 이름으로 Accept, Content-Type, Authorization 등의 이름은 사용할 수 없다.

하지만 이와 상응하는 OpenAPI 키워드가 있습니다.

HeaderOpenAPI keywords
Content-TypeRequest content type: requestBody.content.<media-type>
Response content type: responses.<code>.content.<media-type>
Acceptresponses.<code>.content.<media-type>
AuthorizationsecuritySchemes,security

Cookie headers로 파라미터를 전달할 수도 있다. 예를 들면 Cookie: name=value 형태다.

다중 쿠키 파라미터는 같은 헤더 안에서 전달된다.

GET /api/users
Host: example.com
Cookie: debug=0; csrftoken=BUSe35dohU3O1MZvDCUOJ

Cookie parameters는 in: cookie로 정의한다.

      parameters:
        - in: cookie
          name: debug
          schema:
            type: integer
            enum: [0, 1]
            default: 0
        - in: cookie
          name: csrftoken
          schema:
            type: string

쿠키 파라미터는 원시값, 배열, 객체일 수 있다.. 배열과 객체는 form 스타일을 사용하여 직렬화된다.

🚨cookie authentication 정의를 위해서는 API keys를 사용하여야 합니다.

📌Required and Optional Parameters

OpenAPI는 기본적으로 모든 request parameters를 optional로 간주하고 있다.

하지만 path parameter같은 경우는 반드시 필요한 값이 들어와야 하는 parameter이기 때문에 required: true를 설정해야 한다.

      parameters:
        - in: path
          name: userId
          schema:
            type: integer
          required: true    # <----------
          description: Numeric ID of the user to get.

✔️schema vs content

parameter contents를 정의하기 위해서는 schema 혹은 content 키워드를 사용한다.

이 둘은 상호 배타적이며 서로 다른 시나리오에서 사용한다.

📌schema

대부분의 경우는 schema를 사용한다.

schema를 사용해서 원시값을 나타낼 수 있고, 배열, 객체를 직렬화된 문자열로 나타낼 수 있다.

배열과 객체 파라미터의 직렬화 method는 paramters section에서 사용되는 style 그리고 explode 키워드에 의해 정의된다.

parameters:
  - in: query
    name: color
    schema:
      type: array
      items:
        type: string
    # Serialize as color=blue,black,brown (default)
    style: form
    explode: false

📌content

contentstyle 그리고 explode로 해결할 수 없는 complex serialization scenarios의 경우에 사용된다.

예를 들어, JSON 문자열을 query string으로 보내야 하는 경우

filter={"type":"t-shirt","color":"blue"}

이러한 경우에는 schemacontent/<media-type>으로 감싸야한다.(wrap schema into content.<media-type>)

schema에는 parameter의 data structure를 정의하고 media type은 직렬화 형식을 설명하는 외부 사양에 대한 참조 역할을 한다.

parameters:
  - in: query
    name: filter
	
    # Wrap 'schema' into 'content.<media-type>'
    content:
      application/json:  # <---- media type indicates how to serialize / deserialize the parameter content
        schema:
          type: object
          properties:
            type:
              type: string
            color:
              type: string

✔️Default Parameter Values

parameter schema에 default 키워드는 optional parameter의 기본값을 명시하기 위해 사용한다.

offset의 default는 0, limit의 default는 20이며 0~100까지의 범위라면 다음과 같이 paramters를 정의할 수 있다.

      parameters:
        - in: query
          name: offset
          schema:
            type: integer
            minimum: 0
            default: 0
          required: false
          description: The number of items to skip before starting to collect the result set.
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
          required: false
          description: The number of items to return.

🚨default 키워드를 required parameter에 사용해서는 안된다.(예를 들면 path parameter에 사용하는 경우)

🚨sample value를 명시하기 위해 사용해서는 안됩니다. example 혹은 examples 키워드로 sample value를 명시해야 한다.

✔️Enum Parameters

parameter schemaenum을 추가하여 paramter를 일련의 값들로 제한할 수 있다.

enum values들을 반드시 parameter data type과 동일해야 합니다.

      parameters:
        - in: query
          name: status
          schema:
            type: string
            enum:
              - available
              - pending
              - sold

✔️Constant Parameters

required parameter에 사용 가능한 값을 하나로 제한하여 상수 파라미터로 정의할 수 있다.

      parameters:
        - in: query
          name: rel_date
          required: true
          schema:
            type: string
            enum:
              - now

enum 프로퍼티로 사용 가능 값을 명시할 수 있는데 하나만 정의하여 사용 가능 값을 하나로 제한한다.

이는 default parameter value와는 다르다. constant parameters는 언제나 하나의 값만 가지며 클라이언트로부터 받지만, default parameter value는 클라이언트로부터 값을 받지 못했을 때 기본으로 사용할 값이다.

✔️Empty-Valued and Nullable Parameters

Query string parameters는 이름만 있고 값이 없을 수도 있다.

GET /foo?metadata

이런 경우에는 parameter 정의에 allowEmptyValue 프로퍼티 값을 true로 해줘야 한다.

      parameters:
        - in: query
          name: metadata
          schema:
            type: boolean
          allowEmptyValue: true  # <-----

OpenAPI 3.0은 schema에 parameter가 null값을 가질 수 있도록 허용한다.

✔️parameter examples

파라미터에 대해 example 혹은 examples를 명시할 수 있다.

      parameters:
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
          example: 20
      parameters:
        - in: query
          name: ids
          description: One or more IDs
          required: true
          schema:
            type: array
            items:
              type: integer
          style: form
          explode: false
          examples:
            oneId:
              summary: Example of a single ID
              value: [5]   # ?ids=5
            multipleIds:
              summary: Example of multiple IDs
              value: [1, 5, 7]   # ?ids=1,5,7

✔️Deprecated Parameters

deprecated: true를 명시해 deprecated parameter를 정의할 수 있다.

        - in: query
          name: format
          required: true
          schema:
            type: string
            enum: [json, xml, yaml]
          deprecated: true
          description: Deprecated, use the appropriate `Accept` header instead.

✔️Common Parameters

📌Common Parameters for All Methods of a Path

공통 파라미터는 operation level말고 path level에서도 정의할 수 있다.

Path-level parameters들은 모든 operations들이 물려받는다.

전형적인 사용 예시는 path parameter를 통해 접근한 resourse를 조작하는 GET/PUT/PATH/DELETE operations다.

paths:
  /user/{id}:
    parameters:
      - in: path
        name: id
        schema:
          type: integer
        required: true
        description: The user ID
    get:
      summary: Gets a user by ID
      ...
    patch:
      summary: Updates an existing user with the specified ID
      ...
    delete:
      summary: Deletes the user with the specified ID

operations level에서 필요한 파라미터를 추가로 정의할 수 있다.

paths:
  /users/{id}:
    parameters:
      - in: path
        name: id
        schema:
          type: integer
        required: true
        description: The user ID.
    # GET/users/{id}?metadata=true
    get:
      summary: Gets a user by ID
      # Note we only define the query parameter, because the {id} is defined at the path level.
      parameters:
        - in: query
          name: metadata
          schema:
            type: boolean
          required: false
          description: If true, the endpoint returns only the user metadata.
      responses:
        '200':
          description: OK

path-level parameters들은 operation level의 paramter에 의해 override 될 수 있다.

paths:
  /users/{id}:
    parameters:
      - in: path
        name: id
        schema:
          type: integer
        required: true
        description: The user ID.
    # DELETE /users/{id} - uses a single ID.
    # Reuses the {id} parameter definition from the path level.
    delete:
      summary: Deletes the user with the specified ID.
      responses:
        '204':
          description: User was deleted.
    # GET /users/id1,id2,id3 - uses one or more user IDs.
    # Overrides the path-level {id} parameter.
    get:
      summary: Gets one or more users by ID.
      parameters:
        - in: path
          name: id
          required: true
          description: A comma-separated list of user IDs.
          schema:
            type: array
            items:
              type: integer
            minItems: 1
          explode: false
          style: simple
      responses:
        '200':
          description: OK

📌Common Parameters for Various Paths

서로 다른 API path들도 공통으로 사용하는 parameters들이 있다. 예를 들면 pagination에 사용하는 parameter다.

이러한 공통 파라미터들은 global components 섹션에 parameters 프로퍼티로 정의할 수 있으며, 어디서든 $ref로 참조할 수 있다.

components:
  parameters:
    offsetParam:  # <-- Arbitrary name for the definition that will be used to refer to it.
                  # Not necessarily the same as the parameter name.
      in: query
      name: offset
      required: false
      schema:
        type: integer
        minimum: 0
      description: The number of items to skip before starting to collect the result set.
    limitParam:
      in: query
      name: limit
      required: false
      schema:
        type: integer
        minimum: 1
        maximum: 50
        default: 20
      description: The numbers of items to return.
paths:
  /users:
    get:
      summary: Gets a list of users.
      parameters:
        - $ref: '#/components/parameters/offsetParam'
        - $ref: '#/components/parameters/limitParam'
      responses:
        '200':
          description: OK
  /teams:
    get:
      summary: Gets a list of teams.
      parameters:
        - $ref: '#/components/parameters/offsetParam'
        - $ref: '#/components/parameters/limitParam'
      responses:
        '200':
          description: OK

components 섹션이 정의된 파라미터들은 모든 operations에 적용되는 것이 아니라, 단지 재사용 가능한 global definition이다.

✔️Parameter Dependencies

OpenAPI 3.0은 paramter dependencies를 지원하지 않는다.

예를 들어 /report endpoint는 rdate 파라미터 혹은 start_date + end_date 파라미터 둘 중 하나를 사용하도록 하고 싶다면 아래와 같이 할 수 있다.

GET /report?rdate=Today
GET /report?start_date=2016-11-15&end_date=2016-11-20
paths:
  /report:
    get:
      parameters:
        - name: rdate
          in: query
          schema:
            type: string
          description: >
             A relative date range for the report, such as `Today` or `LastWeek`.
             For an exact range, use `start_date` and `end_date` instead.
        - name: start_date
          in: query
          schema:
            type: string
            format: date
          description: >
            The start date for the report. Must be used together with `end_date`.
            This parameter is incompatible with `rdate`.
        - name: end_date
          in: query
          schema:
            type: string
            format: date
          description: >
            The end date for the report. Must be used together with `start_date`.
            This parameter is incompatible with `rdate`.
      responses:
        '400':
          description: Either `rdate` or `start_date`+`end_date` are required.
profile
백엔드 개발자

0개의 댓글