A beginner API project needs more than a successful request. Start by checking how input behaves when a required value is absent, blank or the wrong type.
Here is a framework-independent Python example. It validates an incoming dictionary; HTTP handling belongs in the web framework around it.
def validate_name(payload):
name = payload.get("name")
if not isinstance(name, str) or not name.strip():
return {"error": "name must be a non-empty string"}, 400
return {"name": name.strip()}, 200
def test_name_validation():
for payload in ({}, {"name": ""}, {"name": " "}, {"name": 123}):
body, status = validate_name(payload)
assert status == 400
assert "error" in body
assert validate_name({"name": " Asha "}) == ({"name": "Asha"}, 200)
test_name_validation()
What the test demonstrates
A missing key and an empty string are different inputs, but both fail this example’s contract. Whitespace-only strings also fail. A valid string is trimmed. The tests document that decision, so a later change cannot silently accept an integer as a name.
What it does not cover
This function assumes the payload is already a dictionary. Your endpoint must separately handle invalid JSON, unexpected top-level types, authentication and authorization. Add a length limit based on the application’s requirements. Do not include real personal information in test fixtures.
Turn it into a project exercise
Connect this logic to a small form endpoint, map validation failures to the appropriate response, and add an integration test that sends an actual request. Keep the expected response explicit. AI-generated code should be checked against those expectations rather than judged only by whether it runs.
Published by ScholarLogic, an IT training provider in Bengaluru. Related learning path: Python training. This article was prepared with AI assistance.
Top comments (0)