Validate API request and response for user creation
Preconditions (2)
✅ Expected Result: User is created successfully with status 201 and response body contains correct user data
import unittest import requests class TestUserCreation(unittest.TestCase): def setUp(self): self.url = "https://api.example.com/users" self.user_data = {"name": "John Doe", "email": "john@example.com"} def test_create_user(self): try: response = requests.post(self.url, json=self.user_data) except requests.exceptions.RequestException as e: self.fail(f"Request failed: {e}") self.assertEqual(response.status_code, 201, "Expected status code 201 for user creation") json_response = response.json() self.assertIn("id", json_response, "Response JSON should contain 'id'") self.assertIn("name", json_response, "Response JSON should contain 'name'") self.assertIn("email", json_response, "Response JSON should contain 'email'") self.assertEqual(json_response["email"], self.user_data["email"], "Response email should match request email") if __name__ == "__main__": unittest.main()
The setUp method prepares the API URL and user data before each test.
The test method test_create_user sends a POST request with the user data JSON.
We catch exceptions to fail the test if the request fails.
Assertions check the HTTP status code is 201, meaning created successfully.
We verify the response JSON contains the keys id, name, and email.
Finally, we assert the email in the response matches the email sent in the request.
This ensures the API request and response are validated correctly.
Now add data-driven testing with 3 different user inputs to validate user creation for multiple cases
request and response validation in software testing?status_code and it should be compared with == for equality.assert response.status_code == 200, which is syntactically correct and logically valid.response = api_call() assert response.json()['success'] == True assert response.status_code == 201
response.json()['success'] == True will pass because success is True.response.status_code == 201 will fail because the actual status code is 200, not 201.assert response.json()['data'] != None
response.json()['data']. If 'data' key is missing, KeyError occurs.error. Which assertion correctly checks that if error exists, its value is a non-empty string?Pass the test and this pattern moves unknown