검색
검색
공개 노트 검색
회원가입로그인

[GPT Actions] 3. 데이터 모델 정의 및 Components 활용하기

요약
  • OpenAPI 스키마의 components 섹션에서 데이터 모델, 응답, 매개변수, 예제 등을 재사용할 수 있는 방법을 배웠습니다.
  • 'Book', 'Author', 'Review' 스키마를 정의하고, 이들을 paths 섹션에서 어떻게 활용하는지 설명했습니다.
  • API 문서의 일관성을 유지하고, 중복을 줄이며, 문서를 더 이해하기 쉽게 만드는 components 섹션의 중요성을 강조했습니다.
page thumbnail

안녕하세요! 이번 파트에서는 OpenAPI 스키마의 components 섹션에 대해 자세히 알아보고, 데이터 모델을 정의하는 방법을 배워보겠습니다. 또한 이를 통해 스키마를 더 효율적으로 구성하는 방법도 알아보겠습니다.

  1. components 섹션이란?

components 섹션은 API 전체에서 재사용할 수 있는 다양한 요소들을 정의하는 곳입니다. 여기에는 스키마(데이터 모델), 응답, 매개변수, 예제 등이 포함될 수 있습니다. 이 섹션을 잘 활용하면 중복을 줄이고 일관성을 유지할 수 있습니다.

  1. 스키마(Schema) 정의하기

스키마는 데이터의 구조를 정의합니다. 우리의 Bookstore API에서 "Book"과 "Author" 스키마를 정의해 봅시다.

my_api.yaml 파일을 열고 components 섹션을 다음과 같이 수정해주세요:

components:
  schemas:
    Book:
      type: object
      properties:
        id:
          type: integer
        title:
          type: string
        author:
          $ref: '#/components/schemas/Author'
        publicationYear:
          type: integer
      required:
        - title
        - author
    Author:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        birthYear:
          type: integer
      required:
        - name

이 코드에 대해 설명드리겠습니다:

  • schemas: 여기서 재사용 가능한 스키마들을 정의합니다.

  • Book: 책에 대한 스키마입니다.

    • properties: 책의 속성들을 정의합니다.

    • required: 필수 속성들을 나열합니다.

  • Author: 저자에 대한 스키마입니다.

  • $ref: '#/components/schemas/Author': 이는 Author 스키마를 참조한다는 의미입니다. 이렇게 하면 스키마 간 관계를 표현할 수 있습니다.

  1. 스키마 재사용하기

이제 정의한 스키마를 paths 섹션에서 재사용해 봅시다. '/books' 경로의 GET 메서드 응답을 수정해보겠습니다:

paths:
  /books:
    get:
      summary: List all books
      description: Retrieves a list of all books in the inventory
      responses:
        '200':
          description: Successful response
          content:
            application/json:    
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Book'

여기서 $ref: '#/components/schemas/Book'은 우리가 components 섹션에서 정의한 Book 스키마를 참조합니다.

  1. 응답(Response) 재사용하기

자주 사용되는 응답도 components 섹션에 정의하여 재사용할 수 있습니다. 에러 응답을 정의해 봅시다:

components:
  schemas:
    # (이전 스키마 정의는 그대로 둡니다)
  responses:
    NotFound:
      description: The specified resource was not found
      content:
        application/json:
          schema:
            type: object
            properties:
              message:
                type: string
    BadRequest:
      description: Bad request
      content:
        application/json:
          schema:
            type: object
            properties:
              message:
                type: string

이제 이 응답들을 paths 섹션에서 재사용할 수 있습니다:

paths:
  /books/{bookId}:
    get:
      summary: Get a book by ID
      description: Retrieves details of a specific book
      parameters:
        - $ref: '#/components/parameters/BookId'
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Book'
        '404':
          $ref: '#/components/responses/NotFound'
  1. 매개변수(Parameter) 재사용하기

자주 사용되는 매개변수도 components 섹션에 정의할 수 있습니다:

components:
  # (이전 정의는 그대로 둡니다)
  parameters:
    BookId:
      name: bookId
      in: path
      required: true
      schema:
        type: integer
      description: The ID of the book

이제 이 매개변수를 paths 섹션에서 재사용할 수 있습니다:

paths:
  /books/{bookId}:
    get:
      summary: Get a book by ID
      description: Retrieves details of a specific book
      parameters:
        - $ref: '#/components/parameters/BookId'
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Book'
        '404':
          $ref: '#/components/responses/NotFound'
  1. 예제(Example) 추가하기

components 섹션에 예제를 추가하면 API 문서를 더 이해하기 쉽게 만들 수 있습니다:

components:
  # (이전 정의는 그대로 둡니다)
  examples:
    BookExample:
      value:
        id: 1
        title: "The Great Gatsby"
        author:
          id: 1
          name: "F. Scott Fitzgerald"
          birthYear: 1896
        publicationYear: 1925

이 예제를 응답에 추가해 봅시다:

paths:
  /books/{bookId}:
    get:
      # (이전 정의는 그대로 둡니다)
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Book'
              example:
                $ref: '#/components/examples/BookExample'
        '404':
          $ref: '#/components/responses/NotFound'

[연습문제]

이제 여러분 차례입니다! 다음 요구사항을 만족하는 새로운 스키마와 응답을 추가해보세요:

  • "Review" 스키마 추가: id(integer), bookId(integer), rating(integer, 1-5), comment(string)

  • "ReviewCreated" 응답 추가: 201 상태 코드, Review 스키마 사용

  • '/books/{bookId}/reviews' POST 경로 추가: 새 리뷰 생성, ReviewCreated 응답 사용

    [정답]

여러분의 스키마가 다음과 비슷하다면 정답입니다:

components:
  schemas:
    # (이전 스키마는 그대로 둡니다)
    Review:
      type: object
      properties:
        id:
          type: integer
        bookId:
          type: integer
        rating:
          type: integer
          minimum: 1
          maximum: 5
        comment:
          type: string
      required:
        - bookId
        - rating
  responses:
    # (이전 응답은 그대로 둡니다)
    ReviewCreated:
      description: Review created successfully
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Review'

paths:
  # (이전 경로는 그대로 둡니다)
  /books/{bookId}/reviews:
    post:
      summary: Create a new review
      description: Adds a new review for a specific book
      parameters:
        - $ref: '#/components/parameters/BookId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Review'
      responses:
        '201':
          $ref: '#/components/responses/ReviewCreated'
        '400':
          $ref: '#/components/responses/BadRequest'
        '404':
          $ref: '#/components/responses/NotFound'

축하합니다! 이번 파트에서 우리는 OpenAPI 스키마의 components 섹션을 자세히 살펴보았습니다. 재사용 가능한 스키마, 응답, 매개변수, 예제를 정의하고 이를 paths 섹션에서 활용하는 방법을 배웠습니다.

components 섹션을 잘 활용하면 API 문서의 일관성을 유지하고, 중복을 줄이며, 문서를 더 이해하기 쉽게 만들 수 있습니다. 이는 대규모 API를 설계할 때 특히 유용합니다.

다음 파트에서는 보안 스키마를 정의하고 API에 인증을 추가하는 방법에 대해 배워보겠습니다. 궁금한 점이 있다면 언제든 물어보세요.

공유하기
카카오로 공유하기
페이스북 공유하기
트위터로 공유하기
url 복사하기
조회수 : 97
heart
T
페이지 기반 대답
AI Chat