Thuta Learning
Python
AdvancedProgrammingအခြေခံ

API Basics (Enhanced)

Pythonသင်ခန်းစာ 4730 မိနစ်

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

  • HTTP request (method, URL, header, body) နဲ့ response (status, header, body) ရဲ့ အစိတ်အပိုင်းတွေကို ခွဲပြနိုင်ဖို့
  • 2xx, 3xx, 4xx, 5xx status code အုပ်စုတွေကို ဖတ်ပြီး 200, 201, 404, 500 လို code တွေရဲ့ အဓိပ္ပာယ် ပြောနိုင်ဖို့
  • requests.get() နဲ့ requests.post(json=...) ကို timeout ထည့်ပြီး ပို့နိုင်ဖို့
  • raise_for_status() နဲ့ HTTP error ကို network error နဲ့ ခွဲပြီး ကိုင်တွယ်နိုင်ဖို့

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

ရိုးရိုးလေး ရှင်းရရင်

စားသောက်ဆိုင်မှာ ကိုယ်တိုင် မီးဖိုချောင်ထဲ ဝင်ပြီး ချက်လို့ မရပါဘူး။ Menu ထဲက ဟင်းကို waiter ကို မှာရပြီး waiter က ဟင်းပွဲ ဒါမှမဟုတ် "ဒီနေ့ ကုန်သွားပြီ" ဆိုတဲ့ အဖြေကို ပြန်ယူလာပေးပါတယ်။

API (Application Programming Interface) က ဒီ menu နဲ့ waiter ပါ။ ကိုယ့် Python program က weather service ရဲ့ database ကို တိုက်ရိုက် မဖတ်ရဘဲ သတ်မှတ်ထားတဲ့ URL ကို request ပို့ပြီး JSON data နဲ့ status code ပါတဲ့ response ကို ပြန်ရပါတယ်။ Web API အများစုက HTTP ကို သုံးပါတယ်။

Problem → Why → Solution

ပြဿနာ: request အောင်မြင်တာနဲ့ API အောင်မြင်တာ မတူဘူး

အောက်က code ကို ပထမဆုံး API code အဖြစ် အများဆုံး ရေးကြပါတယ်။ Post ရှိရင် အလုပ်လုပ်ပါတယ်။ Post မရှိရင်တော့ server က 404 status နဲ့ {"error": "not found"} ကို ပြန်ပို့ပြီး data["title"] က KeyError နဲ့ crash ပါတယ်။ Server က လုံးဝ မဖြေရင်တော့ timeout မပါလို့ program က အချိန်အကန့်အသတ်မရှိ စောင့်နေပါလိမ့်မယ်။

first_call.py
import requests

response = requests.get("https://api.example.com/posts/42")  # no timeout
data = response.json()
print(data["title"])  # KeyError: the body was {"error": "not found"}

ဘာကြောင့် exception မတက်တာလဲ

HTTP အလွှာမှာတော့ ဒါက အောင်မြင်တဲ့ အသွားအပြန်ပါပဲ — request ရောက်ပြီး response လည်း ပြန်လာပါတယ်။ requests library က 4xx, 5xx status တွေမှာ ကိုယ့်ဘာသာ exception မပစ်ပါဘူး၊ status ကို စစ်ဖို့က ကိုယ့်တာဝန်ပါ။ timeout ကိုလည်း default မပေးထားလို့ ကိုယ်တိုင် မထည့်ရင် server တစ်ခု ငြိမ်နေတာနဲ့ program တစ်ခုလုံး ရပ်သွားနိုင်ပါတယ်။

Core concept: HTTP request နဲ့ response

