Thuta Learning
JavaScript
AdvancedProgrammingအခြေခံ

API Basics

JavaScriptသင်ခန်းစာ 3730 မိနစ်

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

  • Request တစ်ခုရဲ့ အစိတ်အပိုင်း လေးခုနဲ့ response ရဲ့ အစိတ်အပိုင်း သုံးခုကို နာမည်တပ်နိုင်ဖို့
  • URL နဲ့ URLSearchParams ကို သုံးပြီး query string ကို လုံခြုံစွာ တည်ဆောက်နိုင်ဖို့
  • Status code ရဲ့ 2xx, 4xx, 5xx အုပ်စုတွေကို ဖတ်ပြီး network error, HTTP error, invalid payload ကို ခွဲခြားနိုင်ဖို့
  • Frontend code ထဲက API key ဟာ secret မဟုတ်ဘူးဆိုတာ ရှင်းပြနိုင်ဖို့

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

API ကို ရိုးရိုးလေး ပြောရရင်

API (Application Programming Interface) ဆိုတာ program တစ်ခုက နောက် program တစ်ခုကို 'ဒီလို မေးရင် ဒီလို ဖြေပေးမယ်' လို့ ကတိပေးထားတဲ့ စည်းမျဉ်းစုပါ။ Web API တွေက HTTP ကို သုံးပါတယ်: သင့် JavaScript က URL တစ်ခုဆီ request ပို့ပြီး server က response တစ်ခု ပြန်ပေးပါတယ်၊ များသောအားဖြင့် JSON format နဲ့ပါ။

စားသောက်ဆိုင်က menu နဲ့ မှာယူမှု စာရွက်ကို စဉ်းစားကြည့်ပါ။ Menu (API documentation) က ဘာတွေ မှာလို့ရလဲ ပြောပြီး စာရွက် (request) မှာ ဘယ်ဟင်း၊ ဘယ်နှစ်ပွဲ စတာတွေကို သတ်မှတ်ထားတဲ့ ပုံစံအတိုင်း ရေးရပါတယ်။ မီးဖိုချောင် (server) ထဲမှာ ဘာဖြစ်နေလဲ သင် သိစရာ မလိုပါဘူး၊ ပြန်ရလာတဲ့ ပန်းကန် (response) ကိုပဲ စိတ်ဝင်စားရုံပါပဲ။

Problem → Why → Solution

ပြဿနာ: frontend ထဲက 'secret' key

Payment API တစ်ခုကို စမ်းနေရင်း secret key ကို .env file ထဲ ထည့်ပြီး frontend code က တိုက်ရိုက် ခေါ်လိုက်တယ် ဆိုပါစို့။ Code ထဲမှာ key ကို တိုက်ရိုက် မရေးထားလို့ လုံခြုံတယ်လို့ ထင်ရပါတယ်။ တကယ်တော့ Vite ရဲ့ VITE_ ဒါမှမဟုတ် Next.js ရဲ့ NEXT_PUBLIC_ prefix ပါတဲ့ variable တွေကို build လုပ်တဲ့အချိန်မှာ JavaScript bundle ထဲ စာသားအတိုင်း ထည့်ပေးလိုက်တာပါ။ Website ကို ဝင်ကြည့်တဲ့ ဘယ်သူမဆို DevTools ကနေ key ကို ကူးယူသွားနိုင်ပါတယ်။

checkout.js
// Runs in the visitor's browser: this value ends up inside the bundle
const key = import.meta.env.VITE_PAYMENTS_SECRET_KEY;

await fetch("https://api.payments.example/v1/charges", {
  method: "POST",
  headers: { Authorization: `Bearer ${key}` }, // visible in the Network tab
  body: JSON.stringify({ amount: 5000, currency: "usd" }),
});

Browser က secret ကို မထိန်းနိုင်ဘူး

