Python pytest examples for validating JSON API responses
This article presents a series of pytest‑based Python examples that demonstrate how to validate various aspects of JSON responses from an API, including field presence, nested structures, size, list length, uniqueness, pattern matching, date ranges, numeric ranges, element order, and field types.
1. Validate JSON data structure: send a GET request to an API endpoint and assert that the response JSON contains specific top‑level fields.
import requests
import pytest
def test_json_structure():
url = "https://api.example.com/data"
response = requests.get(url)
data = response.json()
assert "id" in data and "name" in data, "Expected fields not found in JSON response."2. Validate nested JSON structure: ensure that a nested object and its sub‑fields exist in the response.
def test_nested_json():
url = "https://api.example.com/data"
response = requests.get(url)
data = response.json()
assert "user" in data and "details" in data["user"], "Nested structure not found."3. Validate JSON size: check that the number of top‑level items falls within an expected range.
def test_json_size():
url = "https://api.example.com/data"
response = requests.get(url)
data = response.json()
assert 10 <= len(data) <= 20, "JSON size is out of the expected range."4. Validate list length inside JSON: verify that a specific list field contains the expected number of elements.
def test_list_length():
url = "https://api.example.com/data"
response = requests.get(url)
data = response.json()
assert len(data["items"]) == 5, "List length does not match the expected value."5. Validate uniqueness of a field across items: ensure that all "id" values are unique.
def test_unique_values():
url = "https://api.example.com/data"
response = requests.get(url)
data = response.json()
ids = [item["id"] for item in data]
assert len(ids) == len(set(ids)), "IDs are not unique."6. Validate pattern matching: confirm that a date field matches the YYYY‑MM‑DD format using a regular expression.
import re
def test_pattern_matching():
url = "https://api.example.com/data"
response = requests.get(url)
data = response.json()
pattern = r"^\d{4}-\d{2}-\d{2}$"
assert all(re.match(pattern, item["date"]) for item in data), "Date format does not match the expected pattern."7. Validate date range: check that each date in the response is not in the future.
from datetime import datetime
def test_date_range():
url = "https://api.example.com/data"
response = requests.get(url)
data = response.json()
today = datetime.now().date()
for item in data:
date_str = item["date"]
date_obj = datetime.strptime(date_str, "%Y-%m-%d").date()
assert date_obj <= today, "Date is in the future."8. Validate numeric range: ensure that a numeric field stays within 0‑100.
def test_numeric_range():
url = "https://api.example.com/data"
response = requests.get(url)
data = response.json()
for item in data:
value = item["value"]
assert 0 <= value <= 100, "Value is out of the expected range."9. Validate element order: confirm that the list of IDs is sorted in ascending order.
def test_element_order():
url = "https://api.example.com/data"
response = requests.get(url)
data = response.json()
ids = [item["id"] for item in data]
assert ids == sorted(ids), "Elements are not in ascending order."10. Validate field types: check that each "id" is an integer and each "name" is a string.
def test_field_types():
url = "https://api.example.com/data"
response = requests.get(url)
data = response.json()
for item in data:
assert isinstance(item["id"], int), "ID should be an integer."
assert isinstance(item["name"], str), "Name should be a string."All tests use the pytest framework; when run against a reachable API they output "PASSED" if the assertions hold, otherwise pytest provides detailed failure information.
Test Development Learning Exchange
Test Development Learning Exchange
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.