HTTP request တစ်ခုမှာ အပိုင်းလေးပိုင်း ပါပါတယ်။ Method က ဘာလုပ်ချင်လဲ (GET ဖတ်ဖို့၊ POST အသစ်ဖန်တီးဖို့၊ PUT/PATCH ပြင်ဖို့၊ DELETE ဖျက်ဖို့) ပြောပါတယ်။ URL က ဘယ် resource လဲ ပြောပြီး ?city=Yangon လို query string ပါနိုင်ပါတယ်။ Header တွေက Accept, Content-Type, Authorization လို metadata တွေ သယ်ပြီး body ကတော့ POST/PUT မှာ ပို့တဲ့ data (အများအားဖြင့် JSON) ပါ။

Methodပုံမှန် အသုံးထပ်ပို့ရင် ဘေးကင်းလား
GETresource ကို ဖတ်တယ်ဘေးကင်း — ဘာမှ မပြောင်းလဲ
POSTresource အသစ် ဖန်တီးတယ်မကင်း — နှစ်ခု ဖြစ်သွားနိုင်
PUTresource တစ်ခုလုံးကို အစားထိုးတယ်ဘေးကင်း — ရလဒ် အတူတူ
PATCHfield တချို့ကို ပြင်တယ်ပြင်ပုံပေါ် မူတည်
DELETEresource ကို ဖျက်တယ်ဘေးကင်း — ဒုတိယအကြိမ်မှာ 404 ရနိုင်

Response မှာတော့ status code, header နဲ့ body ပါပါတယ်။ Status code ရဲ့ ပထမ ဂဏန်းက အုပ်စုကို ပြောပါတယ်၊ ဒါကြောင့် code တိုင်းကို အလွတ်ကျက်စရာ မလိုပါဘူး။

အုပ်စုအဓိပ္ပာယ်နဲ့ ဥပမာ
2xxအောင်မြင် — 200 OK, 201 Created, 204 No Content
3xxတခြားနေရာ ရွှေ့ထား — 301, 302 (HEAD မှလွဲရင် requests က redirect ကို အလိုအလျောက် လိုက်ပါတယ်)
4xxClient ဘက်က အမှား — 400 Bad Request, 401 Unauthorized, 404 Not Found, 429 Too Many Requests
5xxServer ဘက်က အမှား — 500 Internal Server Error, 503 Service Unavailable

Python မှာ requests library (pip install requests) က ဒီ အသွားအပြန်ကို လွယ်ကူစေပါတယ်။ requests.get(url, params=..., headers=..., timeout=5) က Response object ပြန်ပေးပြီး response.status_code, response.headers, response.text, response.json() နဲ့ အပိုင်းတိုင်းကို ဖတ်လို့ရပါတယ်။ requests.post(url, json=payload) က dict ကို JSON အဖြစ် ပြောင်းပြီး Content-Type: application/json header ကို အလိုအလျောက် ထည့်ပေးပါတယ်။ response.raise_for_status() က 4xx/5xx ဆိုရင် HTTPError ပစ်ပြီး 2xx ဆိုရင် ဘာမှ မလုပ်ပါဘူး။

API ပုံစံ အမျိုးမျိုး ရှိပါတယ်။ REST က resource URL တွေနဲ့ HTTP method တွေကို သုံးလို့ အသုံးအများဆုံးပါ။ GraphQL က endpoint တစ်ခုတည်းကို query ပို့ပြီး လိုတဲ့ field ကိုပဲ တောင်းပါတယ်။ SOAP ကတော့ XML အခြေခံ ပုံစံဟောင်းပါ။

မှတ်ထားရမယ့် ပုံစံ: အသွားနဲ့ အပြန်
  1. Method + URL + header + body ပို့
  2. Server က resource ကို လုပ်ဆောင်
  3. Status + header + body ပြန်လာ
  4. Status ကို အရင်စစ်၊ ပြီးမှ body ဖတ်

Response ရောက်လာတာက network အောင်မြင်တာပဲ ဖြစ်ပြီး API က အောင်မြင်လား ဆိုတာ status code က ပြောပါတယ်။

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

python
import requests

response = requests.get(url, params=query_dict, headers=header_dict, timeout=seconds)
response = requests.post(url, json=payload_dict, timeout=seconds)

