Thuta Learning
API Tutorial
IntermediateWeb Developmentအလယ်အလတ်

Request ဥပမာများ (curl & JS)

API Tutorialသင်ခန်းစာ 1140 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • JSON request ကို JSON.stringify နဲ့ Content-Type: application/json တွဲပြီး fetch နဲ့ ပို့နိုင်ဖို့
  • Object ကို stringify မလုပ်ဘဲ ပို့ရင် server က ဘာမြင်လဲ ပြောပြနိုင်ပြီး error ကို ရှာတွေ့နိုင်ဖို့
  • fetch က 404 နဲ့ 500 မှာ မ throw ဘဲ res.ok ကို စစ်ရတာ၊ AbortSignal.timeout နဲ့ timeout ထည့်တာကို လုပ်နိုင်ဖို့
  • တူညီတဲ့ request ကို curl (-H, -d, --json, -G) နဲ့ shell quoting မှန်အောင် ရေးနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

Request ဥပမာတွေကို ရိုးရိုးလေး ပြောရရင်

API request တစ်ခုက စာတိုက်ထဲ ပို့တဲ့ စာတစ်စောင်လိုပါပဲ။ စာအိတ်ပေါ်မှာ လိပ်စာ (URL) နဲ့ ဘာလုပ်ခိုင်းမလဲ (method) ရေးပြီး စာအိတ်ပေါ်က label တွေ (header) က အထဲက စာကို ဘယ်ဘာသာနဲ့ ရေးထားလဲ ပြောပါတယ်၊ ပြီးတော့ စာအတွင်းပိုင်း (body) ပါပါတယ်။ Server က label ကိုဖတ်ပြီးမှ စာကို ဘယ်လိုဖတ်ရမလဲ ဆုံးဖြတ်ပါတယ်။

curl နဲ့ fetch က အဲဒီ စာကို ရေးတဲ့ နည်းလမ်းနှစ်မျိုးပါ။ curl က terminal ထဲမှာ အမြန်စမ်းဖို့၊ documentation ထဲက ဥပမာတွေ ကူးသုံးဖို့ အသင့်တော်ဆုံးပါ။ fetch က JavaScript code ထဲက ခေါ်ဖို့ပါ။ နှစ်ခုလုံးက တူညီတဲ့ HTTP request ကို ထုတ်ပေးတာမို့ တစ်ခုကို နားလည်ရင် နောက်တစ်ခုကို ဖတ်လို့ရပါတယ်။

Problem → Why → Solution

ပြဿနာ: ပို့တာ မှန်ပုံရပေမဲ့ server က နားမလည်ဘူး

User တစ်ယောက် ဖန်တီးဖို့ fetch call ရေးပြီး body ထဲမှာ object ကို တိုက်ရိုက်ထည့်လိုက်ပါတယ်။ Error မတက်ပါဘူး၊ ဒါပေမဲ့ server က 415 ဒါမှမဟုတ် 400 ပြန်ပြီး server log ထဲမှာ body က [object Object] ဆိုတဲ့ စာသား ဖြစ်နေပါတယ်။ ပြီးရင် res.json() ကို ခေါ်တဲ့အခါ data.id က undefined ဖြစ်တာ၊ ဒါမှမဟုတ် server က HTML error page ပြန်ရင် SyntaxError တက်တာ တွေ့ရပါတယ်။

broken-request.js
// BROKEN: three small mistakes that each look reasonable
const res = await fetch("https://api.example.com/v1/users", {
  method: "POST",
  body: { name: "Alice", email: "alice@example.com" },
});
const data = await res.json();
console.log(data.id); // undefined, or a SyntaxError if the server answered with HTML

Header နဲ့ body ကို client က ကိုယ်တိုင် ပြည့်စုံအောင် လုပ်ရတယ်

