Chapter 14: JSON, XML & HTTP Requests
Parse and generate JSON and XML, and interact with web APIs using HTTP requests.
Downloadchapter14.py
Objectives
- Load and dump JSON with the
json
module. - Parse XML using
xml.etree.ElementTree
. - Make HTTP GET and POST requests with
requests
. - Handle query parameters, headers and JSON bodies.
- Process API responses and error handling.
1. JSON Handling
Convert between JSON text and Python objects:
import json
data = {"user": "alice", "active": True, "roles": ["admin","user"]}
# serialize
text = json.dumps(data, indent=2)
# deserialize
obj = json.loads(text)
print(obj["roles"]) # ['admin', 'user']
2. XML Parsing
Use xml.etree.ElementTree
to read and navigate XML:
import xml.etree.ElementTree as ET
xml = "<root><item id='1'>Foo</item></root>"
root = ET.fromstring(xml)
for item in root.findall("item"):
print(item.get("id"), item.text) # 1 Foo
3. HTTP with requests
Install via pip install requests
. Make GET and POST:
import requests
# GET with params
resp = requests.get("https://api.example.com/data", params={"q":"python"})
print(resp.status_code, resp.json())
# POST JSON body
payload = {"name":"bob","age":30}
resp = requests.post("https://api.example.com/users", json=payload)
print(resp.status_code, resp.text)
Set headers and timeout:
headers = {"Authorization":"Bearer TOKEN"}
resp = requests.get("https://api.example.com/secure", headers=headers, timeout=5)
Exercises
- Read a JSON file, modify it and write it back.
- Parse an XML file of books and print titles published after 2000.
- Use
requests
to fetch GitHub user data (https://api.github.com/users/<username>
). - POST a JSON payload to a mock API (e.g.,
https://httpbin.org/post
) and display the response.