0
0
Testing Fundamentalstesting~15 mins

Request and response validation in Testing Fundamentals - Build an Automation Script

Choose your learning style9 modes available
Validate API request and response for user creation
Preconditions (2)
Step 1: Send a POST request to /users with JSON body {"name": "John Doe", "email": "john@example.com"}
Step 2: Check the HTTP status code is 201
Step 3: Verify the response body contains the created user's id, name, and email
Step 4: Verify the response email matches the request email
✅ Expected Result: User is created successfully with status 201 and response body contains correct user data
Automation Requirements - Python requests with unittest
Assertions Needed:
Assert HTTP status code is 201
Assert response JSON has keys 'id', 'name', 'email'
Assert response 'email' equals request 'email'
Best Practices:
Use setup method to prepare test data
Use clear and descriptive assertion messages
Handle possible exceptions during request
Automated Solution
Testing Fundamentals
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.

Common Mistakes - 3 Pitfalls
Not checking the HTTP status code before parsing JSON
Hardcoding URLs or data inside the test method
Not handling exceptions from the request call
Bonus Challenge

Now add data-driven testing with 3 different user inputs to validate user creation for multiple cases

Show Hint