fetch က body ကို text ဒါမှမဟုတ် bytes အနေနဲ့ပဲ ပို့နိုင်ပါတယ်။ Object ကို ပေးရင် String(object) လို့ပဲ ပြောင်းလို့ [object Object] ဖြစ်ပါတယ်။ String ပေးရင်လည်း Content-Type ကို text/plain လို့ ထည့်ပေးလိုက်တာမို့ server ကို 'ဒါ JSON ပါ' လို့ ကိုယ်တိုင် ပြောရပါတယ်။ ပြီးတော့ fetch က network ပြတ်မှ reject လုပ်တာမို့ 404 နဲ့ 500 ကို ကိုယ်တိုင် စစ်ရပါတယ်။

Core concept: request ရဲ့ အပိုင်းလေးပိုင်း ကိုက်ညီရမယ်

Request တစ်ခုမှာ method နဲ့ URL (query string ပါ)၊ header၊ body ဆိုပြီး အပိုင်းတွေ ရှိပါတယ်။ Server က အဲဒါတွေကို ပေါင်းပြီး ဘာတောင်းလဲ နားလည်တာမို့ တစ်ခုချင်းစီ မှန်ရုံနဲ့ မလုံလောက်ဘဲ တစ်ခုနဲ့တစ်ခု ကိုက်ညီရပါတယ်။ JSON ပို့မယ်ဆိုရင် body က JSON text ဖြစ်ရမယ်၊ Content-Type က application/json ဖြစ်ရမယ်၊ method က body ထောက်ပံ့တဲ့ POST, PUT ဒါမှမဟုတ် PATCH ဖြစ်သင့်တယ်။ ကိုက်ညီမှုမရှိရင် client ဘက်မှာ error မတက်တတ်ပါဘူး၊ server က 400 ဒါမှမဟုတ် 415 ပြန်တာ၊ ဒါမှမဟုတ် မှားနေတဲ့ data ကို တိတ်တဆိတ် လက်ခံတာမျိုး ဖြစ်တတ်ပါတယ်။

JavaScript မှာ JSON body ကို JSON.stringify(object) နဲ့ text ပြောင်းပါ၊ ပြီးတော့ headers ထဲမှာ Content-Type: application/json ထည့်ပါ။ Server က Content-Type ကို ကြည့်ပြီး ဘယ် parser သုံးမလဲ ရွေးပါတယ်၊ မထည့်ရင် fetch က string body အတွက် text/plain;charset=UTF-8 လို့ ထည့်ပေးပြီး JSON parser မသုံးတော့တာ ဖြစ်ပါတယ်။ Accept header ကတော့ 'JSON ပြန်ပေးပါ' လို့ ပြောတာပါ။ Query string ကိုလည်း string ဆက်ရေးတာထက် URLSearchParams နဲ့ ဆောက်ပါ၊ &, space နဲ့ non-ASCII character တွေကို ကိုယ့်ကိုယ်စား encode လုပ်ပေးပါတယ်။

Response ဘက်မှာ fetch ရဲ့ အကြီးဆုံး အံ့သြစရာက 404 ဒါမှမဟုတ် 500 ရရင်တောင် promise က အောင်မြင်ပြီး Response object ကို ပြန်ပေးတာပါ။ Network ပြတ်တာ၊ DNS မရှာတွေ့တာ၊ abort လုပ်တာမှသာ reject ဖြစ်ပါတယ်။ ဒါကြောင့် res.ok (status 200 ကနေ 299) ကို စစ်ရပါမယ်။ fetch က ကိုယ့်ဘာသာ မြန်မြန် လက်လျှော့ပေးတာလည်း မဟုတ်ပါဘူး၊ timeout ကို AbortSignal.timeout(ms) နဲ့ ကိုယ်တိုင် ထည့်ပါ။ ဒါကြောင့် fetch ကို try/catch နဲ့ ဖုံးရုံနဲ့ မလုံလောက်ပါဘူး။

အပိုင်းfetchcurl
Methodmethod: "POST"-X POST (-d ပါရင် POST အလိုလို)
Headerheaders: { Name: value }-H "Name: value"
JSON bodybody: JSON.stringify(obj)-d '{...}' ဒါမှမဟုတ် --json '{...}'
Query stringnew URLSearchParams({...})-G --data-urlencode "q=..."
Timeoutsignal: AbortSignal.timeout(5000)--max-time 5
Server ဖတ်လို့ရတဲ့ စာတစ်စောင် ရေးခြင်း
  1. Method + URL (query ကို လုံခြုံစွာ ဆောက်)
  2. Header: Content-Type, Accept, auth
  3. Body: JSON.stringify(object)
  4. fetch ဒါမှမဟုတ် curl နဲ့ ပို့
  5. res.ok စစ်ပြီးမှ body ကို parse

