본문 바로가기
C.W.K.
Stream
Lesson 06 of 08 · published

OpenAPI — YAML 의 API 계약

~12 min · yaml, openapi, api

Level 0평문
0 XP0/64 lessons0/12 achievements
0/100 XP to next level100 XP to go0% complete

한 YAML 파일에서 API 문서, 검증, SDK 생성

OpenAPI 3.x, 예전 이름으로는 Swagger 가 HTTP API 를 YAML 이나 JSON 문서 한 장으로 그려. 그러면 도구들이 그 한 파일에서 문서를 렌더하고 (Redoc, Swagger UI), 요청과 응답을 검증하고 (Stoplight, Spectral), 수십 개 언어로 SDK 를 뽑아내.

최상위 모양

  • openapi: — spec 버전이야 (지금은 3.1.0).
  • info: — 제목과 버전, 설명이 들어가.
  • paths: — 엔드포인트들이야. path 아래 method (get/post 등) 를 두고, 그 아래 parameter 와 requestBody, response 를 달아.
  • components: — 돌려 쓸 schema 와 parameter, response, security scheme 을 모아둬.

왜 JSON 위에 YAML

OpenAPI spec 은 깊이 중첩된 schema 를 잔뜩 안고 수백 줄로 자라는 일이 흔해. 주석과 anchor, folded 문자열이 있는 YAML 은 그래도 읽히는데, 같은 걸 JSON 으로 쓰면 그냥 벽이 돼. spec 자체는 둘 다 받아주고, 그래서 팀들이 알아서 YAML 쪽으로 몰린 거야.

Schema-first vs code-first: 둘 다 멀쩡한 방식이야. schema-first 는 OpenAPI YAML 을 손으로 먼저 쓰고 거기서 server stub 과 client 를 뽑아. code-first 는 server 를 먼저 짜고 (FastAPI, NestJS, ASP.NET) decorator 에서 OpenAPI 를 뽑아내지. schema-first 쪽이 계약이 더 단단하고, code-first 쪽이 피드백이 더 빨라. 판단 기준은 팀 크기야. 작은 팀이면 code-first, 여러 팀이 함께 쓰는 API 면 schema-first.

Code

작지만 완전한 OpenAPI 문서·yaml
openapi: 3.1.0
info:
  title: Pippa API
  version: 1.0.0
  description: Toy API for the markup quest.

paths:
  /users/{id}:
    get:
      operationId: getUser
      parameters:
        - in: path
          name: id
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: User found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          description: User not found

components:
  schemas:
    User:
      type: object
      properties:
        id:    { type: integer }
        name:  { type: string  }
        email: { type: string, format: email }
      required: [id, name, email]
Docs 렌더, 검증, 클라이언트 생성·bash
# Docs 라이브 미리보기 (Redocly / Stoplight Studio)
npx @redocly/cli preview-docs openapi.yaml

# Spectral 로 lint (스타일 + best practice)
npm install -g @stoplight/spectral-cli
spectral lint openapi.yaml

# TypeScript 클라이언트 생성
npx openapi-typescript openapi.yaml -o api-types.ts

# Python 클라이언트 생성 (openapi-generator)
openapi-generator-cli generate -i openapi.yaml -g python-pydantic-v1 -o ./gen
여러 path 에서 참조되는 재사용 schema (component)·yaml
components:
  schemas:
    Error:
      type: object
      properties:
        code:    { type: integer }
        message: { type: string  }
      required: [code, message]

paths:
  /a:
    get:
      responses:
        '500':
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /b:
    get:
      responses:
        '500':
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

External links

Exercise

직접 만든 내부 HTTP 엔드포인트를 하나 골라. OpenAPI 정의를 손으로 써봐. path, method, parameter, request body, response schema, 그리고 error 모양까지. Redocly preview 로 렌더해서 보고. 그러다 schema 와 실제 코드가 갈라지는 데를 찾으면, 거기가 진짜 버그야. API 가 말한 것과 내놓는 게 다른 거니까.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.