response.raise_for_status()   # HTTPError for 4xx / 5xx
status = response.status_code
data = response.json()        # parse the JSON body

params က query string ဖြစ်လာပြီး json= က request body ဖြစ်လာပါတယ်။ timeout ကို request တိုင်းမှာ ထည့်ပါ။ Body ကို မဖတ်ခင် raise_for_status() ဒါမှမဟုတ် status_code နဲ့ အရင်စစ်ပါ။

Example: offline fake API နဲ့ GET, POST, 404

Internet မလိုဘဲ run လို့ရအောင် example ရဲ့ ပထမပိုင်းက Python standard library ရဲ့ http.server နဲ့ ကိုယ့်စက်ပေါ်မှာ (127.0.0.1) API သေးသေးလေး တစ်ခု ဖွင့်ထားပါတယ်။ ဒုတိယပိုင်းက client code ဖြစ်ပြီး URL ကို တကယ့် API URL နဲ့ လဲလိုက်ရင် အတူတူ အလုပ်လုပ်ပါတယ်။ requests က တကယ့် HTTP request တွေကို ပို့ပါတယ်။

api_basics.py
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer

import requests


# --- A tiny fake API on your own machine, so the example runs offline ---
class FakeAPI(BaseHTTPRequestHandler):
    def reply(self, status, data):
        body = json.dumps(data).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path == "/posts/1":
            self.reply(200, {"id": 1, "userId": 1, "title": "Hello API"})
        else:
            self.reply(404, {"error": "post not found"})

    def do_POST(self):
        size = int(self.headers["Content-Length"])
        post = json.loads(self.rfile.read(size))
        self.reply(201, {**post, "id": 101})

    def log_message(self, *args):  # keep the server quiet
        pass


server = HTTPServer(("127.0.0.1", 0), FakeAPI)
threading.Thread(target=server.serve_forever, daemon=True).start()
BASE = f"http://127.0.0.1:{server.server_port}"

# --- The client: the same code works against a real API URL ---
response = requests.get(f"{BASE}/posts/1", timeout=5)
print("GET status:", response.status_code, response.reason)
print("Content-Type:", response.headers["Content-Type"])
print("Title:", response.json()["title"])

new_post = {"title": "Sai's Post", "body": "Hello API", "userId": 1}
response = requests.post(f"{BASE}/posts", json=new_post, timeout=5)
print("POST status:", response.status_code, response.reason)
print("Created:", response.json())

response = requests.get(f"{BASE}/posts/999", timeout=5)
try:
    response.raise_for_status()
except requests.exceptions.HTTPError:
    print("HTTP error:", response.status_code, response.json()["error"])

server.shutdown()

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

  1. Fake serverserver = HTTPServer(("127.0.0.1", 0), FakeAPI)

    Port 0 က OS ကို လွတ်နေတဲ့ port တစ်ခု ရွေးခိုင်းတာပါ။ Server ကို daemon thread ထဲမှာ run လို့ main program က client code ကို ဆက် run နိုင်ပါတယ်။

  2. GET with timeoutresponse = requests.get(f"{BASE}/posts/1", timeout=5)

    timeout=5 က server ဆီ ချိတ်ဆက်တာ ဒါမှမဟုတ် data စောင့်တာ ၅ စက္ကန့်ထက် ကြာရင် exception ပစ်ပါတယ်။ Response ရဲ့ status_code နဲ့ reason က 200 OK ပါ။

  3. Read JSONprint("Title:", response.json()["title"])

    .json() က response body ကို Python dict အဖြစ် parse လုပ်ပေးပါတယ်။ Status ကို စစ်ပြီးမှ ခေါ်တာ ဘေးကင်းပါတယ်။

  4. POSTresponse = requests.post(f"{BASE}/posts", json=new_post, timeout=5)

    json= က dict ကို JSON text ပြောင်းပြီး Content-Type header ကို သတ်မှတ်ပေးပါတယ်။ Server က resource အသစ် ဖန်တီးလို့ 201 Created နဲ့ id 101 ပါတဲ့ object ကို ပြန်ပေးပါတယ်။

  5. Handle 404 response.raise_for_status()

    /posts/999 မရှိလို့ status 404 ပါ။ raise_for_status() က HTTPError ပစ်ပြီး except block က status နဲ့ server ပို့လိုက်တဲ့ error message ကို ပြပါတယ်။

