APIs और requests के साथ काम
API क्या है?
API (Application Programming Interface) से एक program internet पर दूसरे program से data या काम माँगता है। Weather app, weather API से आज का तापमान माँगता है; shop app server से products माँगता है और orders वापस भेजता है। ज़्यादातर web APIs HTTP इस्तेमाल करते हैं और JSON में जवाब देते हैं।
| HTTP method | अर्थ | उदाहरण |
|---|---|---|
| GET | Data पढ़ना | Products की list |
| POST | कुछ नया बनाना | Order लगाना |
| PUT / PATCH | बदलना | Address बदलना |
| DELETE | हटाना | Order cancel |
इस lesson में हम sweet shop के लिए मुफ़्त CodingEasily practice API इस्तेमाल करेंगे: https://codingeasily.in/api/sweets/। यह असली है, key नहीं चाहिए और आपका data कभी store नहीं करता, इसलिए बेझिझक प्रयोग करें।
pip install requests
आपकी पहली GET request
import requests
URL = "https://codingeasily.in/api/sweets/"
response = requests.get(URL, timeout=10)
print("status :", response.status_code)
print("type :", response.headers["Content-Type"])
products = response.json() # JSON text → Python list of dicts
print("items :", len(products))
for p in products[:3]:
print(f"{p['id']}. {p['name']:<14} ₹{p['price']}/{p['unit']} stock {p['stock']}")status_code200 का मतलब OK।.json()जवाब को Python lists और dicts में बदलता है।- हमेशा
timeout=दें; इसके बिना बंद server आपका program हमेशा के लिए रोक सकता है।
Query parameters
Strings जोड़कर URL न बनाएँ। params में dictionary दें, requests उसे सही encode करता है (spaces, Hindi, &)।
import requests
URL = "https://codingeasily.in/api/sweets/"
r = requests.get(URL, params={"category": "box"}, timeout=10)
print(r.url)
print([p["name"] for p in r.json()])
r = requests.get(URL, params={"q": "kaju"}, timeout=10)
print([p["name"] for p in r.json()])Status codes और errors
| Code | अर्थ | Program क्या करे |
|---|---|---|
| 200 / 201 | OK / Created | Data इस्तेमाल करें |
| 400 / 422 | आपकी request ग़लत है | Server का message user को दिखाएँ |
| 401 / 403 | Login नहीं / अनुमति नहीं | Login या सही API key माँगें |
| 404 | नहीं मिला | “not found” दिखाएँ |
| 429 | बहुत ज़्यादा requests | रुककर दोबारा कोशिश |
| 500–599 | Server की समस्या | बाद में दोबारा; error log करें |
import requests
URL = "https://codingeasily.in/api/sweets/"
def get_product(product_id):
try:
r = requests.get(URL, params={"id": product_id}, timeout=5)
r.raise_for_status() # turns 4xx/5xx into an exception
return r.json()
except requests.exceptions.HTTPError:
return f"HTTP {r.status_code}: {r.json().get('error')}"
except requests.exceptions.Timeout:
return "Server is too slow, try again"
except requests.exceptions.ConnectionError:
return "No internet connection"
print(get_product(2)["name"])
print(get_product(99))404 या 500 response भी “सफल” call माना जाता है। Data इस्तेमाल करने से पहले raise_for_status() बुलाएँ या r.ok जाँचें।
Timeouts व्यवहार में
Practice API ?delay= (milliseconds) से धीमा server बना सकता है। यहाँ server को 2 सेकंड चाहिए पर हम सिर्फ़ 1 इंतज़ार करते हैं:
import requests
URL = "https://codingeasily.in/api/sweets/"
try:
requests.get(URL, params={"delay": 2000}, timeout=1)
except requests.exceptions.Timeout:
print("Timed out after 1 second – show a friendly message instead of freezing")
r = requests.get(URL, params={"delay": 500}, timeout=5)
print("with a longer timeout:", r.status_code)POST: JSON भेजना (order लगाना)
import requests
URL = "https://codingeasily.in/api/sweets/"
order = {
"name": "Aarti Gupta",
"phone": "9829012345",
"items": [{"id": 1, "qty": 0.5}, {"id": 7, "qty": 2}],
"coupon": "SWEET10",
"mode": "pickup",
}
r = requests.post(URL, json=order, timeout=10) # json= sets the header and encodes for you
print(r.status_code)
data = r.json()
for item in data["items"]:
print(f" {item['name']:<17} x{item['qty']:<4} ₹{item['amount']}")
print("subtotal", data["subtotal"], "| discount", data["discount"], "| delivery", data["delivery"], "| total", data["total"])
bad = requests.post(URL, json={"name": "A", "phone": "12345", "items": []}, timeout=10)
print(bad.status_code, bad.json()["fields"])Server सब कुछ जाँचता है और prices ख़ुद गिनता है – client सिर्फ़ ids और quantities भेजता है। असली e-commerce APIs ऐसे ही नकली prices से बचते हैं।
Headers, API keys और sessions
import os
import requests
session = requests.Session() # reuses the connection → faster
session.headers.update({
"User-Agent": "school-report/1.0 (contact@example.com)",
"Authorization": f"Bearer {os.environ.get('MY_API_KEY', 'demo-key')}",
})
r = session.get("https://codingeasily.in/api/sweets/", params={"id": 3}, timeout=10)
print(r.status_code, r.json()["name"])
print("sent header:", r.request.headers["User-Agent"])Keys को environment variables या ऐसी .env file में रखें जो Git में commit न हो। GitHub पर डाली key bots कुछ ही मिनटों में ढूँढ लेते हैं।
अविश्वसनीय servers के लिए अपने-आप retry
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(total=3, backoff_factor=0.5, status_forcelist=[429, 500, 502, 503, 504])
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
session.mount("http://", HTTPAdapter(max_retries=retry))
try:
session.get("https://codingeasily.in/api/sweets/", params={"fail": 1}, timeout=5)
except requests.exceptions.RetryError:
print("Gave up after 3 retries – the server keeps returning 500")?fail=1 से practice API HTTP 500 लौटाता है। Session हार मानने से पहले बढ़ते इंतज़ार (0.5 s, 1 s, 2 s) के साथ 3 बार retry करता है।
Mini project: low-stock report
import csv
import requests
URL = "https://codingeasily.in/api/sweets/"
products = requests.get(URL, timeout=10).json()
low = sorted((p for p in products if p["stock"] < 15), key=lambda p: p["stock"])
with open("reorder.csv", "w", newline="", encoding="utf-8-sig") as f:
w = csv.writer(f)
w.writerow(["Product", "Stock", "Status"])
for p in low:
w.writerow([p["name"], p["stock"], "OUT OF STOCK" if p["stock"] == 0 else "Reorder"])
print(open("reorder.csv", encoding="utf-8-sig").read())आम ग़लतियाँ
| ग़लती | सुधार |
|---|---|
| Timeout नहीं | हमेशा timeout=10 (या tuple (3, 10)) |
| Status जाँचे बिना data इस्तेमाल | r.raise_for_status() या if r.ok: |
JSON APIs के लिए json= की जगह data= | json=payload इस्तेमाल करें |
| + और f-strings से URLs बनाना | params={...} इस्तेमाल करें |
| API key code / GitHub में | Environment variable या .env (git-ignored) |
| तेज़ loop में API call | Rate limits मानें; sleep, caching या batch endpoints |
अभ्यास
- सभी milk sweets (
?category=milk) rating के क्रम में छापें। input()से product id लेकर उसकी details या “not found” छापें।- बिना coupon का delivery order लगाकर server से मिला delivery charge छापें।
- ₹500 से कम के order पर coupon लगाकर coupon field का server error message छापें।
सारांश
requests.get(url, params=…, timeout=…)पढ़ता है;requests.post(url, json=…)JSON भेजता है।r.json()Python data देता है;r.status_code/raise_for_status()जाँचें।- Timeout और ConnectionError संभालें; अस्थिर servers के लिए retries जोड़ें।
- Sessions connection और headers दोबारा इस्तेमाल करते हैं; API keys code से बाहर रखें।