Browser ထဲ ရောက်သွားတဲ့ code, variable, request header အားလုံးကို user က မြင်နိုင်ပါတယ်။ Secret key လိုတဲ့ API ခေါ်ဆိုမှုတွေကို သင့်ကိုယ်ပိုင် server (backend ဒါမှမဟုတ် serverless function) ကနေပဲ ပို့ပါ၊ browser က အဲဒီ server ကိုပဲ ခေါ်ပါ။ Frontend မှာ ထည့်လို့ရတာက ပိုင်ရှင်က public ဖြစ်ဖို့ ရည်ရွယ်ထားတဲ့ key (ဥပမာ domain ကန့်သတ်ထားတဲ့ publishable key) တွေပဲ ဖြစ်ပါတယ်။

Core concept: request, response နဲ့ contract

HTTP request တစ်ခုမှာ အစိတ်အပိုင်း လေးခု ရှိပါတယ်။ Method (GET, POST, PUT, PATCH, DELETE) က ဘာလုပ်ချင်လဲ ပြောပါတယ်။ URL က ဘယ် resource လဲ ပြောပြီး ?page=2&limit=10 လို query string ပါနိုင်ပါတယ်။ Headers က metadata ဖြစ်ပါတယ်: Accept (ဘယ် format ပြန်ချင်လဲ)၊ Content-Type (ပို့တဲ့ body ရဲ့ format)၊ Authorization (ကိုယ်ဘယ်သူလဲ)။ Body က ပို့မယ့် data ဖြစ်ပြီး POST, PUT, PATCH တွေမှာ အသုံးများပါတယ်။

Response မှာ အစိတ်အပိုင်း သုံးခု ရှိပါတယ်: status code၊ headers နဲ့ body။ Status code ရဲ့ ပထမ digit က အုပ်စုကို ပြောပါတယ်၊ ဒါကြောင့် မမြင်ဖူးတဲ့ code ကိုတောင် ဘယ်လို ကိုင်တွယ်ရမလဲ ခန့်မှန်းလို့ ရပါတယ်။

အုပ်စုအဓိပ္ပာယ်ဥပမာ
2xxအောင်မြင်တယ်200 OK, 201 Created, 204 No Content
3xxတခြားနေရာ သွားပါ301, 304 Not Modified
4xxClient ဘက်က မှားတယ်400, 401, 403, 404, 429
5xxServer ဘက်က မှားတယ်500, 502, 503

API contract (documentation ဒါမှမဟုတ် OpenAPI spec) က endpoint တစ်ခုချင်းစီရဲ့ method, request နဲ့ response shape, ဖြစ်နိုင်တဲ့ status code တွေ၊ authentication နည်း၊ rate limit (ဥပမာ တစ်မိနစ် request 60) နဲ့ version တွေကို သတ်မှတ်ပါတယ်။ GET က ဖတ်ဖို့၊ POST က ဖန်တီးဖို့ ဆိုတာ ယေဘုယျ စည်းမျဉ်းပါ၊ ဒါပေမဲ့ API တစ်ခုချင်းစီရဲ့ documentation ကသာ အတည်ဖြစ်ပါတယ်။

Client ဘက်ကနေ ကြည့်ရင် API call တစ်ခုက ပုံစံ သုံးမျိုးနဲ့ fail ဖြစ်နိုင်ပါတယ်: network error (response မရ)၊ HTTP error (4xx/5xx response ရ) နဲ့ invalid payload (2xx ရပေမဲ့ data shape မှားနေ)။ တစ်ခုချင်းစီကို ကိုင်တွယ်ပုံ မတူလို့ ခွဲခြားထားဖို့ လိုပါတယ်။ 5xx နဲ့ network error က နောက်တစ်ကြိမ် ပြန်ကြိုးစားရင် အောင်မြင်နိုင်ပေမဲ့ 4xx ကတော့ request ကိုယ်တိုင်ကို မပြင်မချင်း များသောအားဖြင့် ထပ်ပြီး fail ဖြစ်နေမှာပါ။

API call ကို စာပို့ပြီး စာပြန်ရတာလို မြင်ပါ
  1. Method + URL: ဘာကို ဘယ်မှာ
  2. Headers: format နဲ့ ကိုယ့်အထောက်အထား
  3. Body: ပို့မယ့် data (ရှိရင်)
  4. Status → headers → body ပြန်ရ
  5. Network/HTTP/payload error ခွဲ