You should see
GET status: 200 OK
Content-Type: application/json
Title: Hello API
POST status: 201 Created
Created: {'title': "Sai's Post", 'body': 'Hello API', 'userId': 1, 'id': 101}
HTTP error: 404 post not found
Python API & JSON Visual Guide
Python app, HTTP request, API server, JSON response flow ကို တစ်ကြောင်းတည်းမြင်နိုင်ပါတယ်။

ပို့မယ့် request ကို ကြိုကြည့်ခြင်း

requests.Request(...).prepare() က network ကို မထိဘဲ ပို့မယ့် request ကို တည်ဆောက်ပေးလို့ URL, header, body ကို စစ်ကြည့်လို့ရပါတယ်။ params dict ထဲက space ကို + အဖြစ် encode လုပ်ပေးတာ၊ json= က Content-Type ကို သတ်မှတ်ပေးတာကို မြင်ရပါမယ်။ URL ကို string ပေါင်းပြီး ကိုယ်တိုင် မဆောက်ဘဲ params ကို သုံးရတာ ဒီ encode လုပ်ပေးမှုကြောင့်ပါ။

inspect_request.py
import requests

search = requests.Request(
    "GET", "https://api.example.com/search",
    params={"q": "mandalay weather", "units": "metric"},
    headers={"Accept": "application/json"},
).prepare()
print(search.method, search.url)

create = requests.Request("POST", "https://api.example.com/posts",
                          json={"title": "Hi"}).prepare()
print(create.headers["Content-Type"], create.body)

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

Real project တွေမှာ ဘယ်လို သုံးလဲ

Weather data ယူတာ၊ payment provider ဆီ ငွေပေးချေမှု ဖန်တီးတာ၊ map service ကနေ လိပ်စာကို တည်နေရာ ပြောင်းတာ၊ GitHub API နဲ့ issue တွေ ဖတ်တာ — ဒါတွေ အားလုံးက ဒီ lesson ထဲက request/response ပုံစံ အတိုင်းပါပဲ။ API provider အများစုက API key ကို Authorization header ဒါမှမဟုတ် query parameter နဲ့ ပို့ခိုင်းပြီး key ကို source code ထဲ မထည့်ဘဲ environment variable ကနေ ဖတ်ရပါတယ်။

Production client တွေမှာ status code အလိုက် တုံ့ပြန်ပုံ ကွဲပါတယ်။ 400 နဲ့ 422 ဆိုရင် ကိုယ်ပို့တဲ့ data မှားလို့ ထပ်ပို့လည်း အကျိုးမရှိပါဘူး။ 401 ဆိုရင် key ကို စစ်ရပြီး 429 ဆိုရင် Retry-After header အတိုင်း စောင့်ရပါတယ်။ 5xx နဲ့ timeout တွေကိုတော့ အကြိမ်အရေအတွက် ကန့်သတ်ပြီး ခဏစောင့်ကာ ပြန်ကြိုးစားလို့ ရပါတယ်။ ဒါကို နောက် lesson တွေမှာ ဆက်ကြည့်ပါမယ်။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. timeout မထည့်တာ

requests မှာ default timeout မရှိလို့ server တစ်ခု ငြိမ်နေရင် request က အချိန်အကန့်အသတ်မရှိ စောင့်ပါတယ်။ Web server worker ဒါမှမဟုတ် scheduled job တစ်ခုလုံး ရပ်သွားနိုင်လို့ request တိုင်းမှာ timeout=5 လို တန်ဖိုး ထည့်ပါ။

