ข้ามไปยังเนื้อหา

OpenAPI

OpenAPI (เดิมเรียกว่า Swagger) คือวิธีมาตรฐานที่เครื่องอ่านได้ในการอธิบาย REST API ทั้ง path, operation, parameter, schema ของ request/response และ status code เอกสารเพียงไฟล์เดียวขับเคลื่อนทั้งเอกสาร การสร้าง client, mock server และการทดสอบ

นี่คือ endpoint หนึ่งที่อธิบายด้วย OpenAPI 3.1 (YAML)

openapi: 3.1.0
info:
title: Blog API
version: 1.0.0
paths:
/articles/{id}:
get:
summary: Get an article by id
parameters:
- name: id
in: path
required: true
schema:
type: string
responses:
'200':
description: The article
content:
application/json:
schema:
$ref: '#/components/schemas/Article'
'404':
description: Not found
components:
schemas:
Article:
type: object
required: [id, title]
properties:
id: { type: string }
title: { type: string }
body: { type: string }

แต่ละ operation จะประกาศ parameter ของตัวเองและทุก response ที่คืนได้ โดยผูกแต่ละตัวเข้ากับ schema ส่วน components/schemas เก็บรูปแบบที่ใช้ซ้ำได้ แล้วอ้างถึงด้วย $ref

  • Spec-first — เขียนเอกสาร OpenAPI ก่อน แล้วค่อยสร้างของจริงให้ตรงตามนั้น วิธีนี้ตกลง contract กันได้ตั้งแต่ยังไม่มี code จึงเหมาะมากกับทีมและ consumer ภายนอก
  • Code-first — ใส่ annotation ให้ handler/schema แล้ว generate spec ออกมาจาก code ตรง ๆ วิธีนี้ code กับ spec จะคลาดเคลื่อนกันน้อยกว่า เพราะฝ่ายหนึ่งผลิตอีกฝ่ายออกมา

ไม่ว่าจะเลือกทางไหน เครื่องมือก็ดึงคุณค่าจาก spec ออกมาได้ Swagger UI / Redoc ทำเป็นเอกสารแบบโต้ตอบ ตัว generator ปั้น client ที่มี type ให้ และ validator ก็เอา spec ไปตรวจ request ที่วิ่งเข้ามา

ข้อดี (OpenAPI)ข้อแลกเปลี่ยน
documentation generate จาก schema — ไม่ drift จาก codesetup OpenAPI spec ต้องการ discipline
SDK generation อัตโนมัติ สำหรับหลายภาษาspec ที่ verbose — YAML/JSON file ใหญ่
validation middleware จาก schema — request/response ถูกต้องเสมอcode-first vs spec-first ต้องเลือก approach
contract testing ระหว่าง producer และ consumerspec เก่า ถ้า developer ไม่ update พร้อมกับ code

OpenAPI Spec ที่ Drift จาก Implementation อาการ:

  • เขียน spec ก่อน แล้ว implement ตาม — แต่ implementation เปลี่ยนโดยไม่ update spec
  • developer ใช้ spec ที่ผิดสร้าง client — bug ตอน integrate
  • generate spec จาก code (code-first) หรือ enforce spec validation ใน CI

ไม่มี Example ใน Spec อาการ:

  • spec มีแค่ type definition ไม่มี example request/response
  • developer ไม่รู้ว่า field ควรส่งค่าอะไร — ต้องลองเอง
  • เพิ่ม example หรือ examples field ใน spec ทุก request/response body

💡 ตัวอย่างจากของจริง

Stripe API:

  • OpenAPI spec ที่ comprehensive — ทุก endpoint มี schema, example, error response
  • ใช้ generate SDK สำหรับ 7+ ภาษา: Python, Ruby, Node.js, Go, Java, PHP, .NET

GitHub API:

  • OpenAPI spec เปิดสาธารณะ — community สร้าง SDK และ tool บน spec นั้น
  • Octokit ทุกภาษา generate มาจาก spec เดียวกัน
เอกสาร OpenAPI อธิบายอะไร?
อะไรคือสิ่งที่แยก spec-first ออกจาก code-first?
ข้อใดคือประโยชน์โดยตรงของ spec ของ OpenAPI ที่ดูแลรักษาไว้ดี?