Request ထဲ ထည့်လိုက်တဲ့ အရာတိုင်းကို browser ရဲ့ Network tab မှာ မြင်ရပါတယ်၊ secret တွေကို server ဘက်မှာပဲ ထားပါ။

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

text
METHOD https://host/path?key=value      <- request line
Header-Name: value                       <- headers (Accept, Authorization...)

{ "json": "body" }                       <- body (POST, PUT, PATCH)

HTTP/1.1 STATUS Reason                   <- response status line
Content-Type: application/json          <- response headers

{ "json": "result" }                     <- response body

HTTP message တိုင်းက ဒီပုံစံပါပဲ: ပထမ line၊ header တွေ၊ line အလွတ်တစ်ကြောင်းနဲ့ optional body။ JavaScript မှာ request object, fetch options နဲ့ Response object တွေက ဒီအစိတ်အပိုင်းတွေကို property အဖြစ် ကိုယ်စားပြုပါတယ်။

Worked example: request ကို တည်ဆောက်ပြီး response ကို ဖတ်ခြင်း

buildRequest helper က method, path, query, body, token တို့ကနေ request အပြည့်အစုံကို တည်ဆောက်ပါတယ်။ ပြီးတော့ server ပြန်ပေးနိုင်တဲ့ JSON response တစ်ခုကို parse လုပ်ပါတယ်။ Network ကို တမင် မသုံးထားပါဘူး: request ဆိုတာ မပို့ခင်အထိ data သက်သက်ပဲ ဖြစ်ပြီး print ထုတ်ကြည့်ရင် အစိတ်အပိုင်း တိုင်းကို မြင်ရပါတယ်။

api-basics.js
// An API call is a request (method, URL, headers, body) and a response
// (status, headers, body). Here both are plain objects you can inspect.
const baseUrl = "https://api.example.com";

function buildRequest(method, path, { query = {}, body, token } = {}) {
  const url = new URL(path, baseUrl);
  for (const [key, value] of Object.entries(query)) {
    url.searchParams.set(key, String(value));
  }
  const headers = { Accept: "application/json" };
  if (body !== undefined) headers["Content-Type"] = "application/json";
  if (token) headers.Authorization = `Bearer ${token}`;
  return { method, url: url.href, headers, body: body && JSON.stringify(body) };
}

const listUsers = buildRequest("GET", "/users", { query: { page: 2, limit: 1 } });
console.log(listUsers.method, listUsers.url);

const createUser = buildRequest("POST", "/users", {
  body: { name: "Aung Kyaw", email: "aung@example.com" },
  token: "demo-token",
});
console.log(createUser.method, createUser.url);
console.log("Headers:", Object.keys(createUser.headers).join(", "));
console.log("Body:", createUser.body);

// A response the server could send back for the GET request
const response = {
  status: 200,
  body: '{"page":2,"total":3,"users":[{"id":2,"name":"Su Su"}]}',
};
const data = JSON.parse(response.body);
console.log(`Status: ${response.status}`);
console.log(`Page ${data.page}: ${data.users[0].name} (${data.total} users in total)`);

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

  1. Safe URL buildingconst url = new URL(path, baseUrl);

    URL constructor က path ကို base နဲ့ ပေါင်းပေးပြီး searchParams.set က space, & လို special character တွေကို မှန်ကန်စွာ encode လုပ်ပေးပါတယ်။ String ပေါင်းတာထက် လုံခြုံပါတယ်။

  2. Headers depend on the requestif (body !== undefined) headers["Content-Type"] = "application/json";

    Content-Type က ပို့တဲ့ body ရဲ့ format ကို ပြောတာဖြစ်လို့ body ရှိမှ ထည့်ပါတယ်။ Accept ကတော့ ပြန်လိုချင်တဲ့ format ဖြစ်လို့ request တိုင်းမှာ ပါပါတယ်။

  3. Identify the callerif (token) headers.Authorization = `Bearer ${token}`;

    Bearer token က 'ဒီ token ကို ကိုင်ထားသူ' လို့ အဓိပ္ပာယ်ရပါတယ်။ ဒီမှာ demo-token ကို သုံးထားပါတယ်၊ တကယ့် secret ကိုတော့ server ပေါ်ကနေပဲ ပို့ပါ။

  4. Query string in the URLconst listUsers = buildRequest("GET", "/users", { query: { page: 2, limit: 1 } });

    GET request မှာ body မပါလို့ filter နဲ့ pagination ကို query string နဲ့ ပို့ပါတယ်။ Output မှာ ?page=2&limit=1 အဖြစ် ပေါ်လာပါတယ်။

  5. Response body is textconst data = JSON.parse(response.body);

    Network ပေါ်ကနေ ရောက်လာတဲ့ body က အမြဲ text ပါ။ JSON.parse လုပ်ပြီးမှ data.users[0].name လို property တွေကို ဖတ်လို့ရပါတယ်။