2. Status မစစ်ဘဲ .json() ခေါ်တာ

Error response ရဲ့ body က ကိုယ်မျှော်လင့်တဲ့ field တွေ မပါလို့ KeyError ဖြစ်တတ်ပြီး proxy ဒါမှမဟုတ် load balancer က HTML error page ပြန်ရင် .json() ကိုယ်တိုင်က JSONDecodeError ပစ်ပါတယ်။ raise_for_status() ကို အရင် ခေါ်ပါ။

3. API key ကို code ထဲ ရေးထားတာ

Key ကို source file ထဲ ထည့်ပြီး git commit လုပ်လိုက်ရင် repository ကို မြင်ရတဲ့ လူတိုင်း သုံးလို့ရသွားပါတယ်။ os.environ["WEATHER_API_KEY"] နဲ့ ဖတ်ပြီး key ကို log ထဲမှာလည်း print မထုတ်ပါနဲ့။

4. Error တိုင်းကို ပြန်ကြိုးစားတာ

400 Bad Request ကို ဘယ်နှခါ ပြန်ပို့ပို့ ရလဒ် မပြောင်းပါဘူး၊ POST ကို မစဉ်းစားဘဲ ပြန်ပို့ရင် record နှစ်ခု ဖြစ်သွားနိုင်ပါတယ်။ Timeout, 503 လို ယာယီ ပြဿနာတွေကိုပဲ ကန့်သတ်ပြီး ပြန်ကြိုးစားပါ။

Best Practices

အကောင်းဆုံး အလေ့အကျင့်များ

  • API တစ်ခုကို code မရေးခင် documentation ထဲက endpoint, method, လိုအပ်တဲ့ header နဲ့ error response ပုံစံကို အရင် ဖတ်ပါ။
  • Query string ကို f-string နဲ့ ကိုယ်တိုင် မဆောက်ဘဲ params= ကို ပေးပါ၊ space နဲ့ & လို စာလုံးတွေကို မှန်မှန် encode လုပ်ပေးပါတယ်။
  • API ခေါ်တဲ့ code ကို function တစ်ခုထဲ စုထားပါ၊ ဒါမှ test မှာ requests.get ကို patch လုပ်ရ လွယ်ပါတယ်။
  • Log ထဲမှာ URL နဲ့ status code ကို မှတ်ပြီး API key နဲ့ Authorization header ကိုတော့ ဘယ်တော့မှ မမှတ်ပါနဲ့။

Mini challenge

Mini challenge: user နာမည် ဘေးကင်းစွာ ယူတာ

fetch_user_name(user_id) ကို ရေးပါ။ Network မလိုအောင် unittest.mock.patch နဲ့ requests.get ကို fake response လေးခုနဲ့ အစားထိုးပြီး အောင်မြင်တာ၊ 404၊ 503၊ timeout ဆိုတဲ့ အခြေအနေ လေးမျိုးကို စမ်းပါ။

  • status_family(code) က "success", "redirect", "client error", "server error" ဒါမှမဟုတ် "unknown" ပြန်ရမယ်
  • requests.get ကို timeout နဲ့ ခေါ်ပြီး raise_for_status() ကို သုံးရမယ်
  • HTTPError ဆိုရင် "failed: <code> (<family>)" ပြန်ရမယ်
  • တခြား RequestException ဆိုရင် "failed: <ExceptionName>" ပြန်ရမယ်၊ အောင်မြင်ရင် name field ကို ပြန်ရမယ်
fetch_user.py
import json
from unittest.mock import patch

import requests


def fake_response(status, data):
    """Build a real requests.Response without touching the network."""
    resp = requests.Response()
    resp.status_code = status
    resp._content = json.dumps(data).encode("utf-8")
    return resp


def status_family(code):
    # TODO: map 2xx/3xx/4xx/5xx to a family name, anything else to "unknown"
    ...


