Python JSON और APIs
In this page:
import requests
response = requests.get("api_url", params={"key": value})
data = response.json()
API क्या है?
एक API (Application Programming Interface) एक defined contract है जो अलग-अलग systems को programmatically data exchange करने देता है, सबसे आम तौर पर structured JSON लौटाकर जिसे कोई भी client language बिना किसी special tooling के parse कर सकती है।
उदाहरण: What is an API?
# APIs typically exchange data as JSON
import json
print(json.dumps({"status": "ok"}))
JSON Responses Parse करना
requests से data fetch करने के बाद, response पर .json() call करना raw JSON body को सीधे native Python dictionaries और lists में parse कर देता है, और आपको खुद response text पर json.loads() call करने के manual step से बचा देता है।
उदाहरण: Parsing JSON Responses
from unittest.mock import patch
import requests
with patch("requests.get") as mock_get:
mock_get.return_value.json.return_value = {"id": 1, "name": "Alex"}
response = requests.get("https://api.example.com/user/1")
print(response.json()) # parses the JSON body directly into a dict
Query Parameters
बहुत सारे APIs URL में जोड़े गए query parameters के ज़रिए results filter या customize करने का समर्थन करते हैं।
requests.get(url, params={...}) को कोई dictionary पास करना आपके लिए सही ढंग से encoded query string बना देता है, और special characters संभालता है जिन्हें वरना manually URL-escape करना पड़ता।
उदाहरण: Query Parameters
from unittest.mock import patch
import requests
with patch("requests.get") as mock_get:
mock_get.return_value.status_code = 200
requests.get("https://api.example.com/search", params={"q": "python"}) # builds the query string automatically
mock_get.assert_called_with("https://api.example.com/search", params={"q": "python"})
print("Query sent")
HTTP Errors संभालना
हर fail हुई request खुद exception raise नहीं करती -- requests की नज़र में 404 या 500 response भी normal रूप से ही लौटता है।
Response पर .raise_for_status() call करना status code failure बताने पर explicitly एक HTTPError raise करता है, जो चुपचाप bad data के साथ काम करने की बजाय API errors पकड़ने का भरोसेमंद तरीका है।
उदाहरण: Handling HTTP Errors
from unittest.mock import patch
import requests
with patch("requests.get") as mock_get:
mock_get.return_value.raise_for_status.side_effect = requests.exceptions.HTTPError("404")
response = requests.get("https://api.example.com/missing")
try:
response.raise_for_status() # explicitly raises for a failing status code
except requests.exceptions.HTTPError as e:
print("HTTP error:", e)
API Keys और Authorization
ज़्यादातर non-trivial public APIs को requests authenticate करने और rate limits लागू करने के लिए API key के लिए register करना पड़ता है।
वो key आमतौर पर या तो किसी custom request header के रूप में भेजी जाती है (जैसे Authorization: Bearer <key>) या query parameters में से एक के रूप में, यह इस बात पर निर्भर करता है कि specific API क्या document करती है।
उदाहरण: API Keys and Authorization
from unittest.mock import patch
import requests
with patch("requests.get") as mock_get:
mock_get.return_value.status_code = 200
headers = {"Authorization": "Bearer my-api-key"} # common way to send an API key
requests.get("https://api.example.com/data", headers=headers)
print("Sent with Authorization header")
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first:
- Python NumPy Introduction
- Python NumPy Arrays
- Python Pandas Introduction
- Python Pandas DataFrame
- Python Matplotlib Basics
- Python Data Visualization
- Python Statistics Module
- Python CSV & Data Analysis
- Python requests Module
- Python JSON & APIs
- Python Web Scraping Basics
- Python Flask Introduction
- Python Django Introduction
- Python MongoDB