zero-wiki Help

자원 생성

경로 파라미터가 어떻게 동작하는지 알아보고 api를 통해 자원을 생성하고 조회를 진행한다.

문제 정의

POST /reviews 요청을 보내기 위해서는 아래 필드가 필요하다.

  • message (string)

  • rating (number)

  • userId (string)

post 요청은 다음과 같이 요청 본문에 위 필드에 대한 정보를 작성하면 된다.

openapi: 3.0.3 # ... paths: /reviews: post: # POST를 포함한 일부 메소드만 요청 본문을 필요로 한다. requestBody: #... 요청 본문 작성 위치

POST와 요청 본문 기술하기

있는 정보를 조회하는 GET 요청과 달리 POST 요청은 실행될 때마다 새로운 자원을 생성하므로, 멱등하지 않다.

요청 본문

하나의 연산은 하나의 requestBody만 포함할 수 있다. 미디어 타입은 저마다의 규격이 있고 각 규격은 여러 다른 요청 본문에 맞도록 기술할 수 있다.

또한 일부 연산에만 요청 본문이 허용된다는 점도 주목해야한다. 대표적인 예시로 GET과 DELETE와 같은 연산에는 요청 본문이 허용되지 않습니다. 물론 포함하는 게 기술적으로는 가능할 수 있지만 HTTP 명세에는 어긋납니다. 또 명세를 그대로 구현하는 서버에 경우 요청 본문을 무시하므로 의도대로 작동하지 않을 수 있습니다.

openapi: 3.0.3 # ... paths: /foo: post: #... requestBody: description: Return a bar after creating a foo content: # 요청 본문 내용이나 데이터를 기술한다. application/json: # 요청 본문 데이터의 미디어 타입 schema: type: object properties: bar: type: string

requestBody의 스키마

기존에 GET 요청을 할 때 가져오는 필드는 다음과 같이 표시할 수 있었습니다.

type: object properties: message: # 제약사항이 없는 문자열 값을 갖는 message 필드 type: string rating: type: integer minimum: 1 maximum: 5 userId: type: string pattern: '^[0-9a-fa-F\-]{36}$' nullable: true

이러한 스키마의 내용을 OpenAPI 정의서의 POST /reviews의 연산 부분에 추가할 수 있습니다.

paths: /reviews: post: # /reviews 경로의 POST 메소드에 대한 내용 기술 description: Create a new review requestBody: # 요청 본문 정의 내용을 작성한다. description: A new Review content: application/json: schema: type: object properties: message: type: string rating: type: integer minimum: 1 maximum: 5 userId: type: string pattern: '^[0-9a-fa-F\-]{36}$' nullable: true responses: '201': description: Successfully created a new Review content: application/json: schema: type: object properties: message: type: string rating: type: integer minimum: 1 maximum: 5 userId: type: string pattern: '^[0-9a-fa-F\-]{36}$' nullable: true uuid: type: string pattern: '^[0-9a-fa-F\-]{36}$'

예시 추가로 try-it-out 기능 개선

작성한 스키마는 무미건조하다. 예시를 사용하면 스키마를 읽는 것보다 훨씬 더 빨리 요점을 파악할 수 있게 된다.

/reviews: post: description: Create a new review requestBody: description: A new Review content: application/json: schema: type: object properties: message: type: string example: Blew my mind, life won't be the same after.. rating: type: integer minimum: 1 maximum: 5 example: 5 userId: type: string pattern: '^[0-9a-fa-F\-]{36}$' nullable: true

경로 파라미터를 포함한 GET 기술하기

요청 /reviews/{reviewId}에는 중괄호가 포함돼 있다. 이런걸 경로 파라미터라고 부른다.

경로 파라미터

경로 파라미터는 쿼리 파라미터를 기술하는 방법과 똑같은 방법으로 기술할 수 있다.

  • name: 파라미터 이름

  • in: 파라미터 위치 (query, path, header, cookie)

  • schema: 파라미터 스키마

추가로 다음 사항도 들어갈 수 있다.

  • required, example, examples,

  • deprecated: 파라미터의 폐기 여부

  • style: 값 직렬화 방식

  • explode: 배열 원소나 객체 필드에 대한 별도의 파라미터 생성 여부

  • allowReserved: '/'나 '?'처럼 예약된 문자 허용 여부. 캐치올 파라미터 사용시 유용하다.

경로 파라미터 기술하기

다음과 같이 기술할 수 있다.

parameters: - in: path name: reviewId required: true schema: type: string description: The review's ID example: 3basd0d00w899d-12dasdg-fsdf
Last modified: 28 November 2024