Header က body ကို ဘယ်လိုဖတ်ရမလဲ ပြောတာမို့ body နဲ့ ကိုက်ညီမှ server က နားလည်ပါတယ်။

အထွေထွေ ပုံစံ

javascript
const res = await fetch(url, {
  method: "POST",
  headers: { "Content-Type": "application/json", Accept: "application/json" },
  body: JSON.stringify(data),
  signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const result = await res.json();

Request ကို options object တစ်ခုထဲမှာ ဖော်ပြပြီး res.ok စစ်ပြီးမှ body ကို ဖတ်ပါ။ GET မှာ body နဲ့ Content-Type မလိုပါဘူး။

Worked example: server ဘာမြင်လဲ ကြည့်ပြီး bug သုံးမျိုး

အောက်က script က JSON ကိုပဲ လက်ခံတဲ့ တင်းကြပ်တဲ့ endpoint တစ်ခုကို စတင်ပြီး တူညီတဲ့ user data ကို နည်းလမ်းသုံးမျိုးနဲ့ ပို့ပါတယ်။ Server ဘက်က ရောက်လာတဲ့ Content-Type နဲ့ body စာသား အတိအကျကို print ထုတ်တာမို့ client ကနေ ဘာထွက်သွားလဲ မျက်စိနဲ့ မြင်ရပါတယ်။

ပထမကြိုးစားမှုမှာ object ကို တိုက်ရိုက်ပို့လို့ server က text/plain နဲ့ [object Object] ကို မြင်ပါတယ်။ ဒုတိယမှာ stringify လုပ်ထားပေမဲ့ Content-Type မပါလို့ server က JSON လို့ မသိပါဘူး။ တတိယမှာပဲ နှစ်ခုစလုံး မှန်လို့ 201 ရပါတယ်။

json-request.mjs
import http from "node:http";

// A strict JSON endpoint: it only accepts bodies labelled application/json.
const server = http.createServer(async (req, res) => {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  const type = req.headers["content-type"] ?? "(none)";
  console.log(`  server saw: ${type} | ${raw}`);

  const reply = (status, body) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(body));
  };
  if (!type.startsWith("application/json")) {
    return reply(415, { error: "unsupported_media_type" });
  }
  try {
    reply(201, { id: 1, ...JSON.parse(raw) });
  } catch {
    reply(400, { error: "invalid_json" });
  }
});

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const url = `http://127.0.0.1:${server.address().port}/v1/users`;
const user = { name: "Alice", email: "alice@example.com" };

async function attempt(label, init) {
  console.log(label);
  const res = await fetch(url, { method: "POST", ...init });
  console.log(`  -> ${res.status} ${await res.text()}`);
}