You should see
GET https://api.example.com/users?page=2&limit=1
POST https://api.example.com/users
Headers: Accept, Content-Type, Authorization
Body: {"name":"Aung Kyaw","email":"aung@example.com"}
Status: 200
Page 2: Su Su (3 users in total)

API က 'ကိုယ်ဘယ်သူလဲ' ကို ဘယ်လို သိလဲ

API အများစုက caller ကို request တိုင်းမှာ ပါလာတဲ့ အထောက်အထားနဲ့ မှတ်မိပါတယ်၊ server က ယခင် request ကို မမှတ်ထားလို့ပါ။ အသုံးများတဲ့ ပုံစံ သုံးမျိုးကို အောက်မှာ နှိုင်းယှဉ်ထားပါတယ်။ ဘယ်ပုံစံကို လက်ခံလဲဆိုတာ API documentation ရဲ့ authentication အပိုင်းမှာ ဖော်ပြထားပါတယ်။

ပုံစံဘယ်လို ပို့လဲဘယ်မှာ သုံးလဲ
API keyX-API-Key header ဒါမှမဟုတ် queryServer-to-server call
Bearer tokenAuthorization: Bearer <token>Login ဝင်ထားတဲ့ user၊ OAuth
Session cookieBrowser က အလိုအလျောက် ပို့Domain တူ web app

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

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

Frontend app တိုင်းနီးပါးက API တစ်ခုထက်မက ခေါ်ပါတယ်: ကိုယ်ပိုင် backend၊ map, payment, email လို third-party service တွေ။ အဖွဲ့တွေက API ကို documentation ထဲက ဥပမာ request/response နဲ့ status code ဇယားကနေ စတင် နားလည်ပြီး အဲဒါကို client function တွေအဖြစ် ပြောင်းရေးပါတယ်။

  • Backend-for-frontend ပုံစံ: browser က /api/checkout လို ကိုယ်ပိုင် endpoint ကို ခေါ်ပြီး server က secret key နဲ့ payment provider ကို ခေါ်ပါတယ်။ Key က browser ထဲ ဘယ်တော့မှ မရောက်ပါဘူး။
  • 429 Too Many Requests ရရင် Retry-After header မှာ ပြောထားတဲ့ စက္ကန့်ကို စောင့်ပြီးမှ ပြန်ကြိုးစားပါတယ်၊ ချက်ချင်း ထပ်ခါထပ်ခါ ပို့ရင် ပိုဆိုးလာပါတယ်။
  • API ကို /v1/ ဒါမှမဟုတ် version header နဲ့ ခွဲထားလို့ server ဘက်က response shape ပြောင်းတဲ့အခါ app အဟောင်းတွေ ချက်ချင်း မပျက်ပါဘူး။

အမှားများ

API နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ

Secret key ကို frontend ထဲ ထည့်ခြင်း

VITE_ ဒါမှမဟုတ် NEXT_PUBLIC_ variable၊ minify လုပ်ထားတဲ့ bundle၊ obfuscation တစ်ခုမှ key ကို မဖုံးကွယ်နိုင်ပါဘူး။ Key ပေါက်ကြားသွားရင် ချက်ချင်း rotate လုပ်ပြီး ခေါ်ဆိုမှုကို server ဘက် ရွှေ့ပါ။

