← Back to Python Course | Chapter 13: Data Science & Web | Lesson 10 of 14

Python JSON और APIs

API किसी website का दिया मेन्यू है जिससे programs जानकारी माँग सकते हैं, और JSON वो साफ़-सुथरा format है जिसमें जवाब आता है। Python जवाब पढ़ता है और जो चाहिए वो निकाल लेता है।
Syntax
python
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?

python
# 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

python
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

python
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

python
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

python
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")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.