ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
REST API ဆိုတာ စားသောက်ဆိုင်က ကောင်တာတစ်ခုလိုပါ။ Customer (mobile app၊ website ဒါမှမဟုတ် တခြား program) က menu ထဲက ဟင်းတစ်ခု (URL) နဲ့ ဘာလုပ်ချင်လဲ (method) ကို ပြောပါတယ်။ ကောင်တာက အော်ဒါကို စစ်ပြီး ပန်းကန် (JSON) နဲ့ ရလဒ်ကို ပြောတဲ့ စာကဒ်တစ်ခု (status code) ကို ပြန်ပေးပါတယ်။
ဥပမာ GET /api/users/1 က "user နံပါတ် ၁ ကို ပြပါ"၊ POST /api/users က "user အသစ် ဖန်တီးပါ" လို့ ပြောတာပါ။ Customer က မီးဖိုချောင်ထဲ ဘာဖြစ်နေလဲ မသိဘဲ ကောင်တာရဲ့ စည်းကမ်းကိုပဲ သိဖို့ လိုပါတယ်။ ဒီ project မှာ အဲဒီ ကောင်တာကို Python နဲ့ ဆောက်ပါမယ်။
Problem → Why → Solution
ပြဿနာ: အရာအားလုံးကို လုပ်တဲ့ route တစ်ခု
API ပထမဆုံးရေးတဲ့အခါ route function တစ်ခုထဲမှာ body ဖတ်တာ၊ SQL ရေးတာ၊ response ပြန်တာ အားလုံးကို ထည့်ချင်ပါတယ်။ အောက်က code က client က email မပို့ရင် KeyError နဲ့ 500 Internal Server Error ဖြစ်ပါတယ်။ f-string နဲ့ SQL တည်ဆောက်ထားလို့ name ထဲမှာ quote ပါတဲ့ user က database ကို ဖျက်တဲ့ SQL ကိုတောင် run စေနိုင်ပါတယ်။
အောင်မြင်ရင်လည်း 201 Created နဲ့ user object အစား 200 နဲ့ "ok" စာသားပဲ ပြန်လို့ client က id အသစ်ကို မသိနိုင်ပါဘူး။ ပြီးတော့ ဒီ function ကို test လုပ်ဖို့ server နဲ့ database အစစ် လိုပါတယ်။
@app.post("/api/users")
def create():
data = request.json
db.execute(f"INSERT INTO users VALUES ('{data['name']}', '{data['email']}')")
return "ok" # 200, plain text, no id - and KeyError if email is missingဘာကြောင့် ပြဿနာဖြစ်တာလဲ
Route တစ်ခုက HTTP၊ validation၊ business rule နဲ့ storage ဆိုတဲ့ အလုပ်လေးခုကို တစ်ပြိုင်နက် လုပ်နေပါတယ်။ အပိုင်းတစ်ခုခု ပြောင်းရင် ကျန်တာတွေပါ ထိခိုက်ပြီး အမှားတိုင်းက client အတွက် အသုံးမဝင်တဲ့ 500 အဖြစ်ပဲ ရောက်ပါတယ်။ Client က ဘာမှားလဲ၊ ဘယ်လို ပြင်ရမလဲ မသိနိုင်ပါဘူး။
Core concept: resource၊ method၊ status code၊ layer
REST design က noun နဲ့ verb ကို ခွဲထားပါတယ်။ URL က resource (noun) ကို နာမည်ပေးပါတယ်။ /api/users က user collection ဖြစ်ပြီး /api/users/1 က user တစ်ယောက်ပါ။ HTTP method က လုပ်ချင်တဲ့ verb ကို ပြောပါတယ်။ ဒါကြောင့် /api/createUser လို URL မရေးဘဲ POST /api/users လို့ ရေးပါတယ်။
| Method | အဓိပ္ပာယ် | ထပ်ခေါ်ရင် |
|---|---|---|
| GET | ဖတ်တယ်၊ ဘာမှ မပြောင်းဘူး | ရလဒ်တူ (safe) |
| POST | Collection ထဲ အသစ်ဖန်တီး | Record နှစ်ခု ဖြစ်နိုင် |
| PUT | Resource တစ်ခုလုံးကို အစားထိုး | ရလဒ်တူ (idempotent) |
| PATCH | ပေးလိုက်တဲ့ field တွေကိုပဲ ပြင် | Design ပေါ် မူတည် |
| DELETE | Resource ကို ဖျက် | ဖျက်ပြီးသားပဲ (idempotent) |
"ထပ်ခေါ်ရင်" column က ဘာကြောင့် အရေးကြီးလဲ။ Mobile network တွေမှာ request တစ်ခုက server ဆီ ရောက်ပြီး response ပဲ ပျောက်သွားတတ်ပါတယ်။ Client က ပြန်ကြိုးစားတဲ့အခါ PUT ဒါမှမဟုတ် DELETE ဆိုရင် ဒုတိယအကြိမ်က server ရဲ့ အခြေအနေကို ထပ်မပြောင်းလို့ ဘေးကင်းပါတယ်။ POST ကို retry လုပ်ရင်တော့ user နှစ်ယောက် ဖန်တီးမိနိုင်လို့ အဲဒီကို သတိထားပြီး design လုပ်ရပါတယ်။
Status code က ရလဒ်ကို စက်တွေဖတ်လို့ရအောင် ပြောပါတယ်။ 2xx က အောင်မြင်တာ၊ 4xx က client ဘက်က အမှား၊ 5xx က server ဘက်က အမှားပါ။ ဒီ project မှာ သုံးတာတွေက 200 OK၊ 201 Created (POST အောင်မြင်)၊ 204 No Content (DELETE အောင်မြင်ပြီး body မရှိ)၊ 400 Bad Request (body မမှန်)၊ 404 Not Found၊ 405 Method Not Allowed နဲ့ challenge အတွက် 409 Conflict (email ထပ်နေ) တို့ပါ။ Error body တွေကိုလည်း {"error": ...} ဆိုတဲ့ shape တစ်မျိုးတည်းနဲ့ ပြန်ပေးလို့ client က error ကို နေရာတစ်ခုတည်းမှာ ကိုင်တွယ်နိုင်ပါတယ်။
နောက်ဆုံးအနေနဲ့ code ကို layer လေးခု ခွဲပါတယ်။ Routing က method နဲ့ path ကို function တစ်ခုဆီ ပို့ပါတယ်။ Validation က body ကို စစ်ပါတယ်။ Handler က rule တွေကို အကောင်အထည်ဖော်ပြီး (status, body) ကို ပြန်ပေးပါတယ်။ Data layer က သိမ်းဆည်းပါတယ်။ Handler တွေက HTTP ကို မသိလို့ server မပါဘဲ function ခေါ်ရုံနဲ့ test လုပ်နိုင်ပါတယ်။
- Method + path ကို handler ဆီ route
- Request body ကို validate
- Rule ကို apply ပြီး data ကို ပြင်
- (status, JSON body) ကို ပြန်ပေး
Step တိုင်းက 4xx နဲ့ အစောပိုင်း ပြန်လှည့်နိုင်ပါတယ်။ Data ကို ပြင်တာက နောက်ဆုံး check ပြီးမှပဲ ဖြစ်ပါတယ်။
အခြေခံ ပုံစံ
def create_item(body):
errors = validate(body)
if errors:
return 400, {"error": "validation failed", "fields": errors}
item = store.add(body)
return 201, {"data": item}
def get_item(item_id):
item = store.find(item_id)
if item is None:
return 404, {"error": f"item {item_id} not found"}
return 200, {"data": item}Handler တိုင်းက (status code, JSON-ready body) ကို ပြန်ပေးပါတယ်။ Error ဖြစ်တဲ့ case တွေကို အရင်စစ်ပြီး အောင်မြင်တဲ့ လမ်းကို နောက်ဆုံးမှ ရေးပါတယ်။
Framework မပါတဲ့ users API
ဒီ runnable example မှာ framework လုံးဝ မပါပါဘူး။ handle() function က Flask လုပ်ပေးတဲ့ အလုပ်ဖြစ်တဲ့ method နဲ့ path ကို function တစ်ခုနဲ့ တွဲပေးတာကို လုပ်ပါတယ်။ ဒါကြောင့် ဘယ်နေရာမှာမဆို install မလုပ်ဘဲ run လို့ရပြီး framework တစ်ခုက သင့်အတွက် ဘာလုပ်ပေးလဲဆိုတာ ရှင်းရှင်း မြင်ရပါတယ်။ call() က client လိုပဲ request ပို့ပြီး status နဲ့ JSON ကို print ထုတ်ပါတယ်။
Response တိုင်းကို shape တူအောင် ထားပါ။ get_user() က အောင်မြင်ရင် dict၊ မအောင်မြင်ရင် tuple ပြန်ရင် caller တိုင်းက type ကို လိုက်စစ်နေရပါတယ်။ မရှိတဲ့ user ကို ဖျက်တာကလည်း success လို့ မပြန်သင့်ပါဘူး။ ဒီမှာ handler တိုင်းက (status, body) ကို အမြဲ ပြန်ပေးပါတယ်။
import json
# ---- data layer: an in-memory "table" (a database in a real app) ----
users = {
1: {"id": 1, "name": "Aung Kyaw", "email": "aung@example.com"},
2: {"id": 2, "name": "Su Su", "email": "susu@example.com"},
}
next_id = 3
# ---- validation: never trust the request body ----
def validate_user(body):
errors = {}
name, email = body.get("name"), body.get("email")
if not isinstance(name, str) or not name.strip():
errors["name"] = "is required"
if not isinstance(email, str) or "@" not in email:
errors["email"] = "must be an email address"
return errors
# ---- handlers: each returns (status code, JSON-ready body) ----
def list_users():
return 200, {"data": list(users.values()), "count": len(users)}
def get_user(user_id):
if user_id not in users:
return 404, {"error": f"user {user_id} not found"}
return 200, {"data": users[user_id]}
def create_user(body):
global next_id
errors = validate_user(body)
if errors:
return 400, {"error": "validation failed", "fields": errors}
user = {"id": next_id, "name": body["name"].strip(), "email": body["email"]}
users[next_id] = user
next_id += 1
return 201, {"data": user}
def delete_user(user_id):
if users.pop(user_id, None) is None:
return 404, {"error": f"user {user_id} not found"}
return 204, None
# ---- routing: method + path -> handler (Flask does this part for you) ----
def handle(method, path, body=None):
parts = path.strip("/").split("/") # "/api/users/1" -> [..., "1"]
if parts[:2] != ["api", "users"] or len(parts) > 3:
return 404, {"error": "no such endpoint"}
if len(parts) == 2:
routes = {"GET": list_users, "POST": lambda: create_user(body or {})}
elif parts[2].isdigit():
uid = int(parts[2])
routes = {"GET": lambda: get_user(uid), "DELETE": lambda: delete_user(uid)}
else:
return 404, {"error": "user id must be a number"}
if method not in routes:
return 405, {"error": f"{method} is not allowed on {path}"}
return routes[method]()
def call(method, path, body=None):
status, payload = handle(method, path, body)
line = f"{method} {path} -> {status}"
if payload is not None:
line += " " + json.dumps(payload)
print(line)
call("GET", "/api/users/1")
call("POST", "/api/users", {"name": "Min Min", "email": "minmin@example.com"})
call("POST", "/api/users", {"name": " ", "email": "no-at-sign"})
call("DELETE", "/api/users/2")
call("DELETE", "/api/users/2")
call("PUT", "/api/users")
status, payload = handle("GET", "/api/users")
print("GET /api/users ->", status, "count =", payload["count"])Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Validation returns errors, not exceptions
def validate_user(body):Field တစ်ခုစီရဲ့ ပြဿနာကို dictionary ထဲ စုလို့ client က တစ်ကြိမ်တည်းနဲ့ အမှားအားလုံးကို သိပါတယ်။ isinstance() check က name ကို 123 လို number အဖြစ် ပို့တာကိုလည်း ဖမ်းပါတယ်။
- 201 with the new resource
return 201, {"data": user}POST အောင်မြင်ရင် 201 Created နဲ့ id ပါတဲ့ user ကို ပြန်ပေးလို့ client က နောက် request တွေမှာ /api/users/3 ကို သုံးနိုင်ပါတယ်။
- Honest DELETE
if users.pop(user_id, None) is None:pop() က key မရှိရင် default None ကို ပြန်ပါတယ်။ ဒါကြောင့် ပထမ DELETE က 204၊ ဒုတိယ DELETE က 404 ရပါတယ်။ User 2 က နှစ်ခါလုံး ဖျက်ပြီးသား အခြေအနေပဲ ဖြစ်လို့ DELETE က idempotent ဖြစ်နေဆဲပါ။
- A route table per path
routes = {"GET": list_users, "POST": lambda: create_user(body or {})}Path တစ်ခုစီအတွက် ခွင့်ပြုထားတဲ့ method တွေကို dictionary နဲ့ ဖော်ပြပါတယ်။ lambda က handler ကို ချက်ချင်း မခေါ်ဘဲ method ကိုက်မှ ခေါ်အောင် ချိန်ထားပါတယ်။
- 405, not 404
if method not in routes:Path က ရှိပေမယ့် method ကို ခွင့်မပြုရင် 405 ပါ။ 404 ဆိုရင် URL မှားတယ်လို့ client က ထင်သွားပါလိမ့်မယ်။
- Real JSON on the wire
line += " " + json.dumps(payload)json.dumps() က double quote ပါတဲ့ JSON စစ်စစ်ကို ထုတ်ပါတယ်။ Original က print(dict) နဲ့ Python repr ({'id': 1}) ကို ပြခဲ့ပြီး အဲဒါက JSON မဟုတ်ပါဘူး။
GET /api/users/1 -> 200 {"data": {"id": 1, "name": "Aung Kyaw", "email": "aung@example.com"}}
POST /api/users -> 201 {"data": {"id": 3, "name": "Min Min", "email": "minmin@example.com"}}
POST /api/users -> 400 {"error": "validation failed", "fields": {"name": "is required", "email": "must be an email address"}}
DELETE /api/users/2 -> 204
DELETE /api/users/2 -> 404 {"error": "user 2 not found"}
PUT /api/users -> 405 {"error": "PUT is not allowed on /api/users"}
GET /api/users -> 200 count = 2အလားတူ API ကို Flask ပေါ်မှာ
Handler တွေက (status, body) ကိုပဲ ပြန်ပေးလို့ Flask ကို ပြောင်းသုံးတဲ့အခါ ပြင်ရတာ နည်းပါတယ်။ handle() ကို ဖယ်ပြီး route decorator တွေနဲ့ အစားထိုးရုံပါ။ Flask က <int:user_id> converter နဲ့ number မဟုတ်တဲ့ id ကို 404 ပေးပြီး route မရှိတဲ့ method ကို 405 အလိုလို ပေးပါတယ်။ Route function က dict ပြန်ရင် JSON response အဖြစ် ပြောင်းပေးပါတယ်။
အောက်က snippet က handler တွေကို users_service.py module ထဲ ရွှေ့ထားပြီလို့ ယူဆပါတယ်။ Flask project တစ်ခုထဲမှာ run ရမှာမို့ ဒီ lesson ထဲမှာ execute မလုပ်ပါဘူး။
# app.py - the same endpoints on Flask (pip install flask)
# Run locally with: flask --app app run --debug (never --debug in production)
from flask import Flask, request
from users_service import create_user, delete_user, get_user, list_users
app = Flask(__name__)
@app.get("/api/users")
def users_index():
status, body = list_users()
return body, status # Flask turns a dict into a JSON response
@app.get("/api/users/<int:user_id>") # a non-number id is a 404 automatically
def users_show(user_id):
status, body = get_user(user_id)
return body, status
@app.post("/api/users")
def users_create():
payload = request.get_json(silent=True) or {} # bad or missing JSON -> {}
status, body = create_user(payload)
return body, status
@app.delete("/api/users/<int:user_id>")
def users_delete(user_id):
status, body = delete_user(user_id)
return ("", 204) if status == 204 else (body, status)
# A test without starting a server:
# client = app.test_client()
# resp = client.post("/api/users", json={"name": "Min", "email": "min@example.com"})
# assert resp.status_code == 201 and resp.get_json()["data"]["id"] == 3လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Production API တစ်ခုမှာ in-memory dictionary အစား SQLite ဒါမှမဟုတ် PostgreSQL လို database ကို parameterized query ဒါမှမဟုတ် SQLAlchemy လို ORM နဲ့ သုံးပါတယ်။ Request တိုင်းမှာ token နဲ့ authentication လုပ်ပြီး ဒီ user က ဒီ record ကို ပြင်ခွင့်ရှိလား (authorization) စစ်ပါတယ်။ User ထောင်ချီရှိတဲ့ collection တွေကို ?page=2&limit=50 လို pagination နဲ့ ပြန်ပေးပြီး client အဟောင်းတွေ မပျက်အောင် /api/v1/ လို version ကို URL ထဲ ထည့်လေ့ရှိပါတယ်။
Team တွေက endpoint တွေကို OpenAPI document နဲ့ ဖော်ပြပြီး frontend developer တွေက အဲဒီ contract ကို ကြည့်ကာ အလုပ်လုပ်ပါတယ်။ Flask ရဲ့ built-in server က development အတွက်ပဲ ဖြစ်လို့ production မှာ Gunicorn လို WSGI server နောက်မှာ run ပါတယ်။ Load balancer က စစ်ဖို့ /health endpoint တစ်ခုလည်း ထားလေ့ရှိပါတယ်။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
အရာအားလုံးကို 200 နဲ့ ပြန်တာ
Error ကို body ထဲမှာ {"status": "error"} လို့ ရေးပြီး 200 နဲ့ ပြန်ရင် client library တွေ၊ monitoring tool တွေနဲ့ cache တွေက အောင်မြင်တယ်လို့ ထင်ပါတယ်။ Error တိုင်းမှာ 4xx ဒါမှမဟုတ် 5xx code ကို သုံးပါ။
Request body ကို ယုံကြည်တာ
body["email"] ကို တိုက်ရိုက် ဖတ်ရင် field မပါတဲ့ request က KeyError ဖြစ်ပြီး 500 ရပါတယ်။ Client က ပို့တာ ဘာမဆို ဖြစ်နိုင်လို့ field ရှိမရှိ၊ type မှန်မမှန် အရင်စစ်ပြီး 400 နဲ့ ဖြေပါ။
SQL ကို f-string နဲ့ တည်ဆောက်တာ
User input ကို SQL string ထဲ ကပ်ထည့်ရင် SQL injection ဖြစ်နိုင်ပါတယ်။ cursor.execute("INSERT INTO users VALUES (?, ?)", (name, email)) လို parameterized query ကို အမြဲ သုံးပါ။
Debug mode ကို production မှာ ဖွင့်ထားတာ
Flask ရဲ့ debug mode က browser ထဲကနေ Python code run လို့ရတဲ့ interactive debugger ကို ဖွင့်ပေးပါတယ်။ Internet ပေါ်မှာ ဒါကို ဖွင့်ထားတာက server ကို အခြားသူ လက်ထဲ အပ်လိုက်သလိုပါပဲ။
Mini challenge
PATCH /api/users/<id> ကို ထည့်ပါ
ပေးလိုက်တဲ့ field တွေကိုပဲ ပြင်တဲ့ update_user(user_id, body) handler ကို ရေးပါ။ Example ထဲက handler တွေလိုပဲ (status, body) ကို ပြန်ပေးရပါမယ်။
- User မရှိရင် 404 ပြန်ပါ
- Body အလွတ် ဒါမှမဟုတ် name/email မဟုတ်တဲ့ field ပါရင် 400 ပြန်ပါ
- Name အလွတ် ဒါမှမဟုတ် @ မပါတဲ့ email ဆိုရင် 400 ပြန်ပါ
- တခြား user သုံးပြီးသား email ဆိုရင် 409 Conflict ပြန်ပါ
- အောင်မြင်ရင် 200 နဲ့ ပြင်ပြီးသား user ကို ပြန်ပေးပါ
users = {
1: {"id": 1, "name": "Aung Kyaw", "email": "aung@example.com"},
2: {"id": 2, "name": "Su Su", "email": "susu@example.com"},
}
EDITABLE = {"name", "email"}
def update_user(user_id, body):
"""PATCH /api/users/<id>"""
# TODO: 404 if the user is missing
# TODO: 400 if body is empty or has keys outside EDITABLE
# TODO: 400 for an empty name or an email without "@"
# TODO: 409 if another user already owns the email
# TODO: apply the changes and return 200 with the user
...
# TODO: call update_user for each case and print the (status, body) tuplesရလဒ်: Name ပြောင်းတာက 200၊ user 9 က 404၊ role field က 400၊ Su Su ရဲ့ email ကို user 1 ယူဖို့ ကြိုးစားတာက 409၊ Su Su ကိုယ်တိုင် email ပြောင်းတာက 200 ရပါတယ်။
အရိပ်အမြွက် ကြည့်ရန်
set(body) - EDITABLE က ခွင့်မပြုတဲ့ key တွေကို ပေးပါတယ်။ Email ထပ်နေလား စစ်ဖို့ any(u["email"] == new_email and u["id"] != user_id for u in users.values()) ကို သုံးပါ။ Check အားလုံး ပြီးမှ users[user_id].update(body) ကို ခေါ်ပါ။
အဖြေ ကြည့်ရန်
users = {
1: {"id": 1, "name": "Aung Kyaw", "email": "aung@example.com"},
2: {"id": 2, "name": "Su Su", "email": "susu@example.com"},
}
EDITABLE = {"name", "email"}
def update_user(user_id, body):
"""PATCH /api/users/<id>: change only the fields that were sent."""
if user_id not in users:
return 404, {"error": f"user {user_id} not found"}
unknown = set(body) - EDITABLE
if not body or unknown:
return 400, {"error": f"send name and/or email only, got {sorted(unknown)}"}
if "name" in body and not str(body["name"]).strip():
return 400, {"error": "name cannot be empty"}
if "email" in body:
if "@" not in str(body["email"]):
return 400, {"error": "email must contain @"}
taken = any(u["email"] == body["email"] and u["id"] != user_id
for u in users.values())
if taken:
return 409, {"error": "email already used by another user"}
users[user_id].update(body)
return 200, {"data": users[user_id]}
print(update_user(1, {"name": "Aung Kyaw Moe"}))
print(update_user(9, {"name": "Nobody"}))
print(update_user(1, {"role": "admin"}))
print(update_user(1, {"email": "susu@example.com"}))
print(update_user(2, {"email": "su.su@example.com"}))Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- URL က resource (noun) ဖြစ်ပြီး HTTP method က action (verb) ပါ
- 201၊ 204၊ 400၊ 404၊ 405၊ 409 ကို ဖြစ်ရပ်နဲ့ ကိုက်အောင် ရွေးပြီး error body shape ကို တစ်မျိုးတည်း ထားပါ
- Request body ကို ဘယ်တော့မှ မယုံဘဲ field တစ်ခုစီကို validate လုပ်ပါ
- Handler တွေက (status, body) ပြန်ရင် server မပါဘဲ test လုပ်ပြီး Flask နဲ့ လွယ်လွယ် ချိတ်နိုင်ပါတယ်
Requests — User Guide — Requests