def fetch_user_name(user_id):
    # TODO: GET https://api.example.com/users/<user_id> with a timeout
    # TODO: raise_for_status(); on HTTPError use e.response.status_code
    # TODO: catch requests.exceptions.RequestException for network problems
    # TODO: return the "name" field from the JSON body on success
    ...


# TODO: patch("requests.get", side_effect=[...]) with a 200, a 404, a 503
#       and requests.exceptions.ConnectTimeout(...), then call ids 1 to 4

ရလဒ်: Output လေးကြောင်း ထွက်ရပါမယ်: 1 -> Aye 2 -> failed: 404 (client error) 3 -> failed: 503 (server error) 4 -> failed: ConnectTimeout

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

patch ရဲ့ side_effect ကို list ပေးရင် ခေါ်တိုင်း နောက်တစ်ခုကို ပြန်ပေးပြီး item က exception ဆိုရင် return မလုပ်ဘဲ raise လုပ်ပါတယ်။ HTTPError ကို RequestException ထက် အရင် except လုပ်ပါ၊ HTTPError က RequestException ရဲ့ subclass ဖြစ်လို့ပါ။

အဖြေ ကြည့်ရန်
fetch_user.py
import json
from unittest.mock import patch

import requests


def fake_response(status, data):
    """Build a real requests.Response without touching the network."""
    resp = requests.Response()
    resp.status_code = status
    resp.reason = {200: "OK", 404: "Not Found", 503: "Service Unavailable"}[status]
    resp.url = "https://api.example.com/users"
    resp._content = json.dumps(data).encode("utf-8")
    return resp


def status_family(code):
    if 200 <= code < 300:
        return "success"
    if 300 <= code < 400:
        return "redirect"
    if 400 <= code < 500:
        return "client error"
    if 500 <= code < 600:
        return "server error"
    return "unknown"


def fetch_user_name(user_id):
    url = f"https://api.example.com/users/{user_id}"
    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()
    except requests.exceptions.HTTPError as e:
        code = e.response.status_code
        return f"failed: {code} ({status_family(code)})"
    except requests.exceptions.RequestException as e:
        return f"failed: {type(e).__name__}"
    return response.json()["name"]


fakes = [
    fake_response(200, {"id": 1, "name": "Aye"}),
    fake_response(404, {"error": "no such user"}),
    fake_response(503, {"error": "try later"}),
    requests.exceptions.ConnectTimeout("connect timed out"),
]
with patch("requests.get", side_effect=fakes):
    for user_id in [1, 2, 3, 4]:
        print(user_id, "->", fetch_user_name(user_id))

Quick Quiz 1 / 3

requests.get(url, timeout=5) ကို ခေါ်တော့ server က 404 ပြန်တယ်။ အဲဒီ line မှာ ဘာဖြစ်မလဲ။

Quick Quiz 2 / 3

POST request က resource အသစ်ကို အောင်မြင်စွာ ဖန်တီးပြီးတဲ့အခါ စံနှုန်းကိုက်တဲ့ API က ဘယ် status ကို အများအားဖြင့် ပြန်ပေးလဲ။

Quick Quiz 3 / 3

requests.post(url, json=payload) မှာ json= က ဘာလုပ်ပေးလဲ။

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

  • API က program နှစ်ခုကြားက စည်းမျဉ်း (contract) ဖြစ်ပြီး web API အများစုက HTTP request/response ကို သုံးပါတယ်။
  • Request = method + URL + header + body၊ response = status + header + body ပါ။
  • Status ရဲ့ ပထမ ဂဏန်းက အုပ်စုကို ပြောပါတယ် — 2xx အောင်မြင်၊ 4xx client အမှား၊ 5xx server အမှား။
  • Request တိုင်းမှာ timeout ထည့်ပြီး body ကို မဖတ်ခင် raise_for_status() နဲ့ status ကို စစ်ပါ။

Requests — User Guide — Requests

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

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

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

API Basics (Enhanced) | Thuta Learning