Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟡 Advanced Python  ·  Lesson 28

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अर्थउदाहरण
GETData पढ़नाProducts की list
POSTकुछ नया बनानाOrder लगाना
PUT / PATCHबदलनाAddress बदलना
DELETEहटानाOrder cancel

इस lesson में हम sweet shop के लिए मुफ़्त CodingEasily practice API इस्तेमाल करेंगे: https://codingeasily.in/api/sweets/। यह असली है, key नहीं चाहिए और आपका data कभी store नहीं करता, इसलिए बेझिझक प्रयोग करें।

Terminal – install once (inside your venv)
pip install requests

आपकी पहली GET request

Python – get_products.py
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 : 200 type : application/json; charset=utf-8 items : 8 1. Kaju Katli ₹900/kg stock 25 2. Malai Ghewar ₹650/kg stock 8 3. Rasmalai ₹700/kg stock 12
  • status_code 200 का मतलब OK।
  • .json() जवाब को Python lists और dicts में बदलता है।
  • हमेशा timeout= दें; इसके बिना बंद server आपका program हमेशा के लिए रोक सकता है।

Query parameters

Strings जोड़कर URL न बनाएँ। params में dictionary दें, requests उसे सही encode करता है (spaces, Hindi, &)।

Python – params.py
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()])
https://codingeasily.in/api/sweets/?category=box ['Classic Gift Box', 'Assorted Gift Box'] ['Kaju Katli']

Status codes और errors

Codeअर्थProgram क्या करे
200 / 201OK / CreatedData इस्तेमाल करें
400 / 422आपकी request ग़लत हैServer का message user को दिखाएँ
401 / 403Login नहीं / अनुमति नहींLogin या सही API key माँगें
404नहीं मिला“not found” दिखाएँ
429बहुत ज़्यादा requestsरुककर दोबारा कोशिश
500–599Server की समस्याबाद में दोबारा; error log करें
Python – errors.py
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))
Malai Ghewar HTTP 404: Product not found
⚠️ requests अपने-आप 404 पर error नहीं देता

404 या 500 response भी “सफल” call माना जाता है। Data इस्तेमाल करने से पहले raise_for_status() बुलाएँ या r.ok जाँचें।

Timeouts व्यवहार में

Practice API ?delay= (milliseconds) से धीमा server बना सकता है। यहाँ server को 2 सेकंड चाहिए पर हम सिर्फ़ 1 इंतज़ार करते हैं:

Python – timeout.py
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)
Timed out after 1 second – show a friendly message instead of freezing with a longer timeout: 200

POST: JSON भेजना (order लगाना)

Python – post_order.py
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"])
201 Kaju Katli x0.5 ₹450 Classic Gift Box x2 ₹960 subtotal 1410 | discount 141 | delivery 0 | total 1269 422 {'name': 'Name must have at least 2 letters.', 'phone': 'Enter a valid 10-digit Indian mobile number.', 'items': 'Cart is empty.'}

Server सब कुछ जाँचता है और prices ख़ुद गिनता है – client सिर्फ़ ids और quantities भेजता है। असली e-commerce APIs ऐसे ही नकली prices से बचते हैं।

Headers, API keys और sessions

Python – session_headers.py
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"])
200 Rasmalai sent header: school-report/1.0 (contact@example.com)
🔐 API keys कभी code में न लिखें

Keys को environment variables या ऐसी .env file में रखें जो Git में commit न हो। GitHub पर डाली key bots कुछ ही मिनटों में ढूँढ लेते हैं।

अविश्वसनीय servers के लिए अपने-आप retry

Python – retries.py
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")
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

Python – low_stock_report.py
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())
Product,Stock,Status Kalakand,0,OUT OF STOCK Malai Ghewar,8,Reorder Rasmalai,12,Reorder

आम ग़लतियाँ

ग़लतीसुधार
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 callRate limits मानें; sleep, caching या batch endpoints

अभ्यास

  1. सभी milk sweets (?category=milk) rating के क्रम में छापें।
  2. input() से product id लेकर उसकी details या “not found” छापें।
  3. बिना coupon का delivery order लगाकर server से मिला delivery charge छापें।
  4. ₹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 से बाहर रखें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या requests Python में built-in है?
नहीं। pip install requests से install करें। Built-in विकल्प urllib.request है, जो चलता है पर ज़्यादा code माँगता है। requests Python की सबसे लोकप्रिय HTTP library है।
मुझे SSL error क्यों मिलता है?
आम तौर पर computer की date/time ग़लत होती है, office proxy HTTPS बीच में पकड़ता है, या certificates पुराने हैं। घड़ी ठीक करें या pip install --upgrade certifi से certifi update करें। असली projects में verify=False न लगाएँ।
requests या httpx?
साधारण scripts के लिए requests आसान और स्थिर है। httpx की API लगभग वैसी ही है और यह async तथा HTTP/2 भी देता है, जो एक साथ बहुत सारी requests में मदद करता है।
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
अगला topicPython Code Testing और Debugging आपकी प्रगति: 28 / 66 (42%) · Lesson 29 / 66 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें