Most Testers validate API responses inside a test framework. But do we know how to do it with just Python?
Scenario: Our API returns a JSON response after creating a user. We need to verify the status, the message, and the user details are exactly what we expected.
Here is the JSON response:
*JSON data:
*
{
"status": "success",
"message": "User created",
"user": {
"id": 101,
"name": "Ujjwal"
}
}
Here is the Python validation:
*Python code:
*
import json
with open("data.json", "r") as file:
data = json.load(file)
if data["status"] == "success" and data["user"]["name"] == "Ujjwal" and data["user"]["id"] == 101:
print("Validation Passed")
else:
print("Validation Failed")
Output:
Validation Passed
****Why this matters as a Tester:
Before we reach for requests or pytest, understanding how Python reads and validates JSON at the base level makes us a sharper tester. Every API assertion we write in a framework is doing exactly this under the hood.
Knowing the foundation makes us better at debugging when the framework gives us a result we did not expect.
GitHub: https://github.com/beinghumantester/Fundamental-Coding-Programs
Top comments (0)