Query string ကို string ပေါင်းပြီး တည်ဆောက်ခြင်း

"/search?q=" + term လို့ ရေးရင် term ထဲမှာ & ဒါမှမဟုတ် # ပါတဲ့အခါ URL ပျက်သွားပြီး parameter အသစ်တွေ ထိုးသွင်းခံရနိုင်ပါတယ်။ URLSearchParams ဒါမှမဟုတ် encodeURIComponent ကို သုံးပါ။

Failure အမျိုးအစား သုံးခုကို ရောထွေးခြင်း

Error အားလုံးကို 'တစ်ခုခု မှားနေတယ်' လို့ ပြရင် user က ဘာလုပ်ရမလဲ မသိပါဘူး။ Offline ဆိုရင် connection စစ်ခိုင်းပါ၊ 401 ဆိုရင် ပြန် login ဝင်ခိုင်းပါ၊ invalid payload ဆိုရင် bug report အတွက် log လုပ်ပါ။

4xx ကို loop ထဲမှာ ပြန်ကြိုးစားခြင်း

400 ဒါမှမဟုတ် 404 ရတဲ့ request ကို ထပ်ပို့ရုံနဲ့ မပြင်ပါဘူး၊ rate limit ကိုသာ ပိုမြန်မြန် ကုန်စေပါတယ်။ Retry ကို network error, 5xx နဲ့ Retry-After ပါတဲ့ 429 အတွက်ပဲ သုံးပြီး ကြိုးစားမှု အရေအတွက်ကို ကန့်သတ်ပါ။

Best Practices

Best practices

  • Endpoint အသစ်တစ်ခုကို code မရေးခင် documentation ထဲက ဥပမာ request/response ကို အရင် ဖတ်ပါ။
  • Base URL, auth header, timeout ကို client function တစ်ခုထဲ စုထားပါ။
  • 2xx ရတိုင်း data က မှန်တယ်လို့ မယူဆဘဲ အရေးကြီး field တွေကို စစ်ပါ။

Mini challenge

Mini challenge: ရလဒ်ကို အမျိုးအစားခွဲတဲ့ getUser

getUser(id, fetchFn) ကို ရေးပါ။ ဘာမှ throw မလုပ်ဘဲ kind field ပါတဲ့ object တစ်ခုကို အမြဲ ပြန်ပေးရပါမယ်: "ok", "invalid-payload", "http-error", "network-error"။ ပေးထားတဲ့ fakeApi က user id 1 မှ 5 အထိ ဖြစ်ရပ်တစ်ခုစီကို ပေးပါတယ်။

  • fetchFn reject ဖြစ်ရင် { kind: "network-error", message } ကို ပြန်ပေးရမယ်
  • response.ok မဟုတ်ရင် status ပါတဲ့ http-error ပြန်ပေးပြီး Retry-After header ရှိရင် number အဖြစ် ထည့်ရမယ်
  • isUser က id (number) နဲ့ name (string) ကို စစ်ပြီး မကိုက်ရင် invalid-payload ပြန်ပေးရမယ်
  • id 1 ကနေ 5 အထိ loop ပတ်ပြီး ရလဒ်တစ်ခုချင်းစီကို print ထုတ်ပါ
get-user.js
// Fake API: each user id triggers a different outcome.
const routes = {
  "/users/1": () => Response.json({ id: 1, name: "Aung Kyaw" }),
  "/users/2": () => Response.json({ id: 2 }), // the name field is missing
  "/users/3": () => Response.json({ error: "User not found" }, { status: 404 }),
  "/users/4": () => new Response(null, { status: 429, headers: { "Retry-After": "30" } }),
};

async function fakeApi(url) {
  const route = routes[new URL(url).pathname];
  if (!route) throw new TypeError("fetch failed"); // like DNS or a dropped connection
  return route();
}

function isUser(value) {
  // TODO: true only for a numeric id and a string name
}