await attempt("1. object passed as body", { body: user });
await attempt("2. stringified, no header", { body: JSON.stringify(user) });
await attempt("3. stringified + Content-Type", {
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(user),
});
server.close();

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. A strict endpointif (!type.startsWith("application/json")) {

    Server က Content-Type ကို အရင်ကြည့်ပါတယ်။ application/json မဟုတ်ရင် body ကို parse မလုပ်ဘဲ 415 Unsupported Media Type ပြန်ပါတယ်။ API အများစုက ဒီလိုပဲ ဆုံးဖြတ်ပါတယ်။

  2. Log what arrivedconsole.log(` server saw: ${type} | ${raw}`);

    ဒီ line က ဒီ lesson ရဲ့ အဓိကပါ။ Server ဘက်ကနေ header နဲ့ body ကို တိုက်ရိုက် print ထုတ်တာမို့ client code က အမှန်တကယ် ဘာပို့လဲ ကြိုမခန့်မှန်းဘဲ မြင်ရပါတယ်။

  3. Bug 1: no stringifyawait attempt("1. object passed as body", { body: user });

    user object ကို body မှာ တိုက်ရိုက်ထည့်လို့ fetch က String(user) လုပ်ပြီး [object Object] ပို့ပါတယ်။ Content-Type ကလည်း text/plain;charset=UTF-8 ဖြစ်သွားပါတယ်။

  4. Bug 2: no Content-Typeawait attempt("2. stringified, no header", { body: JSON.stringify(user) });

    Body က JSON စာသား မှန်ပေမဲ့ Content-Type မပါလို့ fetch က text/plain ထည့်ပေးပါတယ်။ Server ဘက်က 'JSON မဟုတ်ဘူး' လို့ ယူဆပြီး 415 ပြန်ပါတယ်။

  5. Correct requestheaders: { "Content-Type": "application/json" },

    Header နဲ့ JSON.stringify နှစ်ခုစလုံး ပါမှ server က body ကို JSON parse လုပ်ပြီး 201 Created နဲ့ id ပါတဲ့ user ပြန်ပေးပါတယ်။

You should see
1. object passed as body
  server saw: text/plain;charset=UTF-8 | [object Object]
  -> 415 {"error":"unsupported_media_type"}
2. stringified, no header
  server saw: text/plain;charset=UTF-8 | {"name":"Alice","email":"alice@example.com"}
  -> 415 {"error":"unsupported_media_type"}
3. stringified + Content-Type
  server saw: application/json | {"name":"Alice","email":"alice@example.com"}
  -> 201 {"id":1,"name":"Alice","email":"alice@example.com"}

တူညီတဲ့ request ကို curl နဲ့

curl မှာ -H က header တစ်ခုချင်းစီကို ထည့်ပြီး -d က body ကို ထည့်ပါတယ်၊ -d ပါရင် method က POST ဖြစ်သွားလို့ -X POST က မဖြစ်မနေ မလိုပါဘူး။ ဥပမာတွေထဲက host တွေက ရှင်းပြဖို့ ထည့်ထားတာပါ၊ api.example.com က တကယ်မရှိတဲ့ ဥပမာ host ဖြစ်လို့ ကိုယ့် API ရဲ့ URL နဲ့ အစားထိုးပါ။

post-json.sh
# api.example.com is an illustrative host, not a real service
curl -X POST "https://api.example.com/v1/users" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{"name":"Alice","email":"alice@example.com"}'

ပိုတိုတဲ့ပုံစံက --json ပါ (curl 7.82 ကစပြီး ရပါတယ်)၊ Content-Type နဲ့ Accept ကို application/json နဲ့ ကိုယ်စား ထည့်ပေးပြီး POST ကိုလည်း ရွေးပေးပါတယ်။ -i က response ရဲ့ status line နဲ့ header တွေကို body မတိုင်ခင် ပြပေးလို့ debug လုပ်ရာမှာ အသုံးဝင်ပါတယ်။

post-json-short.sh
# --json sets Content-Type and Accept for you and implies POST (curl 7.82+)
curl --json '{"name":"Alice","email":"alice@example.com"}' \
  "https://api.example.com/v1/users"

# -i prints the status line and response headers before the body
curl -i "https://api.example.com/v1/users/u_1"

Shell အလိုက် quoting ကွာတယ်

ဒီ ဥပမာတွေက bash နဲ့ zsh အတွက်ပါ၊ single quote ထဲက JSON ကို အဲဒီမှာ မပြောင်းလဲပါဘူး။ Windows cmd.exe က single quote ကို quote အဖြစ် မသတ်မှတ်လို့ double quote သုံးပြီး JSON ထဲက " ကို \" လို့ escape လုပ်ရပါတယ်။ PowerShell မှာ curl က Invoke-WebRequest ရဲ့ alias ဖြစ်လို့ curl.exe လို့ ရေးပါ။

Query string နဲ့ shell မှာ & ကို quote လုပ်ခြင်း

Query string ထဲက တန်ဖိုးတွေမှာ & ဒါမှမဟုတ် space ပါရင် string ဆက်ရေးတာက URL ကို ဖြတ်ပစ်ပါတယ်။ URLSearchParams က တန်ဖိုးတစ်ခုချင်းစီကို encode လုပ်ပေးတာမို့ q=tea & cake က q=tea+%26+cake ဖြစ်သွားပါတယ်။ အောက်က script က ဆက်ရေးတဲ့နည်းနဲ့ URLSearchParams ကို ယှဉ်ပြပါတယ်။

query-strings.mjs
const params = new URLSearchParams({ q: "caf\u00e9 & tea", page: "2" });
console.log(`https://api.example.com/v1/search?${params}`);

// Gluing strings together breaks as soon as a value contains & or a space:
console.log("https://api.example.com/v1/search?q=" + "tea & cake" + "&page=2");
console.log(new URLSearchParams({ q: "tea & cake", page: "2" }).toString());

ပထမ line မှာ café ရဲ့ é က %C3%A9 ဖြစ်ပြီး space က + ဖြစ်တာ တွေ့ပါမယ်။ ဒုတိယ line က ဆက်ရေးတာမို့ & ရှေ့နောက်က q နဲ့ page ကို server က ခွဲမမြင်ပါဘူး၊ တတိယ line က မှန်ပါတယ်။ Terminal မှာလည်း အတူတူပါပဲ: URL ကို double quote နဲ့ ဖုံးထားရမယ်၊ မဟုတ်ရင် shell က & မှာ command ကို ဖြတ်ပြီး နောက်ပိုင်းကို တခြား command အဖြစ် ယူပါတယ်။ အောက်က curl ဥပမာမှာ -G နဲ့ --data-urlencode က query string ကို ဆောက်ပေးပါတယ်။

get-with-query.sh
# Quote the URL: an unquoted & ends the command in bash and zsh
# -G + --data-urlencode builds the query string and encodes each value
curl -sS --fail-with-body --max-time 5 \
  -H "Authorization: Bearer $TOKEN" \
  -G "https://api.example.com/v1/users" \
  --data-urlencode "role=admin" \
  --data-urlencode "q=tea & cake"

TOKEN ဆိုတာ ကိုယ့် shell မှာ ကြိုသတ်မှတ်ထားတဲ့ environment variable ပါ၊ token ကို command ထဲ တိုက်ရိုက်မရေးပါနဲ့၊ shell history ထဲ ကျန်နေမှာမို့ပါ။

Wire ပေါ်မှာ ဘာတွေ သွားလဲ

fetch ဒါမှမဟုတ် curl ကနေ ထွက်သွားတဲ့ request က အောက်ကလိုပါ: start line၊ header တစ်ကြောင်းစီ၊ လွတ်တဲ့ line တစ်ကြောင်း၊ ပြီးမှ body။ Content-Length က body ရဲ့ byte အရေအတွက်ပါ၊ fetch နဲ့ curl က ကိုယ်တိုင် တွက်ပေးပါတယ်။

text
POST /v1/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json
Content-Length: 44

{"name":"Alice","email":"alice@example.com"}

Server ရဲ့ အဖြေကလည်း ဒီပုံစံအတိုင်းပါပဲ: status line၊ header၊ လွတ်တဲ့ line၊ body။ 201 Created နဲ့ Location header က ဖန်တီးလိုက်တဲ့ user ရဲ့ URL ကို ပြောပြပါတယ်။

text
HTTP/1.1 201 Created
Content-Type: application/json
Location: /v1/users/u_1
Content-Length: 55

{"id":"u_1","name":"Alice","email":"alice@example.com"}

fetch က 404 မှာ မ throw ဘူး၊ timeout လည်း ကိုယ်တိုင်ထည့်ရတယ်

အောက်က script က 404 ပြန်တဲ့ endpoint ကို fetch နဲ့ ခေါ်ပြီး res.ok ကို ကြည့်ပါတယ်၊ ပြီးတော့ ၅၀၀ မီလီစက္ကန့် နှေးတဲ့ endpoint ကို ၁၀၀ မီလီစက္ကန့် timeout နဲ့ ခေါ်ပါတယ်။

ok-and-timeout.mjs
import http from "node:http";

const server = http.createServer((req, res) => {
  if (req.url === "/slow") {
    const timer = setTimeout(() => res.end("late"), 500);
    res.on("close", () => clearTimeout(timer)); // stop if the client gave up
    return;
  }
  res.writeHead(404, { "Content-Type": "application/json" });
  res.end('{"error":"not_found"}');
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

const missing = await fetch(`${base}/v1/users/999`);
console.log(missing.ok, missing.status); // false 404: fetch did not throw
console.log(await missing.json());

try {
  await fetch(`${base}/slow`, { signal: AbortSignal.timeout(100) });
} catch (err) {
  console.log(err.name, "-", err.message);
}
server.close();

ပထမ line က false 404 ဖြစ်ပြီး error မတက်ဘဲ response ကို ပြန်ရတာ တွေ့ပါမယ်။ နောက်ဆုံး line က AbortSignal.timeout က fetch ကို ဖြတ်လိုက်တဲ့အခါ တက်တဲ့ TimeoutError ပါ။ ဒီ error ကို catch လုပ်ပြီး ပြန်ကြိုးစားမလား၊ user ကို ပြမလား ဆုံးဖြတ်နိုင်ပါတယ်။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ request ရေးခြင်း

API documentation အများစုက curl ဥပမာနဲ့ စပါတယ်၊ ဒါကြောင့် curl ကို ဖတ်တတ်ရင် အသစ်တစ်ခုကို စမ်းဖို့ မိနစ်အနည်းငယ်ပဲ ကြာပါတယ်။ Browser ရဲ့ DevTools ရဲ့ Network tab မှာ request ကို right-click နှိပ်ပြီး 'Copy as cURL' လုပ်လို့ရလို့ website က အလုပ်လုပ်နေတဲ့ request ကို terminal မှာ အတိအကျ ပြန်ပို့ကြည့်နိုင်ပါတယ်။ Backend ကနေ တခြား service ကို ခေါ်တဲ့အခါတော့ fetch ကို timeout၊ retry နဲ့ error handling ပါတဲ့ helper တစ်ခုထဲမှာ ထုပ်ပြီး code တစ်ခုလုံး မှာ သုံးပါတယ်။

  • Postman ဒါမှမဟုတ် Insomnia လို tool တွေက curl ကို import လုပ်ပြီး request ကို သိမ်းထားလို့ရလို့ team ထဲမှာ မျှဝေရတာ လွယ်ပါတယ်။
  • SDK တွေက အတွင်းမှာ ဒီလို fetch ကိုပဲ ခေါ်ပါတယ်။ SDK မရှိတဲ့ API အတွက် ကိုယ်ပိုင် client လေးတစ်ခု ရေးတာ ဒီ lesson ရဲ့ ပုံစံပါပဲ။
  • Production မှာ request ID header ထည့်ပြီး log မှာ method, URL (secret မပါဘဲ) နဲ့ status ကို မှတ်ထားပါတယ်၊ ပြဿနာ တက်တဲ့အခါ ရှာလို့ရအောင်ပါ။
  • CI မှာ API ကို smoke test လုပ်ဖို့ curl --fail-with-body ကို သုံးပါတယ်၊ HTTP error ဖြစ်ရင် curl က သုညမဟုတ်တဲ့ exit code ပြန်ပြီး pipeline ကို fail ဖြစ်စေပေမဲ့ response body ကိုလည်း ဆက်ပြပေးပါတယ်။

အမှားများ

Request ပို့ရာမှာ ဖြစ်လေ့ရှိတဲ့ အမှားများ

JSON.stringify မေ့ခြင်း

body: { name: 'Alice' } လို့ ရေးရင် fetch က [object Object] ပို့ပါတယ်။ Error မတက်တာကြောင့် ရှာရခက်ပါတယ်၊ server log မှာ body ကို print ထုတ်ကြည့်တာက အမြန်ဆုံး ရှာတဲ့နည်းပါ။

Content-Type header မထည့်ခြင်း

JSON.stringify လုပ်ထားပေမဲ့ header မပါရင် text/plain နဲ့ ပို့မိပြီး server က 415 ပြန်တာ ဒါမှမဟုတ် body ကို မဖတ်ဘဲ အလွတ်အဖြစ် ယူတာ ဖြစ်ပါတယ်။ JSON ပို့တိုင်း ဒီနှစ်ခုကို အတွဲလိုက် ရေးပါ။

fetch က 404 နဲ့ 500 မှာ throw မယ်လို့ ထင်ခြင်း

try/catch ထဲမှာ fetch ကို ထည့်ထားပေမဲ့ res.ok ကို မစစ်ရင် 404 ကို အောင်မြင်တယ်လို့ ယူသွားတာ ဖြစ်ပါတယ်။ ပြီးတော့ res.json() က error body ကို data လို့ ထင်ပြီး ဆက်သုံးမိပါတယ်။

Shell မှာ URL ကို quote မလုပ်ခြင်း

curl https://api.example.com/v1/users?role=admin&page=2 လို့ ရေးရင် bash က & မှာ curl ကို background ပို့ပြီး page=2 ကို သီးခြား command အဖြစ် ယူပါတယ်။ Server က role=admin ကိုပဲ မြင်ပါတယ်။ URL ကို အမြဲ double quote နဲ့ ဖုံးပါ။

Timeout မထည့်ခြင်း

Server တစ်ခု ကျသွားရင် timeout မရှိတဲ့ fetch က ကြာကြာ စောင့်နေပြီး ကိုယ့် service ရဲ့ request တွေ စုပုံသွားပါတယ်။ အမြဲ AbortSignal.timeout ဒါမှမဟုတ် curl --max-time ထည့်ပါ။

Best Practices

Best practices

  • JSON ပို့တိုင်း JSON.stringify နဲ့ Content-Type: application/json ကို အတွဲလိုက် ထည့်ပါ။
  • Query string ကို URLSearchParams နဲ့ ဆောက်ပါ၊ shell မှာ URL ကို quote လုပ်ပါ။
  • res.ok ကို စစ်ပြီးမှ body ကို ဖတ်ပါ၊ timeout ကို အမြဲ သတ်မှတ်ပါ။
  • Token ကို command မှာ တိုက်ရိုက်မရေးဘဲ environment variable ကနေ ဖတ်ပါ။

Mini challenge

Mini challenge: ကိုယ်ပိုင် request() helper

fetch ကို ထုပ်တဲ့ request(path, options) function တစ်ခု ရေးပါ။ Query ကို URLSearchParams နဲ့ ဆောက်ပါ၊ body ပါမှ JSON header နဲ့ JSON.stringify ကို သုံးပါ၊ AbortSignal.timeout နဲ့ timeout ထည့်ပါ၊ res.ok မဟုတ်ရင် status နဲ့ server ပြောတဲ့ error ပါတဲ့ Error ကို throw လုပ်ပါ။ Local server တစ်ခုနဲ့ အခြေအနေလေးခုကို စမ်းပါ။

  • Query ကို URLSearchParams နဲ့ ဆောက်ပြီး တန်ဖိုးမှာ & ပါလည်း မှန်ရမယ်
  • Body ပါမှသာ Content-Type: application/json နဲ့ JSON.stringify ကို သုံးရမယ်
  • res.ok မဟုတ်ရင် Error("HTTP <status>: <error>") ကို throw လုပ်ရမယ်
  • Search, user ဖန်တီး၊ မရှိတဲ့ path နဲ့ ၁၀၀ မီလီစက္ကန့် timeout ပါတဲ့ /slow ကို စမ်းပြီး တစ်ကြောင်းစီ print ထုတ်ပါ
request-helper.mjs
import http from "node:http";

// TODO: a local server on port 0 with four routes:
//   GET /search?q=...     -> 200 { q }
//   POST /users           -> 201 { id: 1, ...parsed JSON body }
//   GET /slow             -> answers after 500 ms (stop the timer if the client leaves)
//   anything else         -> 404 { error: "not_found" }

// TODO: request(path, { method, query, body, timeoutMs }) that
//   - builds the query string with URLSearchParams
//   - sends JSON (header + JSON.stringify) only when a body is given
//   - gives up after timeoutMs with AbortSignal.timeout
//   - throws Error("HTTP <status>: <error>") when res.ok is false

// TODO: print one line for each: search with "tea & cake", create a user,
//       an unknown path, and /slow with a 100 ms timeout

ရလဒ်: query က {"q":"tea & cake"}၊ create user က {"id":1,"name":"Alice"}၊ missing က Error: HTTP 404: not_found၊ slow က TimeoutError ဖြစ်ရမယ်။

အရိပ်အမြွက် ကြည့်ရန်

new URL(path, baseUrl) ကို ဆောက်ပြီး url.search ကို URLSearchParams နဲ့ သတ်မှတ်ပါ။ Error ကို throw မလုပ်ခင် response body ကို res.json() နဲ့ ဖတ်ပါ၊ ဒါမှ server ရဲ့ error စာသား ရမှာပါ။ Timeout ဆိုရင် err.name က TimeoutError ဖြစ်ပါတယ်။

အဖြေ ကြည့်ရန်
request-helper.mjs
import http from "node:http";

const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, "http://local");
  let raw = "";
  for await (const chunk of req) raw += chunk;
  const reply = (status, body) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(body));
  };

  if (url.pathname === "/search") return reply(200, { q: url.searchParams.get("q") });
  if (url.pathname === "/users" && req.method === "POST") {
    return reply(201, { id: 1, ...JSON.parse(raw) });
  }
  if (url.pathname === "/slow") {
    const timer = setTimeout(() => reply(200, { late: true }), 500);
    res.on("close", () => clearTimeout(timer));
    return;
  }
  reply(404, { error: "not_found" });
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const baseUrl = `http://127.0.0.1:${server.address().port}`;

