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 문서로 묘사. 도구가 docs 렌더 (Redoc, Swagger UI), 요청/응답 검증 (Stoplight, Spectral), 수십 언어로 SDK 생성 — 다 같은 source 파일에서.

최상위 모양

  • openapi: — spec 버전 (현재 3.1.0).
  • info: — 제목, 버전, 설명.
  • paths: — 엔드포인트. 각 path → method (get/post/etc.) → parameter/requestBody/response.
  • components: — 재사용 가능한 schema, parameter, response, security scheme.

왜 JSON 위에 YAML

OpenAPI spec 이 자주 깊이 중첩된 schema 가진 수백 줄. 주석, anchor, folded string 이 YAML 을 readable 하게 만듦, JSON 등가는 벽이 됨. spec 이 둘 다 받아들임; 팀이 다수결로 YAML 선택.

Schema-first vs code-first: 두 유효 워크플로우. Schema-first 가 OpenAPI YAML 손으로 작성 후 server stub + client 생성. Code-first 가 server (FastAPI, NestJS, ASP.NET) 작성 후 decorator 에서 OpenAPI emit. 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

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

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