Master JSON API Testing in Python: 10 Essential Scenarios
This guide walks through ten practical Python examples for parsing, constructing, validating, updating, deleting, and iterating JSON data via HTTP requests, including custom date serialization and schema validation, each demonstrated with complete code and expected outcomes.
1. Parse JSON from an API
Retrieve a JSON string from an endpoint, decode it with json.loads, and assert that a specific key holds the expected value.
import requests
import json
def test_parse_json():
url = "https://api.example.com/data"
response = requests.get(url)
data = json.loads(response.text)
assert data["key"] == "value"Result: PASSED
2. Build a JSON object for POST
Create a Python dictionary, serialize it with json.dumps, set the appropriate Content-Type header, and send it as the request body.
import requests
import json
def test_build_json():
url = "https://api.example.com/data"
data = {"key": "value"}
headers = {"Content-Type": "application/json"}
response = requests.post(url, data=json.dumps(data), headers=headers)
assert response.status_code == 201Result: PASSED
3. Validate JSON structure
Fetch JSON from an API and verify that required fields and nested values exist.
import requests
import json
def test_validate_structure():
url = "https://api.example.com/data"
response = requests.get(url)
data = json.loads(response.text)
assert "key" in data and "value" in data["nested"]Result: PASSED
4. Update a JSON field with PUT
Modify a field in the JSON payload and send it via a PUT request.
import requests
import json
def test_update_json():
url = "https://api.example.com/data"
data = {"key": "new_value"}
headers = {"Content-Type": "application/json"}
response = requests.put(url, data=json.dumps(data), headers=headers)
assert response.status_code == 200Result: PASSED
5. Delete a JSON field with PATCH
Mark a field for removal by setting its value to None and send a PATCH request.
import requests
import json
def test_delete_json_field():
url = "https://api.example.com/data"
data = {"key": None} # mark field for deletion
headers = {"Content-Type": "application/json"}
response = requests.patch(url, data=json.dumps(data), headers=headers)
assert response.status_code == 200Result: PASSED
6. Handle nested JSON
Retrieve a JSON payload containing nested objects and assert a deep‑level value.
import requests
import json
def test_nested_json():
url = "https://api.example.com/data"
response = requests.get(url)
data = json.loads(response.text)
assert data["nested"]["sub_key"] == "sub_value"Result: PASSED
7. Iterate over a JSON array
Loop through an array of objects inside the JSON response and verify each object contains required fields.
import requests
import json
def test_iterate_json_array():
url = "https://api.example.com/data"
response = requests.get(url)
data = json.loads(response.text)
for item in data["items"]:
assert "name" in item and "value" in itemResult: PASSED
8. Serialize dates in JSON
Define a custom JSONEncoder that converts datetime objects to ISO‑8601 strings, then post the payload.
import requests
import json
from datetime import datetime
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
def test_serialize_date():
url = "https://api.example.com/data"
data = {"timestamp": datetime.now()}
headers = {"Content-Type": "application/json"}
response = requests.post(url, data=json.dumps(data, cls=DateTimeEncoder), headers=headers)
assert response.status_code == 201Result: PASSED
9. Convert between JSON and Python dict
Demonstrate round‑trip conversion: dict → JSON string → dict, confirming equality.
import json
def test_json_dict_conversion():
data = {"key": "value"}
json_str = json.dumps(data)
parsed_data = json.loads(json_str)
assert data == parsed_dataResult: PASSED
10. Validate JSON with jsonschema
Use the jsonschema library to ensure a JSON payload conforms to a predefined schema.
import requests
import json
import jsonschema
def test_json_schema_validation():
url = "https://api.example.com/data"
response = requests.get(url)
data = json.loads(response.text)
schema = {
"type": "object",
"properties": {
"key": {"type": "string"},
"nested": {"type": "object", "properties": {"sub_key": {"type": "string"}}}
},
"required": ["key", "nested"]
}
jsonschema.validate(instance=data, schema=schema)Result: PASSED
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