async function request(path, { method = "GET", query, body, timeoutMs = 2000 } = {}) {
  const url = new URL(path, baseUrl);
  if (query) url.search = new URLSearchParams(query).toString();
  const headers = { Accept: "application/json" };
  if (body !== undefined) headers["Content-Type"] = "application/json";

  const res = await fetch(url, {
    method,
    headers,
    body: body === undefined ? undefined : JSON.stringify(body),
    signal: AbortSignal.timeout(timeoutMs),
  });
  const data = res.status === 204 ? null : await res.json();
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${data.error}`);
  return data;
}

async function show(label, pending) {
  try {
    console.log(label.padEnd(12), JSON.stringify(await pending));
  } catch (err) {
    console.log(label.padEnd(12), `${err.name}: ${err.message}`);
  }
}

await show("query", request("/search", { query: { q: "tea & cake" } }));
await show("create user", request("/users", { method: "POST", body: { name: "Alice" } }));
await show("missing", request("/nothing"));
await show("slow", request("/slow", { timeoutMs: 100 }));
server.close();

Quick Quiz 1 / 3

fetch(url, { method: 'POST', body: { name: 'Alice' } }) လို့ ခေါ်ရင် server က ဘာရလဲ?

Quick Quiz 2 / 3

await fetch(url) က 404 ရတဲ့အခါ ဘာဖြစ်လဲ?

Quick Quiz 3 / 3

ဘယ် command က curl ကြောင့် မဟုတ်ဘဲ shell ကြောင့် မှားလဲ?

မှတ်ထားရမယ့် အချက်များ

  • Request ရဲ့ method, URL, header နဲ့ body တွေ ကိုက်ညီမှ server က နားလည်ပါတယ်။
  • JSON ပို့ရင် JSON.stringify(object) နဲ့ Content-Type: application/json ကို အတွဲလိုက် ထည့်ပါ၊ မဟုတ်ရင် server က [object Object] ဒါမှမဟုတ် text/plain မြင်ပါတယ်။
  • fetch က 404 နဲ့ 500 မှာ reject မလုပ်ပါဘူး၊ res.ok ကို စစ်ပြီး AbortSignal.timeout နဲ့ timeout ထည့်ပါ။
  • curl မှာ -H, -d, --json နဲ့ -G ကို သုံးပြီး URL ကို quote လုပ်ပါ၊ query string ကို URLSearchParams နဲ့ ဆောက်ပါ။

RFC 9110 — HTTP Semantics — IETF

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Request ဥပမာများ (curl & JS) | Thuta Learning