Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingbeginner

API Basics (Enhanced)

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Python API & JSON Visual Guide
Python app, HTTP request, API server, JSON response flow ကို တစ်ကြောင်းတည်းမြင်နိုင်ပါတယ်။

🐍 Lesson 20: API Basics

1. API ဆိုတာဘာလဲ?

မြန်မာ → API (Application Programming Interface) ဆိုတာ program တစ်ခုနဲ့ တစ်ခု ဆက်သွယ်ဖို့ အသုံးပြုတဲ့ စည်းမျဉ်းစနစ် ဖြစ်တယ်။ ဥပမာ – မင်း Python program ကနေ weather API ကိုခေါ်ပြီး မိုးလေဝသ အချက်အလက်တွေ ယူနိုင်တယ်။

English → An API is a set of rules that allows one program to interact with another. For example, you can use a weather API to fetch live weather data into your Python program.

2. API Types

  • REST API → Most common, uses HTTP methods (GET, POST, PUT, DELETE)
  • SOAP API → XML-based, older style
  • GraphQL → Flexible query-based API

3. အကျဉ်းချုပ်

✅ API = bridge between programs

✅ REST API is most common (GET, POST, PUT, DELETE)

✅ Use requests library in Python

✅ Always check status codes

python
# ===== 1. Simple API Request =====
import requests

response = requests.get("https://api.github.com")
print(f"Status Code: {response.status_code}")  # 200 = success
print(f"Response: {response.json()}")

# ===== 2. GET Request Example =====
print(f"\n===== GET Request =====")

url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(f"Title: {data['title']}")

# ===== 3. POST Request Example =====
print(f"\n===== POST Request =====")

url = "https://jsonplaceholder.typicode.com/posts"
payload = {"title": "Sai's Post", "body": "Hello API", "userId": 1}

response = requests.post(url, json=payload)
print(f"Created: {response.json()}")

# ===== 4. HTTP Status Codes =====
print(f"\n===== Status Codes =====")
print("200 → Success")
print("201 → Created")
print("400 → Bad request")
print("401 → Unauthorized")
print("404 → Not found")
print("500 → Server error")

# ===== 5. Error Handling =====
print(f"\n===== Error Handling =====")

try:
    r = requests.get("https://jsonplaceholder.typicode.com/invalid")
    r.raise_for_status()
except requests.exceptions.HTTPError as e:
    print(f"HTTP Error: {e}")
You should see
Status Code: 200 Response: {'current_user_url': 'https://api.github.com/user', ...} ===== GET Request ===== Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit ===== POST Request ===== Created: {'title': "Sai's Post", 'body': 'Hello API', 'userId': 1, 'id': 101} ===== Status Codes ===== 200 → Success 201 → Created 400 → Bad request 401 → Unauthorized 404 → Not found 500 → Server error ===== Error Handling ===== HTTP Error: 404 Client Error: Not Found
API Basics (Enhanced) | Thuta Learning