ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
REST API ကို စာကြည့်တိုက် ကောင်တာတစ်ခုလို စဉ်းစားကြည့်ပါ။ စာအုပ်စင်တွေမှာ နာမည်တပ်ထားပါတယ် ("users" စင်၊ "books" စင်)။ စင်တစ်ခုလုံးကို ကြည့်ချင်ရင် /api/users၊ စာအုပ်တစ်အုပ်တည်းကို လိုချင်ရင် /api/users/2 လို့ ပြောရုံပါပဲ။ URL က "ဘာကို" လဲဆိုတာ ပြောပြီး HTTP method (GET၊ POST၊ DELETE...) က "ဘာလုပ်မလဲ" ဆိုတာ ပြောပါတယ်။
ကောင်တာက ပြန်ဖြေတဲ့အခါ အမြဲ အပိုင်းနှစ်ပိုင်း ပါပါတယ်။ ပထမက status code ဆိုတဲ့ အတိုချုပ်အဖြေ (200 ရပါတယ်၊ 404 မရှိပါဘူး) ဖြစ်ပြီး ဒုတိယက အသေးစိတ်ပါတဲ့ JSON body ပါ။ Browser၊ mobile app၊ admin dashboard အားလုံးက ဒီစည်းကမ်းတစ်ခုတည်းကို သိထားရင် server ကို ဘယ်လိုမေးရမလဲ ထပ်မေးစရာ မလိုတော့ပါဘူး။
Problem → Why → Solution
ပြဿနာ: ကိုယ့်စိတ်ကြိုက် endpoint တွေ
Team တစ်ခုက feature တစ်ခုလိုတိုင်း endpoint အသစ်တစ်ခု ထပ်ထည့်သွားတယ်ဆိုပါစို့။ /getUsers၊ /createUser၊ /deleteUser?id=2 စသဖြင့် URL ထဲမှာ verb တွေ ပါလာပြီး delete ကိုတောင် GET နဲ့ ခေါ်နေပါတယ်။ User မရှိတဲ့အခါလည်း status 200 ကိုပဲ ပြန်ပြီး body ထဲမှာ { success: false } လို့ ရေးထားပါတယ်။ Endpoint တစ်ခုက error ကို message လို့ ခေါ်ပြီး နောက်တစ်ခုက err လို့ ခေါ်ပါတယ်။
Frontend developer က endpoint တစ်ခုချင်းစီအတွက် parsing code သီးသန့် ရေးရပါတော့တယ်။ ပိုဆိုးတာက link preview ပြတဲ့ bot တစ်ခုက GET link တွေကို လိုက်ဖွင့်ကြည့်တဲ့အခါ /deleteUser?id=2 ကိုပါ ဖွင့်မိပြီး user ပျက်သွားနိုင်ပါတယ်။
app.get('/getUsers', (req, res) => res.json(users));
app.get('/deleteUser', (req, res) => { // GET that changes data
const i = users.findIndex((u) => u.id === Number(req.query.id));
if (i === -1) return res.json({ success: false, err: 'nope' }); // 200!
users.splice(i, 1);
res.json({ success: true });
});
app.post('/createUser', (req, res) => {
if (!req.body.name) return res.json({ message: 'name?' }); // 200 again
// ...
});ဘာကြောင့် ဒါက ပြဿနာလဲ
HTTP မှာ method နဲ့ status code တွေရဲ့ အဓိပ္ပာယ်ကို standard (RFC 9110) က သတ်မှတ်ထားပြီး browser၊ cache၊ proxy၊ retry library တွေက အဲဒါကို အားကိုးပါတယ်။ GET က data မပြောင်းရဘူးလို့ ယူဆလို့ အလိုလို ပြန်ခေါ်တာ၊ prefetch လုပ်တာ ရှိပါတယ်။ fetch ရဲ့ res.ok က status ကိုပဲ ကြည့်လို့ 200 ပြန်တဲ့ error ကို အောင်မြင်တယ်လို့ ထင်ပါတယ်။
Core concept: REST contract ရဲ့ အစိတ်အပိုင်း လေးခု
REST API ဆိုတာ library တစ်ခု မဟုတ်ပါဘူး။ Server နဲ့ client ကြား သဘောတူထားတဲ့ စည်းကမ်းစုတစ်ခု (contract) ပါ။ Code တစ်ကြောင်းမှ မရေးခင် ဒီ contract ကို အရင် ချရေးထားရင် frontend နဲ့ backend က တစ်ပြိုင်နက် အလုပ်လုပ်နိုင်ပါတယ်။ Contract မှာ ဆုံးဖြတ်ရမယ့် အပိုင်း လေးခု ရှိပါတယ်။
၁။ Resource ကို noun URL နဲ့ နာမည်ပေးပါ
/api/users က collection (user အားလုံး) ဖြစ်ပြီး /api/users/2 က အဲဒီ collection ထဲက item တစ်ခုပါ။ URL ထဲမှာ get၊ create၊ delete လို verb မထည့်ပါဘူး၊ action ကို method က ပြောပြီးသားမို့ပါ။ Plural noun ကို သုံးပါ။
၂။ Action ကို method နဲ့ ရွေးပါ
GET က ဖတ်ရုံသာ ဖြစ်ပြီး data မပြောင်းရပါဘူး (safe)။ POST က collection ထဲ item အသစ် ဖန်တီးပါတယ်။ PATCH က field တချို့ကို ပြင်ပြီး PUT က item တစ်ခုလုံးကို အစားထိုးပါတယ်။ DELETE က ဖယ်ရှားပါတယ်။ GET၊ PUT၊ DELETE တွေက idempotent ပါ၊ ဆိုလိုတာက တစ်ကြိမ်ခေါ်တာနဲ့ အကြိမ်ကြိမ်ခေါ်တာ server state အတူတူပဲ ကျန်ပါတယ်။
၃။ ရလဒ်ကို status code နဲ့ ပြောပါ
2xx က အောင်မြင်တာ၊ 4xx က client ဘက်က အမှား (data မှား၊ မရှိ)၊ 5xx က server ဘက်က အမှား ဖြစ်ပါတယ်။ Client က body ကို မဖတ်ရသေးခင် status ကြည့်ရုံနဲ့ ဘာဖြစ်လဲ သိရပါမယ်။
၄။ Body shape ကို တစ်မျိုးတည်း ထားပါ
ဒီ course မှာ အောင်မြင်ရင် { data: ... } (list ဆိုရင် count ပါ ထပ်ပါ)၊ မအောင်မြင်ရင် { error: "..." } ဆိုတဲ့ shape တစ်မျိုးတည်းကို endpoint တိုင်းမှာ သုံးပါမယ်။
| Request | အဓိပ္ပာယ် | Success status |
|---|---|---|
| GET /api/users | User အားလုံးကို list လုပ် | 200 OK |
| GET /api/users/:id | User တစ်ယောက်ကို ဖတ် | 200 OK (မရှိရင် 404) |
| POST /api/users | User အသစ် ဖန်တီး | 201 Created (data မှားရင် 400) |
| PATCH /api/users/:id | Field တချို့ ပြင် | 200 OK |
| DELETE /api/users/:id | User ကို ဖယ်ရှား | 204 No Content |
ဒီ table က နောက် lesson တွေရဲ့ မြေပုံပါ။ Lesson 23 မှာ GET list၊ Lesson 24 မှာ GET တစ်ခု၊ Lesson 25 မှာ POST ကို ရေးပြီး mini project မှာ PATCH နဲ့ DELETE ပါ ပေါင်းထည့်ပါမယ်။ User တစ်ယောက်မှာ id၊ name၊ role ဆိုတဲ့ field သုံးခုပဲ ရှိပါမယ်။
- URL က resource (noun) ကို ညွှန်း
- Method က action (verb) ကို ပြော
- Status code က ရလဒ်ကို အတိုချုပ်ပြော
- JSON body က အသေးစိတ်ကို ပေး
Endpoint အသစ်တစ်ခု ထည့်ချင်ရင် "ဒါက ဘယ် resource လဲ၊ ဘယ် method လဲ" ကို အရင်မေးပါ။ URL အသစ် တီထွင်ဖို့ မလိုတာ များပါတယ်။
အခြေခံ ပုံစံ
const app = express();
app.use(express.json()); // read JSON request bodies
app.get('/api/things', listHandler); // collection
app.post('/api/things', createHandler);
app.get('/api/things/:id', readOneHandler); // one item
app.delete('/api/things/:id', removeHandler);
app.use((req, res) => res.status(404).json({ error: 'message' }));
app.listen(port);Resource တစ်ခုကို URL နှစ်မျိုး (collection နဲ့ /:id) ပေါ်မှာ method အလိုက် handler ချိတ်ပါတယ်။ အောက်ဆုံးက fallback က ဘယ် route နဲ့မှ မကိုက်တဲ့ request ကို JSON error နဲ့ ဖြေပါတယ်။
Users API ရဲ့ အခြေခံ app
ဒီ app မှာ user data သုံးယောက်ကို memory ထဲမှာ ထားပြီး /api/health ဆိုတဲ့ route တစ်ခုပဲ ရှိပါသေးတယ်။ ကျန်တဲ့ request အားလုံးကို JSON 404 နဲ့ ဖြေပါတယ်။ app.listen(0) က OS ကို အလွတ်ဖြစ်နေတဲ့ port တစ်ခု ရွေးခိုင်းတာမို့ ဘယ်စက်မှာ run run port တိုက်မှာ မဟုတ်ပါဘူး။ Server စတက်ပြီးတာနဲ့ fetch နဲ့ request သုံးခု ပို့ပြီး server ကို ပြန်ပိတ်ပါတယ်။
const express = require('express');
const app = express();
app.use(express.json());
// The one resource this API manages (in memory until a database arrives)
const users = [
{ id: 1, name: 'Aung Aung', role: 'admin' },
{ id: 2, name: 'Mya Mya', role: 'member' },
{ id: 3, name: 'Zaw Zaw', role: 'member' },
];
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', users: users.length });
});
// Every route we have not built yet answers with the same JSON error shape
app.use((req, res) => {
res.status(404).json({ error: `Cannot ${req.method} ${req.path}` });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const calls = [
['GET', '/api/health'],
['GET', '/api/users'],
['DELETE', '/api/users/1'],
];
for (const [method, path] of calls) {
const res = await fetch(base + path, { method });
const type = res.headers.get('content-type');
console.log(`${method} ${path} -> ${res.status} (${type})`);
console.log(` body: ${JSON.stringify(await res.json())}`);
}
server.close();
});Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- JSON body parser
app.use(express.json());Content-Type: application/json ပါတဲ့ request body ကို parse လုပ်ပြီး req.body ထဲ ထည့်ပေးပါတယ်။ ဒီ lesson မှာ မသုံးရသေးပေမယ့် Lesson 25 ရဲ့ POST route အတွက် ကြိုထည့်ထားတာပါ။
- The resource
{ id: 1, name: 'Aung Aung', role: 'admin' },User တိုင်းမှာ id၊ name၊ role ပါပါတယ်။ Array က memory ထဲမှာပဲ ရှိလို့ server restart လုပ်တိုင်း မူလ user သုံးယောက်ဆီ ပြန်ရောက်ပါတယ်။
- res.json()
res.json({ status: 'ok', users: users.length });Object ကို JSON string ပြောင်းပြီး Content-Type ကို application/json; charset=utf-8 လို့ သတ်မှတ်ပေးပါတယ်။ Status ကို မပြောရင် 200 ပါ။
- JSON fallback
res.status(404).json({ error: `Cannot ${req.method} ${req.path}` });app.use() ကို route တွေအောက်မှာ ထားလို့ ဘယ် route နဲ့မှ မကိုက်မှ ဒီကို ရောက်ပါတယ်။ ဒါမရှိရင် Express က HTML page ပြန်ပြီး JSON မျှော်တဲ့ client က parse error တက်ပါမယ်။
- Port 0
const server = app.listen(0, async () => {Port 0 ဆိုရင် OS က အလွတ် port ကို ရွေးပေးပြီး server.address().port က အဲဒီ number ကို ပြန်ပေးပါတယ်။ Test တွေမှာ အသုံးများတဲ့ နည်းပါ။
- Close when done
server.close();Server ကို ပိတ်လိုက်မှ Node process က ပြီးဆုံးပြီး ထွက်သွားပါတယ်။ မပိတ်ရင် program က request တွေကို ဆက်စောင့်နေပါမယ်။
GET /api/health -> 200 (application/json; charset=utf-8)
body: {"status":"ok","users":3}
GET /api/users -> 404 (application/json; charset=utf-8)
body: {"error":"Cannot GET /api/users"}
DELETE /api/users/1 -> 404 (application/json; charset=utf-8)
body: {"error":"Cannot DELETE /api/users/1"}Safe နဲ့ idempotent ဆိုတာ ဘာကြောင့် အရေးကြီးလဲ
Mobile network မှာ request တစ်ခု ပို့ပြီး response မရောက်ခင် connection ပြတ်သွားတာ ခဏခဏ ဖြစ်ပါတယ်။ Client က "server ဆီ ရောက်ခဲ့လား" မသိပါဘူး။ DELETE /api/users/3 လို idempotent request ဆိုရင် ထပ်ပို့လည်း ရလဒ်အတူတူပဲမို့ စိတ်ချလက်ချ retry လုပ်နိုင်ပါတယ်။ POST /api/users ကိုတော့ ထပ်ပို့ရင် user နှစ်ယောက် ဖြစ်သွားနိုင်ပါတယ်။
ဒါကြောင့် method ကို မှန်မှန်ရွေးတာက ဒီဇိုင်း လှဖို့သက်သက် မဟုတ်ပါဘူး။ Retry ဘယ်အချိန် လုပ်ရမလဲ ဆိုတဲ့ ဆုံးဖြတ်ချက်ကို client library တွေက method ကနေ ယူတာမို့ပါ။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Shop တစ်ခုမှာ customer web site၊ Android app၊ staff သုံးတဲ့ admin panel ဆိုပြီး client သုံးခု ရှိနိုင်ပါတယ်။ သုံးခုလုံးက backend API တစ်ခုတည်းကို ခေါ်ပြီး /api/orders၊ /api/orders/:id ဆိုတဲ့ contract တူတူကို သုံးပါတယ်။ Contract တည်ငြိမ်နေရင် backend team က database ပြောင်းတာ၊ code ပြန်ရေးတာ လုပ်ရင်တောင် client တွေ ပြင်စရာ မလိုပါဘူး။
GitHub ရဲ့ REST API လို public API တွေကလည်း GET /repos/{owner}/{repo}/issues လို nested resource URL တွေနဲ့ ဒီပုံစံကိုပဲ လိုက်နာပါတယ်။ Team အများစုက contract ကို OpenAPI document အဖြစ် ရေးထားပြီး အဲဒီကနေ documentation နဲ့ test တွေ ထုတ်ပါတယ်။ Contract ကို ချိုးဖျက်ရမယ့် ပြောင်းလဲမှု ရှိလာရင် /api/v2 လို version အသစ်တစ်ခု ဖွင့်ပြီး client အဟောင်းတွေကို အချိန်ပေးပါတယ်။ App သုံးခုက အားကိုးပြီးမှ contract ကို ပြောင်းတာထက် အစောပိုင်းမှာ မှန်အောင် ချထားတာက အများကြီး သက်သာပါတယ်။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
Error တွေကို status 200 နဲ့ ပြန်တာ
res.json({ success: false }) လို့ပဲ ရေးလိုက်ရင် status က 200 ဖြစ်နေပါတယ်။ Client ရဲ့ res.ok က true ဖြစ်ပြီး monitoring tool တွေက error rate ကို 0% လို့ ပြပါလိမ့်မယ်။ မရှိရင် 404၊ data မှားရင် 400 ကို res.status() နဲ့ တကယ် သတ်မှတ်ပါ။
Data ပြောင်းတဲ့ action ကို GET နဲ့ ရေးတာ
GET /users/2/delete လို route ကို crawler၊ link preview၊ browser prefetch တွေက ကိုယ့်မသိဘဲ ခေါ်သွားနိုင်ပါတယ်။ Data ပြောင်းတာမှန်သမျှကို POST၊ PATCH၊ PUT၊ DELETE နဲ့ပဲ ရေးပါ။
JSON fallback မထည့်တာ
Fallback မရှိရင် route မရှိတဲ့ request ကို Express က "Cannot GET /api/userz" ဆိုတဲ့ HTML page နဲ့ ဖြေပါတယ်။ Client ရဲ့ await res.json() က SyntaxError တက်ပြီး တကယ့်ပြဿနာ (URL typo) ကို ဖုံးသွားပါတယ်။
Mini challenge
Notes API ရဲ့ contract ကို code နဲ့ ရေးပါ
Notes resource အတွက် logic မရေးခင် contract ကို data အဖြစ် ရေးပါ။ Contract array ကနေ route stub တွေကို loop နဲ့ register လုပ်ပြီး stub တိုင်းက 501 Not Implemented ကို JSON error shape နဲ့ ပြန်ပါစေ။ GET /api က contract တစ်ခုလုံးကို ဖတ်လို့ရတဲ့ list အဖြစ် ပြန်ပေးပါ။
- Contract မှာ GET list၊ GET တစ်ခု၊ POST၊ PATCH၊ DELETE ပါပြီး success status မှန်ရပါမယ်
- app[method.toLowerCase()](path, handler) နဲ့ route တွေကို loop ထဲမှာ register လုပ်ပါ
- Stub တိုင်းက status 501 နဲ့ { error: "..." } ကို ပြန်ပါ
- Contract ထဲမှာ မရှိတဲ့ request (ဥပမာ PUT) ကို JSON 404 နဲ့ ဖြေပါ
const express = require('express');
// TODO: one entry per route: { method, path, success, does }
const contract = [];
const app = express();
app.use(express.json());
// TODO: GET /api -> { data: ['GET /api/notes -> 200', ...] }
// TODO: loop over contract and register a 501 stub for each route
// TODO: JSON 404 fallback
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
// TODO: print GET /api, then try POST /api/notes and PUT /api/notes/7
server.close();
});ရလဒ်: Contract ရဲ့ line ငါးကြောင်း (GET /api/notes -> 200 ... DELETE /api/notes/:id -> 204) ထွက်ပြီး POST က 501၊ PUT က 404 ကို JSON error နဲ့ ပြပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
app.get နဲ့ app['get'] က အတူတူပါပဲ။ ဒါကြောင့် method string ကို lowercase ပြောင်းပြီး app[...] နဲ့ ခေါ်လို့ ရပါတယ်။ Stub handler ထဲမှာ route variable ကို closure အနေနဲ့ သုံးနိုင်ပါတယ်။
အဖြေ ကြည့်ရန်
const express = require('express');
const contract = [
{ method: 'GET', path: '/api/notes', success: 200, does: 'list notes' },
{ method: 'GET', path: '/api/notes/:id', success: 200, does: 'read one note' },
{ method: 'POST', path: '/api/notes', success: 201, does: 'create a note' },
{ method: 'PATCH', path: '/api/notes/:id', success: 200, does: 'change some fields' },
{ method: 'DELETE', path: '/api/notes/:id', success: 204, does: 'remove a note' },
];
const app = express();
app.use(express.json());
app.get('/api', (req, res) => {
res.json({ data: contract.map((r) => `${r.method} ${r.path} -> ${r.success}`) });
});
for (const route of contract) {
app[route.method.toLowerCase()](route.path, (req, res) => {
res.status(501).json({ error: `Not implemented yet: ${route.does}` });
});
}
app.use((req, res) => {
res.status(404).json({ error: `Cannot ${req.method} ${req.path}` });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const index = await (await fetch(`${base}/api`)).json();
index.data.forEach((line) => console.log(line));
for (const [method, path] of [['POST', '/api/notes'], ['PUT', '/api/notes/7']]) {
const res = await fetch(base + path, { method });
console.log(method, path, res.status, JSON.stringify(await res.json()));
}
server.close();
});Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- URL က resource (noun) ကို ညွှန်းပြီး method က action ကို ပြောပါတယ်
- /api/users က collection၊ /api/users/:id က item တစ်ခု ဖြစ်ပါတယ်
- Status code က ရလဒ်ကို ပြောပြီး error ကို 200 နဲ့ ဘယ်တော့မှ မပြန်ပါနဲ့
- Route တွေအောက်က JSON fallback က မရှိတဲ့ route တိုင်းကို error shape တူတူနဲ့ ဖြေပါတယ်
HTTP Semantics (RFC 9110) — RFC Editor