เรียก API จริงด้วย requests
👋 อ่านฟรีทั้งหมดบน Aph's Blog — เนื้อหาภาษาไทย ทำตามทีละหน้าใน sidebar ได้เลย หากมีข้อเสนอแนะหรืออยากให้เพิ่มหัวข้อไหน บอกได้เสมอ
ดึงและส่งข้อมูลกับเว็บ/REST API ด้วยไลบรารี requests — ก้าวสู่การทำงานกับข้อมูลออนไลน์
แอปจริงจำนวนมากต้องคุยกับบริการอื่นผ่าน API เช่น ดึงสภาพอากาศ, อัตราแลกเปลี่ยน, ข้อมูลผู้ใช้ ไลบรารี requests ทำให้เรียก HTTP API ได้ง่าย หัวข้อนี้ปูพื้นก่อนไปสร้าง API เองในบท Web
GET — ดึงข้อมูล
python
import requests # pip install requests
resp = requests.get("https://jsonplaceholder.typicode.com/users/1")
print(resp.status_code) # 200 = สำเร็จ
data = resp.json() # แปลง JSON response เป็น dict
print(data["name"])
# ส่ง query parameters
resp = requests.get(
"https://api.example.com/search",
params={"q": "python", "limit": 10},
) # -> ...?q=python&limit=10เช็ค status code เสมอ
อย่าใช้ข้อมูลก่อนเช็คว่าสำเร็จ — status code บอกผลลัพธ์ (เจาะลึกใน บท Web)
| ช่วง | หมายถึง |
|---|---|
| 2xx | สำเร็จ (200 = OK, 201 = สร้างแล้ว) |
| 4xx | ผู้เรียกผิด (404 = ไม่พบ, 401 = ไม่ได้ล็อกอิน) |
| 5xx | เซิร์ฟเวอร์ผิดพลาด |
python
resp = requests.get(url)
resp.raise_for_status() # โยน error อัตโนมัติถ้าไม่ใช่ 2xx
data = resp.json()
# หรือเช็คเอง
if resp.status_code == 200:
data = resp.json()
else:
print(f"พลาด: {resp.status_code}")POST — ส่งข้อมูล + headers
python
resp = requests.post(
"https://api.example.com/users",
json={"name": "Aph", "age": 25}, # ส่ง body เป็น JSON
headers={"Authorization": "Bearer TOKEN123"},
timeout=10, # กันค้างถ้า server ไม่ตอบ
)
print(resp.status_code) # 201เช็ค status + ใส่ timeout เสมอ
อย่าเชื่อว่า request สำเร็จ — เช็ค status_code หรือใช้ raise_for_status() ก่อนใช้ข้อมูล และใส่ timeout เสมอ ไม่งั้นถ้า server ไม่ตอบ โปรแกรมจะค้างไม่มีกำหนด
สรุปหัวข้อนี้
- requests.get/post เรียก API; .json() แปลง response เป็น dict
- ส่ง query ด้วย params=, ส่ง body ด้วย json=, auth ผ่าน headers=
- status: 2xx สำเร็จ, 4xx ผู้เรียกผิด, 5xx เซิร์ฟเวอร์ผิด
- เช็ค status_code / raise_for_status() และใส่ timeout เสมอ
แบบฝึกหัด
1) ดึงข้อมูลจาก jsonplaceholder.typicode.com/users แล้ว print ชื่อทุกคน 2) เช็ค status_code ก่อนใช้ข้อมูล 3) ส่ง query params ไป endpoint ที่รองรับ 4) ลองเรียก URL ที่ไม่มีจริงแล้วจัดการ error ด้วย raise_for_status + try/except