ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
ဆိုင်တစ်ဆိုင်ရဲ့ menu ကို စဉ်းစားကြည့်ပါ။ ဘာတွေ ရနိုင်လဲ၊ ဘယ်လောက်လဲ၊ ဘာထည့်ရလဲ၊ ဘာမျိုး ပြန်ရမလဲ ဆိုတာ menu မှာ ရေးထားလို့ ဧည့်သည်က မီးဖိုချောင်ကို မမေးဘဲ မှာလို့ရပါတယ်။ OpenAPI document ဆိုတာ API အတွက် menu ပါပဲ — endpoint တစ်ခုချင်းစီက ဘာလက်ခံလဲ၊ ဘာပြန်လဲ၊ error ဘာတွေ ရနိုင်လဲ ဆိုတာကို ရေးထားပါတယ်။
ထူးခြားချက်က ဒီ menu ကို လူကသာမက program တွေကပါ ဖတ်နိုင်တာပါ။ ဒါကြောင့် tool တွေက ဒီ document တစ်ခုထဲကနေ စာမျက်နှာ၊ client code၊ mock server နဲ့ စစ်ဆေးမှုတွေကို အလိုလို ထုတ်ပေးနိုင်ပါတယ်။ ဒါပေမယ့် menu ကမှားနေရင် ဧည့်သည်တွေလည်း မှားပြီး မှာကြမှာမို့ spec ကို မှန်အောင် ထိန်းဖို့လည်း လိုပါတယ်။
Problem → Why → Solution
ပြဿနာ: စာရွက်ပေါ်က docs နဲ့ တကယ့် server မတူတာ
Team တစ်ခုက API docs ကို wiki စာမျက်နှာတစ်ခုမှာ လက်နဲ့ ရေးထားပါတယ်။ မတ်လမှာ ရေးတုန်းက GET /users/1 က id ကို number အဖြစ် ပြန်ပါတယ်။ နောက်ပိုင်း backend ကို UUID ပြောင်းလိုက်တဲ့အခါ id က string ဖြစ်သွားပေမယ့် wiki ကို ဘယ်သူမှ မပြင်ဖြစ်ပါဘူး၊ partner တစ်ဦးရဲ့ integration က user.id + 1 လို တွက်ချက်မှုတွေမှာ တိတ်တိတ်လေး မှားပါတော့တယ်။
Swagger UI နဲ့ render လုပ်ထားတဲ့ docs ကို ကြည့်ရတာ လှလှပပ ပြည့်စုံပေမယ့် အဲဒီ spec ကို လအနည်းငယ်က ရေးထားတာဆိုရင် အလားတူ ပြဿနာ ဖြစ်နိုင်ပါတယ်။ စာမျက်နှာတစ်ခု လှတယ်ဆိုတာ ဒီ document က မှန်တယ်လို့ မဆိုလိုပါဘူး၊ ဖတ်လို့ရတယ်လို့ပဲ ဆိုလိုပါတယ်။
// The wiki (written in March) promises: GET /users/1 -> { "id": 1, "name": "..." }
const res = await fetch("https://api.example.com/v1/users/1");
const user = await res.json();
console.log(typeof user.id); // the docs promise "number", the server now sends "string"
console.log(user.id + 1); // "11" instead of 2: wrong, with no error anywhereဘာကြောင့် docs နဲ့ code မကိုက်တော့တာလဲ
စာရွက်ပေါ်က docs နဲ့ code က အမှန်တရား နှစ်ခု ဖြစ်နေပြီး တစ်ခုပြောင်းရင် နောက်တစ်ခုက အလိုလို မပြောင်းပါဘူး။ ဖြေရှင်းနည်းက spec ကို machine-readable ဖြစ်အောင်ရေးပြီး CI မှာ စစ်တာပါ — lint လုပ်၊ တကယ့် response ကို spec နဲ့ နှိုင်းယှဉ်၊ ပြီးခဲ့တဲ့ release နဲ့ diff လုပ်ပါ။ ဒီလိုဆိုရင် မကိုက်တာကို production မရောက်ခင် ဖမ်းမိပါမယ်။
Core concept: OpenAPI ဆိုတာ contract ကို data အဖြစ် ရေးတာ
OpenAPI ဆိုတာ HTTP API တစ်ခုကို programming language မရွေး၊ machine-readable ပုံစံနဲ့ ဖော်ပြတဲ့ standard ပါ၊ YAML ဒါမှမဟုတ် JSON နဲ့ ရေးပါတယ်။ Path တွေ၊ operation တွေ (method + path)၊ parameter တွေ (path, query, header, cookie)၊ request body၊ status code အလိုက် response နဲ့ schema၊ authentication နည်းလမ်းနဲ့ example တွေကို ဖော်ပြပါတယ်။ Specification ကို အရင်က Swagger လို့ ခေါ်ခဲ့ပြီး ယနေ့ OpenAPI လို့ ခေါ်ပါတယ်၊ Swagger UI လို tool တွေရဲ့ နာမည်ကတော့ ဆက်ရှိနေပါတယ်။ Data ဖြစ်လို့ tool တွေက docs render လုပ်၊ client ထုတ်၊ mock server ဖွင့်၊ request/response validate လုပ်၊ version နှစ်ခုကို နှိုင်းယှဉ်လို့ ရပါတယ်။
Document ရဲ့ ဖွဲ့စည်းပုံကတော့ ရိုးရိုးပါပဲ။ openapi က spec version၊ info က title နဲ့ version၊ servers က base URL၊ paths က endpoint တွေ၊ components က ပြန်သုံးလို့ရတဲ့ schema, parameter နဲ့ securitySchemes တွေပါ — ဒါတွေကို $ref နဲ့ ပြန်ညွှန်းပါတယ်။ Operation တိုင်းမှာ operationId (document တစ်ခုလုံးမှာ မထပ်ရ၊ client generator တွေက function နာမည်အဖြစ် သုံးပါတယ်) နဲ့ status code အလိုက် responses ရှိရမယ်၊ error တွေလည်း ပါရမယ်။ လက်ရှိ OpenAPI 3.1 ကို သုံးသူများပေမယ့် 3.0 ကိုပဲ ထောက်ပံ့တဲ့ tool တွေလည်း ရှိလို့ ကိုယ့် tool တွေ ဘယ် version ထောက်ပံ့လဲ စစ်ပါ။
Design-first နဲ့ code-first ဆိုပြီး နည်းလမ်း နှစ်မျိုး ရှိပါတယ်။ Design-first မှာ spec ကို အရင်ရေးပြီး client ဆောင်ရွက်သူတွေနဲ့ review လုပ်ကာ server stub ထုတ်ပါတယ်။ Code-first မှာ code ထဲက annotation ဒါမှမဟုတ် type တွေကနေ spec ကို ထုတ်ပါတယ်။ ဘယ်နည်းလမ်းကို သုံးသုံး drift (spec က integer လို့ ပြောပြီး server က string ပို့တာ) ဆိုတဲ့ အန္တရာယ်က ရှိနေပါတယ်။ CI မှာ spec ကို lint လုပ်ပါ၊ တကယ့် response တွေကို schema နဲ့ စစ်တဲ့ contract test run ပါ၊ ပြီးခဲ့တဲ့ release နဲ့ နှိုင်းယှဉ်ပြီး breaking change ကို ဖမ်းပါ။
Spec က အရာအားလုံးကို မဖော်ပြနိုင်ပါဘူး။ Error model၊ pagination၊ authentication၊ rate limit၊ idempotency နဲ့ webhook တွေကို တစ်စိတ်တစ်ပိုင်းပဲ ဖော်ပြနိုင်ပြီး (OpenAPI 3.1 မှာ webhooks ကို ဖော်ပြနိုင်ပေမယ့် delivery နဲ့ retry အပြုအမူကိုတော့ စာနဲ့ရှင်းရပါမယ်) token ဘယ်လိုရမလဲ၊ rate limit ဘယ်လောက်လဲ၊ ဘယ်ပုံစံ retry လုပ်ရမလဲ ဆိုတာတွေကို စာနဲ့ ရှင်းပြရပါတယ်။ Example တွေကို ကိုယ်ပိုင် secret နဲ့ လူပုဂ္ဂိုလ်ရဲ့ data မပါဘဲ example.com နဲ့ အတု token တွေ သုံးရေးပါ။
- Spec ကို ရေး သို့ ထုတ်
- CI မှာ lint နဲ့ validate
- Docs, client, mock ကို ထုတ်
- Server ကို contract-test
Spec တစ်ခုတည်းကို အမှန်တရားအဖြစ် ထားပြီး ကျန်တာအားလုံးကို အဲဒီကနေ ထုတ်ယူပါတယ်။
အထွေထွေ ပုံစံ: OpenAPI document ရဲ့ အရိုးစု
openapi: 3.1.0
info: { title: <API name>, version: <document version> }
paths:
/<resource>/{<param>}:
<get | post | put | patch | delete>:
operationId: <uniqueName>
parameters: [<name, in, required, schema>]
requestBody: { content: { <media type>: { schema: <schema> } } }
responses:
"<status>": { description: <text>, content: <media types> }
components: { schemas: <reusable schemas>, securitySchemes: <auth> }< > ထဲက အရာတွေက ကိုယ့်တန်ဖိုးနဲ့ အစားထိုးရမယ့် နေရာတွေပါ။ Operation တစ်ခုက method အောက်မှာ ရှိပြီး parameter, requestBody, responses တို့နဲ့ ဖွဲ့စည်းထားပါတယ်၊ ထပ်သုံးမယ့် schema တွေကို components ထဲ ထားပြီး $ref နဲ့ ညွှန်းပါတယ်။
Example: spec ကို serve၊ validate လုပ်ပြီး client ထုတ်ခြင်း
ဒီ example က node:http နဲ့ mock server တစ်ခု စတင်ပြီး /openapi.json မှာ spec ကို ပေးပါတယ်။ ပြီးတော့ client ဘက်က spec ကို fetch လုပ်၊ validateSpec() နဲ့ ဖွဲ့စည်းပုံကို စစ်ပြီး (operationId ထပ်မထပ်၊ path parameter ကြေညာထားလား၊ $ref တွေ ရှိလား)၊ buildClient() နဲ့ operation တစ်ခုချင်းစီအတွက် function တစ်ခုစီ ထုတ်ပါတယ်။
ထုတ်ထားတဲ့ client မှာ client.getUser({ id: 2 }) လို့ ခေါ်ရင် /users/{id} က /users/2 ဖြစ်သွားပါတယ်။ အဆုံးမှာ spec ကို တမင်ချိုးပြီး (parameter ဖျက်၊ မရှိတဲ့ schema ကို $ref) validator က ဘာတွေ ဖမ်းမိလဲ ပြပါတယ်။ ဒီ validator က ရိုးရိုးသဘောတရား သရုပ်ပြတာပဲ၊ တကယ့် project မှာ Spectral လို linter ကို သုံးပါ။
import http from "node:http";
const json = (schema) => ({ "application/json": { schema } });
const ref = (name) => ({ $ref: "#/components/schemas/" + name });
const spec = {
openapi: "3.1.0",
info: { title: "Users API", version: "1.2.0" },
paths: {
"/users": {
get: {
operationId: "listUsers",
parameters: [{ name: "limit", in: "query", schema: { type: "integer" } }],
responses: {
200: {
description: "A list of users",
content: json({ type: "array", items: ref("User") }),
},
},
},
post: {
operationId: "createUser",
requestBody: { required: true, content: json(ref("NewUser")) },
responses: {
201: { description: "Created", content: json(ref("User")) },
422: { description: "Validation failed" },
},
},
},
"/users/{id}": {
get: {
operationId: "getUser",
parameters: [
{ name: "id", in: "path", required: true, schema: { type: "integer" } },
],
responses: {
200: { description: "The user", content: json(ref("User")) },
404: { description: "No such user" },
},
},
},
},
components: {
schemas: {
NewUser: {
type: "object",
required: ["name"],
properties: { name: { type: "string" } },
},
User: {
type: "object",
required: ["id", "name"],
properties: { id: { type: "integer" }, name: { type: "string" } },
},
},
},
};
function refsIn(node, found = []) {
if (Array.isArray(node)) node.forEach((item) => refsIn(item, found));
else if (node && typeof node === "object") {
if (typeof node.$ref === "string") found.push(node.$ref);
Object.values(node).forEach((value) => refsIn(value, found));
}
return found;
}
function validateSpec(doc) {
const problems = [];
if (!String(doc.openapi).startsWith("3.")) problems.push("openapi must be 3.x");
const info = doc.info ?? {};
if (!info.title || !info.version) problems.push("info needs title and version");
const seen = new Set();
for (const [path, item] of Object.entries(doc.paths ?? {})) {
for (const [method, op] of Object.entries(item)) {
const where = method.toUpperCase() + " " + path;
if (!op.operationId) problems.push(where + ": missing operationId");
else if (seen.has(op.operationId)) problems.push(where + ": duplicate operationId");
seen.add(op.operationId);
const responses = Object.keys(op.responses ?? {});
if (responses.length === 0) problems.push(where + ": no responses");
const params = op.parameters ?? [];
const declared = params.filter((p) => p.in === "path").map((p) => p.name);
for (const [, name] of path.matchAll(/\{(\w+)\}/g)) {
if (!declared.includes(name)) {
problems.push(where + ": path parameter {" + name + "} is not declared");
}
}
}
}
for (const target of refsIn(doc)) {
const name = target.replace("#/components/schemas/", "");
if (!doc.components?.schemas?.[name]) problems.push("unresolved $ref: " + name);
}
return problems;
}
const users = [
{ id: 1, name: "Aye Chan" },
{ id: 2, name: "Hnin Su" },
{ id: 3, name: "Kyaw Zin" },
];
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
const send = (status, data) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(data));
};
if (url.pathname === "/openapi.json") return send(200, spec);
if (url.pathname === "/users" && req.method === "GET") {
const limit = Number(url.searchParams.get("limit") ?? users.length);
return send(200, users.slice(0, limit));
}
if (url.pathname === "/users" && req.method === "POST") {
let raw = "";
for await (const chunk of req) raw += chunk;
const body = JSON.parse(raw || "{}");
if (typeof body.name !== "string") return send(422, { error: "name is required" });
users.push({ id: users.length + 1, name: body.name });
return send(201, users.at(-1));
}
const one = url.pathname.match(/^\/users\/(\d+)$/);
if (one) {
const user = users.find((u) => u.id === Number(one[1]));
return user ? send(200, user) : send(404, { error: "not found" });
}
send(404, { error: "no such route" });
});
function buildClient(doc, baseUrl) {
const client = {};
for (const [path, item] of Object.entries(doc.paths)) {
for (const [method, op] of Object.entries(item)) {
client[op.operationId] = async ({ body, ...args } = {}) => {
const fill = (_, name) => encodeURIComponent(args[name]);
const route = path.replace(/\{(\w+)\}/g, fill);
const query = new URLSearchParams();
for (const p of op.parameters ?? []) {
const value = args[p.name];
if (p.in === "query" && value !== undefined) query.set(p.name, value);
}
const init = { method: method.toUpperCase() };
if (body) {
init.headers = { "Content-Type": "application/json" };
init.body = JSON.stringify(body);
}
const qs = query.toString();
const res = await fetch(baseUrl + route + (qs ? "?" + qs : ""), init);
return { status: res.status, data: await res.json() };
};
}
}
return client;
}
await new Promise((resolve) => server.listen(0, resolve));
const base = "http://127.0.0.1:" + server.address().port;
const doc = await (await fetch(base + "/openapi.json")).json();
const problems = validateSpec(doc);
console.log("spec problems:", problems.length ? problems.join("; ") : "none");
const client = buildClient(doc, base);
console.log("generated:", Object.keys(client).join(", "));
const show = (label, r) => {
console.log(label + " -> " + r.status + " " + JSON.stringify(r.data));
};
show("listUsers({ limit: 2 })", await client.listUsers({ limit: 2 }));
show("getUser({ id: 2 })", await client.getUser({ id: 2 }));
show("getUser({ id: 99 })", await client.getUser({ id: 99 }));
show("createUser(Mya)", await client.createUser({ body: { name: "Mya" } }));
show("createUser({})", await client.createUser({ body: {} }));
const broken = structuredClone(doc);
delete broken.paths["/users/{id}"].get.parameters;
const listOk = broken.paths["/users"].get.responses[200].content["application/json"];
listOk.schema = { $ref: "#/components/schemas/Customer" };
console.log("broken copy:");
validateSpec(broken).forEach((problem) => console.log(" - " + problem));
server.close();Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Reusable schemas
const ref = (name) => ({ $ref: "#/components/schemas/" + name });User schema ကို operation တိုင်းမှာ ပြန်ရေးမယ့်အစား components ထဲ တစ်ခါပဲ ရေးပြီး $ref နဲ့ ညွှန်းပါတယ်။ User ပြောင်းရင် တစ်နေရာတည်း ပြင်ရုံပါပဲ။
- operationId
operationId: "listUsers",Operation တစ်ခုချင်းစီရဲ့ မထပ်တဲ့ နာမည်ပါ။ Client generator တွေက ဒီနာမည်ကို function နာမည်အဖြစ် သုံးလို့ client.listUsers() ဆိုပြီး ပေါ်လာပါတယ်၊ မရှိရင် /users get လို အရုပ်ဆိုးတဲ့ နာမည်တွေ ထွက်ပါမယ်။
- Serve and consume
const doc = await (await fetch(base + "/openapi.json")).json();Spec ကို ပုံမှန် JSON endpoint တစ်ခုအဖြစ် ပေးထားလို့ docs UI၊ client generator နဲ့ test tool တွေက URL တစ်ခုတည်းကနေ ဖတ်နိုင်ပါတယ်။
- Check path parameters
for (const [, name] of path.matchAll(/\{(\w+)\}/g)) {Path ထဲက {id} တစ်ခုချင်းစီကို ရှာပြီး parameters ထဲမှာ in: path အဖြစ် ကြေညာထားလားစစ်ပါတယ်။ ကြေညာမထားရင် generator တွေ ဘာတန်ဖိုး ထည့်ရမလဲ မသိတော့ပါဘူး။
- Fill the path
const fill = (_, name) => encodeURIComponent(args[name]);/users/{id} ထဲက {id} ကို client.getUser({ id: 2 }) ထဲက တန်ဖိုးနဲ့ အစားထိုးပါတယ်။ encodeURIComponent က / ? လို အက္ခရာတွေကို path ကို မချိုးအောင် ကာကွယ်ပေးပါတယ်။
- One function per operation
client[op.operationId] = async ({ body, ...args } = {}) => {Operation တစ်ခုစီအတွက် async function တစ်ခု ထုတ်ပါတယ်။ body ကို သီးခြားယူပြီး ကျန်တဲ့ argument တွေကို path နဲ့ query parameter အဖြစ် သုံးပါတယ်။ Spec ပြောင်းရင် client လည်း အလိုလို ပြောင်းပါတယ်။
spec problems: none
generated: listUsers, createUser, getUser
listUsers({ limit: 2 }) -> 200 [{"id":1,"name":"Aye Chan"},{"id":2,"name":"Hnin Su"}]
getUser({ id: 2 }) -> 200 {"id":2,"name":"Hnin Su"}
getUser({ id: 99 }) -> 404 {"error":"not found"}
createUser(Mya) -> 201 {"id":4,"name":"Mya"}
createUser({}) -> 422 {"error":"name is required"}
broken copy:
- GET /users/{id}: path parameter {id} is not declared
- unresolved $ref: Customerအပြည့်အစုံ ပိုပြည့်တဲ့ YAML spec
အပေါ်က JSON က အတိုချုပ်ပါ။ တကယ့် spec မှာတော့ servers, authentication, example နဲ့ error response တွေလည်း ပါပါတယ်။ အောက်က YAML က အဲဒီ API ကိုပဲ bearer token နဲ့ rate-limit သင်ခန်းစာက 429 response ပါအောင် ပိုပြည့်စုံစွာ ဖော်ပြထားတာပါ၊ operation တစ်ခုစီမှာ ဘာတွေ ပါလဲ အနီးကပ် ကြည့်ပါ။
openapi: 3.1.0
info:
title: Users API
version: 1.2.0
servers:
- url: https://api.example.com/v1
security:
- bearerAuth: []
paths:
/users:
get:
operationId: listUsers
summary: List users
parameters:
- name: limit
in: query
required: false
schema:
type: integer
minimum: 1
maximum: 100
default: 20
responses:
"200":
description: A page of users
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/User"
example:
- id: 1
name: Aye Chan
"429":
description: Rate limit exceeded
headers:
Retry-After:
description: Seconds to wait before retrying
schema:
type: integer
/users/{id}:
get:
operationId: getUser
summary: Get one user
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
"200":
description: The user
content:
application/json:
schema:
$ref: "#/components/schemas/User"
"404":
description: No user with that id
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
schemas:
User:
type: object
required: [id, name]
properties:
id:
type: integer
name:
type: stringဒီထဲက အရေးကြီးတဲ့ အချက်တွေကို သတိထားပါ။ Status code တွေကို "200" လို quote ထဲ ရေးရတယ် (YAML key က string ဖြစ်ရလို့)။ security က document တစ်ခုလုံးအတွက် bearer token လိုတယ်လို့ ပြောပြီး operation တစ်ခုချင်းစီမှာလည်း override လုပ်လို့ရတယ်။ 429 response ရဲ့ headers ထဲမှာ Retry-After ကို ဖော်ပြထားလို့ client developer တွေက retry ကို မှန်မှန်ရေးလို့ရတယ်။
Spec ကို မှန်အောင် ထိန်းခြင်း: contract test
Contract test ဆိုတာ တကယ့် response (ဒါမှမဟုတ် စမ်းသပ်တဲ့ server ရဲ့ response) ကို spec ထဲက schema နဲ့ နှိုင်းယှဉ်စစ်တာပါ။ ပြဿနာကဲ့သို့ id က string ဖြစ်သွားရင် ဒီစစ်ဆေးမှုက CI မှာ ကျပြီး ဘယ် field မှာ ဘာမကိုက်လဲ ပြောပြပါမယ်။ အောက်က check() က type, required နဲ့ array item တွေကို စစ်တဲ့ ရိုးရှင်းတဲ့ validator ပါ၊ တကယ့် project မှာတော့ ajv လို JSON Schema library တစ်ခုကို သုံးပါ။
const schemas = {
User: {
type: "object",
required: ["id", "name"],
properties: { id: { type: "integer" }, name: { type: "string" } },
},
};
function typeOf(value) {
if (Array.isArray(value)) return "array";
if (value === null) return "null";
if (Number.isInteger(value)) return "integer";
return typeof value;
}
function check(schema, value, path = "$") {
if (schema.$ref) return check(schemas[schema.$ref.split("/").pop()], value, path);
const actual = typeOf(value);
const numberOk = schema.type === "number" && actual === "integer";
if (actual !== schema.type && !numberOk) {
return [path + ": expected " + schema.type + ", got " + actual];
}
const errors = [];
if (schema.type === "object") {
for (const key of schema.required ?? []) {
if (!(key in value)) errors.push(path + "." + key + ": required but missing");
}
for (const [key, sub] of Object.entries(schema.properties ?? {})) {
if (key in value) errors.push(...check(sub, value[key], path + "." + key));
}
}
if (schema.type === "array") {
value.forEach((item, i) => {
errors.push(...check(schema.items, item, path + "[" + i + "]"));
});
}
return errors;
}
function report(label, errors) {
const summary = errors.length ? errors.length + " problem(s)" : "matches the spec";
console.log(label + ": " + summary);
errors.forEach((error) => console.log(" - " + error));
}
const listUsers = { type: "array", items: { $ref: "#/components/schemas/User" } };
report("yesterday's response", check(listUsers, [{ id: 1, name: "Aye Chan" }]));
report("today's response", check(listUsers, [{ id: "2", name: "Hnin Su" }, { id: 3 }]));yesterday's response: matches the spec
today's response: 2 problem(s)
- $[0].id: expected integer, got string
- $[1].name: required but missing- Lint: spec ကို Spectral လို linter နဲ့ စစ်ပါ — description မပါတာ၊ operationId မထပ်တာ၊ error response မပါတာမျိုး။
- Contract test: တကယ့် response တွေကို schema နဲ့ စစ်ပါ၊ ဒီအပိုင်းက docs ကို မှန်အောင် ထိန်းတဲ့ အဓိက ကာကွယ်မှုပါ။
- Breaking-change diff: ပြီးခဲ့တဲ့ release ရဲ့ spec နဲ့ နှိုင်းယှဉ်ပြီး field ဖယ်တာ၊ type ပြောင်းတာကို PR မှာ ဖမ်းပါ။
ကောင်းတဲ့ API docs မှာ ဘာတွေ ပါသင့်လဲ
| အပိုင်း | ဖြေပေးရမယ့် မေးခွန်း |
|---|---|
| Reference (spec ကနေ ထုတ်) | Endpoint တစ်ခုချင်းစီ ဘာလက်ခံ၊ ဘာပြန်လဲ |
| Guides | Authentication၊ pagination၊ rate limit၊ retry ကို ဘယ်လို လုပ်မလဲ |
| Examples | Copy လုပ်ပြီး အလုပ်လုပ်တဲ့ request နဲ့ response ဘာလဲ |
| Error catalogue | Error တစ်ခုချင်းစီ ဘာကြောင့် ဖြစ်ပြီး ဘယ်လို ပြင်မလဲ |
| Changelog | ဘာတွေ ပြောင်းသွားပြီး breaking ဟုတ်မဟုတ် |
Example က ကောင်းမွန်တဲ့ docs ရဲ့ အသက်ပါ။ အောက်က curl example က တန်ဖိုးအစစ်မပါဘဲ ($API_TOKEN ကို ကိုယ့် environment variable က ယူတာ) ကူးပြီး အလုပ်လုပ်ပါတယ်။ Production log ကနေ ကူးလာတဲ့ တကယ့် email၊ token၊ ID တွေကို example ထဲ ဘယ်တော့မှ မထည့်ပါနဲ့။
curl -s "https://api.example.com/v1/users?limit=2" \
-H "Authorization: Bearer $API_TOKEN"Error docs မှာ status code အားလုံးအတွက် တူညီတဲ့ body ပုံစံ တစ်ခု သတ်မှတ်ပါ။ RFC 9457 (Problem Details) က application/problem+json နဲ့ type, title, status, detail, instance field တွေကို ပေးထားလို့ ဒါကို အခြေခံလို့ရပါတယ်။ ပြီးတော့ changelog ကို ရက်စွဲပါ entry တွေနဲ့ ထားပြီး breaking ဖြစ်မဖြစ် ထင်ရှားစွာ မှတ်ပါ။
{
"type": "https://api.example.com/errors/validation",
"title": "Validation failed",
"status": 422,
"detail": "name is required",
"instance": "/v1/users"
}2026-11-10 Added limit query parameter on GET /users (default 20, max 100)
2026-11-10 Added Retry-After header on every 429 response
2026-10-01 Deprecated GET /v1/users; use /v2/users (sunset 2027-01-15)
2026-10-01 Breaking v2 splits users.name into firstName and lastNameSwagger UI နဲ့ တခြား tool များ
| Tool အမျိုးအစား | ဥပမာ | အလုပ် |
|---|---|---|
| Docs viewer | Swagger UI, Redoc | Spec ကို စာမျက်နှာအဖြစ် ပြ |
| Linter | Spectral | စည်းမျဉ်းတွေနဲ့ spec ကို စစ် |
| Code generator | openapi-generator | Client နဲ့ server stub ထုတ် |
| Mock server | Prism | Backend မပြီးခင် spec ကနေ အတု response ပေး |
| Diff tool | oasdiff | Spec နှစ်ခုကြား breaking change ကို ရှာ |
"Try it out" ကို သတိထားပါ
Swagger UI ရဲ့ Try it out ခလုတ်က browser ထဲကနေ တကယ့် request ပို့တာမို့ မတူတဲ့ origin က API ကို ခေါ်ရင် CORS စည်းမျဉ်းတွေ သက်ရောက်ပါတယ် — API ဘက်မှာ docs site ရဲ့ origin ကို ခွင့်ပြုထားရပါမယ်။ ပြီးတော့ အဲဒီမှာ ရိုက်ထည့်တဲ့ တကယ့် token တွေက browser ထဲမှာ ကျန်နိုင်လို့ production key အစား sandbox key နဲ့ အတု data ကိုပဲ သုံးခိုင်းပါ။ ဒီ tool အမည်တွေက ပြောင်းလဲနိုင်တာမို့ လက်ရှိ documentation ကို စစ်ပါ။
လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
အတော်များများသော team တွေက pull request တိုင်းမှာ CI pipeline ကို run ပါတယ် — spec ကို lint လုပ်၊ ပြီးခဲ့တဲ့ release နဲ့ breaking-change diff လုပ်၊ test server ကို contract test လုပ်ပါတယ်။ Frontend team က Prism လို mock server နဲ့ spec ကနေ အတု API ကို ဖွင့်ပြီး backend မပြီးခင် စလုပ်နိုင်ပါတယ်၊ TypeScript client ကိုလည်း generator နဲ့ ထုတ်ယူပါတယ်။ Docs site ကို Redoc ဒါမှမဟုတ် Swagger UI နဲ့ release တိုင်းမှာ အလိုအလျောက် publish လုပ်ပါတယ်။
ဒီသင်ခန်းစာအရင် နှစ်ခုနဲ့ ဆက်စပ်ပုံကိုလည်း မမေ့ပါနဲ့။ Rate limit policy နဲ့ 429 response ရဲ့ Retry-After ကို spec ထဲ ဖော်ပြပါ၊ version တစ်ခုစီအတွက် document တစ်ခုစီ ထားပါ၊ docs site ရဲ့ "Try it out" အတွက် CORS ကို ကြိုပြင်ဆင်ပါ။ Spec ထဲမှာ ဖော်ပြတာတွေ မလုံလောက်တဲ့ စည်းမျဉ်းတွေ (retry ဘယ်လိုလုပ်၊ idempotency key ဘယ်လို သုံး) ကိုတော့ guides စာမျက်နှာတွေမှာ ရှင်းပြပါ။ ဒီနည်းနဲ့ docs က API ရဲ့ တကယ့် contract ဖြစ်လာပါလိမ့်မယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. Success response တစ်ခုတည်းကိုပဲ ရေးတာ
"200: OK" တစ်ခုတည်း ရေးထားရင် client developer က 401, 404, 422, 429 တွေကို ဘယ်လိုကိုင်ရမလဲ မသိဘဲ ခန့်မှန်းရပါတယ်။ အဲဒီ status တွေနဲ့ error body ရဲ့ ပုံစံကိုပါ ဖော်ပြပါ။
2. Spec ကို code နဲ့ သီးခြား လက်နဲ့ ထိန်းတာ
CI မှာ စစ်ဆေးမှု မရှိရင် spec က code နောက်ကျကျန်ရစ်ပြီး ပြဿနာအတိုင်း drift ဖြစ်ပါတယ်။ Spec ကို code ကနေ ထုတ်ယူပါ ဒါမှမဟုတ် contract test နဲ့ အနည်းဆုံး တိုက်စစ်ပါ။
3. Example ထဲ အစစ်အမှန် data ထည့်တာ
Production log ကနေ ကူးလာတဲ့ email, token, ID တွေက docs မှာ ထာဝရ ပွင့်လင်းသွားပါတယ်။ example.com၊ အတု token၊ ကျပန်းနာမည်တွေကိုပဲ သုံးပါ။
4. operationId မရှိ/ထပ်နေတာနဲ့ description မဖြည့်တာ
operationId ပျက်ကွက်ရင် generator တွေက နာမည်တွေကို path ကနေ ဖန်တီးလို့ client function နာမည်တွေ ရှုပ်ပါတယ်၊ ထပ်နေရင် တစ်ခုကို တစ်ခုက ဖုံးသွားပါတယ်။ "OK" ဆိုတဲ့ description တွေကလည်း ဘာမှ မပြောပြနိုင်ပါဘူး။
Best Practices
အကောင်းဆုံး အလေ့အကျင့်များ
- Endpoint တိုင်းမှာ example တစ်ခုနဲ့ error response တစ်ခုအနည်းဆုံး ထည့်ပါ၊ ပြီးတော့ error body ပုံစံကို တစ်ခုတည်းထားပါ။
- Changelog ကို ရက်စွဲပါ entry တွေနဲ့ ထားပြီး additive နဲ့ breaking ကို ခွဲပြပါ၊ deprecation ရက်တွေကိုလည်း ဒီမှာ ထည့်ပါ။
- Spec ကို docs viewer တစ်ခုနဲ့ ကြည့်ရုံနဲ့ မလုံလောက်ပါဘူး၊ lint နဲ့ contract test ကို CI ရဲ့ ပိတ်ဆို့ချက် (blocking check) အဖြစ် ထားပါ။
Mini challenge
Mini challenge: spec ကနေ reference docs ထုတ်ခြင်း
Tasks API အတွက် OpenAPI-ပုံစံ object တစ်ခု ကိုယ်တိုင်ရေးပြီး describeOperations(spec) function ကို ရေးပါ။ Operation တစ်ခုစီအတွက် method, path, operationId, input တွေ (query/path parameter နဲ့ body) နဲ့ response status code တွေကို တစ်ကြောင်းစီ စာပြင်ထားတဲ့ docs table အဖြစ် print လုပ်ပါ။ client မဟုတ်ဘဲ docs ကို spec ကနေ ထုတ်တာပါ။
- spec ထဲမှာ operation သုံးခု ထည့်ပါ: GET /tasks (listTasks)၊ POST /tasks (createTask)၊ DELETE /tasks/{id} (deleteTask)
- listTasks မှာ query parameter status နဲ့ limit၊ createTask မှာ requestBody၊ deleteTask မှာ path parameter id ရှိရမယ်
- response code တွေက listTasks: 200, 401၊ createTask: 201, 422၊ deleteTask: 204, 404
- ရလဒ်ကို in: query:status, query:limit ဆိုတဲ့ ပုံစံနဲ့ ဖော်ပြပြီး body ပါရင် body လို့ ပြပါ၊ input မရှိရင် - ပြပါ
- ကော်လံတွေကို padEnd နဲ့ တန်းစီပြီး print လုပ်ပါ
// TODO: define const doc = { paths: { ... } } for the Tasks API described above
function describeOperations(spec) {
const lines = [];
// TODO: loop over spec.paths, then over each path item's methods
// TODO: inputs = each parameter as "<in>:<name>", plus "body" when requestBody exists
// TODO: build one line: METHOD, path, operationId, "in: ...", "out: <status codes>"
// TODO: pad the first columns with padEnd so the lines align
return lines;
}
// TODO: print every line returned by describeOperations(doc)ရလဒ်: သုံးကြောင်း print ထွက်ရပါမယ်: GET /tasks listTasks in: query:status, query:limit out: 200, 401 POST /tasks createTask in: body out: 201, 422 DELETE /tasks/{id} deleteTask in: path:id out: 204, 404
အရိပ်အမြွက် ကြည့်ရန်
Object.entries(spec.paths) နဲ့ path တစ်ခုချင်းကို ယူပြီး အထဲက method တွေကို ထပ်ပတ်ပါ။ response code တွေက Object.keys(op.responses) ကနေ ရပါတယ်။ ကော်လံ အကျယ်ကို 7, 13, 12 နဲ့ ပထမဆုံး စမ်းပြီး လိုသလို ညှိပါ။
အဖြေ ကြည့်ရန်
const doc = {
paths: {
"/tasks": {
get: {
operationId: "listTasks",
parameters: [
{ name: "status", in: "query" },
{ name: "limit", in: "query" },
],
responses: { 200: {}, 401: {} },
},
post: {
operationId: "createTask",
requestBody: { required: true },
responses: { 201: {}, 422: {} },
},
},
"/tasks/{id}": {
delete: {
operationId: "deleteTask",
parameters: [{ name: "id", in: "path", required: true }],
responses: { 204: {}, 404: {} },
},
},
},
};
function describeOperations(spec) {
const lines = [];
for (const [path, item] of Object.entries(spec.paths)) {
for (const [method, op] of Object.entries(item)) {
const inputs = (op.parameters ?? []).map((p) => p.in + ":" + p.name);
if (op.requestBody) inputs.push("body");
lines.push(
method.toUpperCase().padEnd(7) +
path.padEnd(13) +
op.operationId.padEnd(12) +
("in: " + (inputs.join(", ") || "-")).padEnd(32) +
"out: " + Object.keys(op.responses).join(", "),
);
}
}
return lines;
}
describeOperations(doc).forEach((line) => console.log(line));Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- OpenAPI က API ကို YAML ဒါမှမဟုတ် JSON နဲ့ machine-readable contract အဖြစ် ဖော်ပြပြီး paths, operationId, responses, components နဲ့ $ref တို့နဲ့ ဖွဲ့စည်းထားပါတယ်။
- Spec ကို data အဖြစ် ဖတ်လို့ရလို့ docs၊ client၊ mock server နဲ့ validation တွေကို tool တွေက ထုတ်ပေးနိုင်ပါတယ်။
- Swagger UI ကောင်းကောင်း render ဖြစ်တာက spec မှန်တာကို မသက်သေပြပါဘူး၊ CI မှာ lint၊ contract test နဲ့ breaking-change diff တို့ လိုပါတယ်။
- ကောင်းတဲ့ docs မှာ reference တစ်ခုတည်း မဟုတ်ဘဲ guide၊ example၊ error catalogue နဲ့ changelog ပါပါတယ်၊ example တွေမှာ secret မပါစေနဲ့။
OpenAPI Specification — OpenAPI Initiative