Introduction
Python me hum web se data lene aur bhejne ke liye APIs use karte hain. API = Application Programming Interface — ek tarika jisse do programs aapas me data exchange karte hain, usually HTTP ke through.
1️⃣ requests Library
Web se GET/POST requests bhejne ke liye sabse popular library hai requests. Isko install karne ke liye:
pip install requests
Example: Simple GET Request
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # 200 ka matlab OK
print(response.headers)
print(response.text[:200]) # sirf pehle 200 characters
Roman Hindi: Yahaan humne GitHub ke API par GET request bheji. Agar 200 mile to request successful hai — phir hum response ka content aur headers dekh sakte hain.
2️⃣ JSON Data ke sath kaam karna
Aaj kal APIs aksar JSON return karti hain. response.json() se hum JSON ko Python dictionary me convert kar lete hain.
import requests
url = "https://api.github.com/users/octocat"
response = requests.get(url)
data = response.json()
print(data["login"])
print(data["public_repos"])
print(data["followers"])
Roman Hindi: response.json() response ko parse karke Python dict banata hai — jisse hum keys se values nikal sakte hain (jaise username, repos, followers).
3️⃣ POST Request (Server ko data bhejna)
Form submit karna ya koi naya record create karna ho to POST request bhejte hain.
import requests
url = "https://httpbin.org/post"
data = {"name": "AIkiPadhai", "language": "Python"}
response = requests.post(url, json=data)
print(response.json())
Roman Hindi: Yahaan humne server ko JSON data bheja aur server ne wohi data wapas kar diya (test endpoint use kiya hai).
4️⃣ Error Handling aur Timeouts
Network unreliable ho sakta hai — isliye timeout aur exception handling zaroori hai.
import requests
try:
response = requests.get("https://example.com", timeout=5)
response.raise_for_status()
except requests.exceptions.Timeout:
print("Request time out ho gaya!")
except requests.exceptions.RequestException as e:
print("Error:", e)
Roman Hindi: timeout=5 se request 5 seconds se zyada wait nahi karegi. raise_for_status() 4xx/5xx responses ko exception me convert kar deta hai.
5️⃣ Mini Project: Live Weather Data Fetcher 🌦️
Ek simple program jo city ka current temperature fetch karega (Open-Meteo API use karke).
import requests
city = "New Delhi"
url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}"
geo_resp = requests.get(url, timeout=5)
geo_data = geo_resp.json()
lat = geo_data["results"][0]["latitude"]
lon = geo_data["results"][0]["longitude"]
weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true"
weather_data = requests.get(weather_url, timeout=5).json()
print(f"Current temperature in {city}: {weather_data['current_weather']['temperature']}°C")
Roman Hindi: Pehle hum city ka latitude/longitude nikal rahe hain (geocoding API se), phir us coordinates ke basis par current weather API se temperature le rahe hain — ye technique API chaining kehlati hai.
6️⃣ Bonus: Socket Programming Intro
Agar aap low-level network programs banana chahte ho (jaise chat server), to socket module use karte hain.
import socket
s = socket.socket()
s.connect(("example.com", 80))
print("Connected to example.com on port 80")
Roman Hindi: Ye code ek TCP connection establish karta hai server ke saath. Iske upar aap HTTP requests manually bhejne ya custom protocol banana seekh sakte ho.