Fundamentals 5 min read

10 Practical Python Examples for JSON Handling and the Requests Module

This article presents ten practical Python examples demonstrating how to create and parse JSON data, perform GET and POST requests, handle parameters, timeouts, cookies, custom headers, file downloads, authentication, and retry mechanisms using the Requests library, enhancing web development and API integration skills.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
10 Practical Python Examples for JSON Handling and the Requests Module

JSON data format and the Requests library are essential tools in modern programming; this guide provides ten hands‑on examples to illustrate their usage.

1️⃣ Create and parse JSON data

import json
# Create JSON data
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
json_data = json.dumps(data)  # Convert Python object to JSON string
print(json_data)  # Output: {"name": "John", "age": 30, "city": "New York"}

# Parse JSON data
json_string = '{"name": "Jane", "age": 28, "city": "San Francisco"}'
parsed_data = json.loads(json_string)  # Convert JSON string to Python dict
print(parsed_data)  # Output: {'name': 'Jane', 'age': 28, 'city': 'San Francisco'}

2️⃣ Send a GET request

import requests
response = requests.get('https://api.github.com')
print(response.status_code)  # e.g., 200
print(response.json())  # JSON response body
# Save the full response
with open('github_response.json', 'w') as f:
    json.dump(response.json(), f)

3️⃣ Send a GET request with parameters

params = {'q': 'Python requests', 'sort': 'stars'}
response = requests.get('https://api.github.com/search/repositories', params=params)
repos = response.json()['items']
for repo in repos[:5]:  # Print first 5 results
    print(repo['full_name'])

4️⃣ Send a POST request

payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = requests.post('http://httpbin.org/post', json=payload, headers=headers)
print(response.json())

5️⃣ Set a timeout

requests.get('http://example.com', timeout=5)  # Timeout after 5 seconds

6️⃣ Handle cookies

# Save cookies
response = requests.get('http://example.com')
cookies = response.cookies
# Send request with saved cookies
requests.get('http://example.com', cookies=cookies)

7️⃣ Customize HTTP headers

headers = {'User-Agent': 'My-Custom-UA'}
response = requests.get('http://httpbin.org/headers', headers=headers)
print(response.text)

8️⃣ Download a file

url = 'https://example.com/image.jpg'
response = requests.get(url)
with open('image.jpg', 'wb') as f:
    f.write(response.content)

9️⃣ Handle authentication

from requests.auth import HTTPBasicAuth
response = requests.get('https://example.com/api', auth=HTTPBasicAuth('username', 'password'))

🔟 Implement a retry mechanism

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
retry_strategy = Retry(
    total=3,
    status_forcelist=[429, 500, 502, 503, 504],
    backoff_factor=1,
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session = requests.Session()
session.mount('http://', adapter)
session.mount('https://', adapter)
response = session.get('https://example.com')

By working through these ten examples, readers gain a solid understanding of JSON manipulation and HTTP interactions with the Requests library, which can greatly improve productivity in web development and API integration tasks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonHTTPAPI
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.