async function getUser(id, fetchFn = fetch) {
  // TODO: 1. call fetchFn; on rejection return a "network-error" result
  // TODO: 2. if !response.ok return an "http-error" result (+ retryAfter)
  // TODO: 3. parse JSON; return "invalid-payload" or "ok" with the user
}

// TODO: print id and getUser(id, fakeApi) for ids 1 to 5

ရလဒ်: id 1 → kind 'ok' နဲ့ Aung Kyaw၊ 2 → 'invalid-payload'၊ 3 → status 404 ပါတဲ့ 'http-error'၊ 4 → status 429 နဲ့ retryAfter: 30၊ 5 → message 'fetch failed' ပါတဲ့ 'network-error'။

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

fetchFn ကို ခေါ်တဲ့ line တစ်ကြောင်းတည်းကိုပဲ try/catch နဲ့ ပတ်ပါ၊ ဒါမှ network error ကိုပဲ ဖမ်းမိပါမယ်။ Header နာမည်တွေက case-insensitive ဖြစ်လို့ response.headers.get("retry-after") က အလုပ်လုပ်ပါတယ်။

အဖြေ ကြည့်ရန်
get-user.js
// Fake API: each user id triggers a different outcome.
const routes = {
  "/users/1": () => Response.json({ id: 1, name: "Aung Kyaw" }),
  "/users/2": () => Response.json({ id: 2 }), // the name field is missing
  "/users/3": () => Response.json({ error: "User not found" }, { status: 404 }),
  "/users/4": () => new Response(null, { status: 429, headers: { "Retry-After": "30" } }),
};

async function fakeApi(url) {
  const route = routes[new URL(url).pathname];
  if (!route) throw new TypeError("fetch failed"); // like DNS or a dropped connection
  return route();
}

function isUser(value) {
  return typeof value?.id === "number" && typeof value?.name === "string";
}

async function getUser(id, fetchFn = fetch) {
  let response;
  try {
    response = await fetchFn(`https://api.example.com/users/${id}`);
  } catch (error) {
    return { kind: "network-error", message: error.message };
  }
  if (!response.ok) {
    const retryAfter = response.headers.get("retry-after");
    return retryAfter
      ? { kind: "http-error", status: response.status, retryAfter: Number(retryAfter) }
      : { kind: "http-error", status: response.status };
  }
  const data = await response.json();
  if (!isUser(data)) return { kind: "invalid-payload", data };
  return { kind: "ok", user: data };
}

async function main() {
  for (const id of [1, 2, 3, 4, 5]) {
    console.log(id, await getUser(id, fakeApi));
  }
}

main();

Quick Quiz 1 / 3

Login မဝင်ရသေးတဲ့ user က protected endpoint ကို ခေါ်တယ်။ API က ပုံမှန်အားဖြင့် ဘယ် status ကို ပြန်ပေးမလဲ?

Quick Quiz 2 / 3

Frontend code ထဲမှာ const key = import.meta.env.VITE_SECRET_KEY လို့ ရေးထားတယ်။ ဘယ်ဟာ မှန်လဲ?

Quick Quiz 3 / 3

API က 200 OK ပြန်ပေးပြီး body က {"id": "7"} ဖြစ်နေတယ်၊ documentation ကတော့ id က number နဲ့ name field ပါမယ်လို့ ပြောထားတယ်။ ဒါက ဘယ်လို failure လဲ?

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

  • Request တစ်ခုမှာ method, URL, headers, body ပါပြီး response မှာ status, headers, body ပါပါတယ်။
  • Status code ရဲ့ ပထမ digit က အုပ်စုကို ပြောပါတယ်: 2xx အောင်မြင်၊ 4xx client မှား၊ 5xx server မှား။
  • API call တစ်ခုက network error, HTTP error, invalid payload ဆိုပြီး ပုံစံ သုံးမျိုးနဲ့ fail ဖြစ်နိုင်ပါတယ်။
  • Browser ထဲ ရောက်တဲ့ key တိုင်းက public ဖြစ်ပါတယ်၊ secret လိုတဲ့ call တွေကို server ဘက်ကနေ ပို့ပါ။

MDN — Fetch API — MDN Web Docs

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

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

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

API Basics | Thuta Learning