0
0
Testing Fundamentalstesting~15 mins

API test automation concepts in Testing Fundamentals - Build an Automation Script

Choose your learning style9 modes available
Verify GET API returns correct user data
Preconditions (2)
Step 1: Send a GET request to https://api.example.com/users/123
Step 2: Check the response status code
Step 3: Check the response body contains user ID 123
Step 4: Check the response body contains user name 'John Doe'
✅ Expected Result: Response status code is 200, and response body contains user ID 123 and user name 'John Doe'
Automation Requirements - Python requests with unittest
Assertions Needed:
Assert response status code is 200
Assert response JSON contains 'id' with value 123
Assert response JSON contains 'name' with value 'John Doe'
Best Practices:
Use setup method to prepare test data if needed
Use clear and descriptive assertion messages
Handle possible exceptions during API call
Keep test independent and repeatable
Automated Solution
Testing Fundamentals
import unittest
import requests

class TestGetUserAPI(unittest.TestCase):
    def setUp(self):
        self.url = "https://api.example.com/users/123"

    def test_get_user(self):
        try:
            response = requests.get(self.url)
        except requests.exceptions.RequestException as e:
            self.fail(f"API request failed: {e}")

        self.assertEqual(response.status_code, 200, "Expected status code 200")

        try:
            data = response.json()
        except ValueError:
            self.fail("Response is not valid JSON")

        self.assertIn('id', data, "Response JSON should contain 'id'")
        self.assertEqual(data['id'], 123, "User ID should be 123")

        self.assertIn('name', data, "Response JSON should contain 'name'")
        self.assertEqual(data['name'], 'John Doe', "User name should be 'John Doe'")

if __name__ == '__main__':
    unittest.main()

The setUp method sets the API URL to keep the test clean and reusable.

The test method test_get_user sends a GET request to the API endpoint using requests.get. It catches exceptions to fail the test if the API call fails.

Assertions check that the status code is 200, meaning success.

Then it parses the JSON response and asserts the presence and correctness of the id and name fields.

Clear assertion messages help understand failures.

This test is independent and can be run repeatedly without side effects.

Common Mistakes - 4 Pitfalls
Not checking the response status code before parsing JSON
Hardcoding API URLs inside test methods
Not handling exceptions during API calls
Not verifying key fields in the response JSON
Bonus Challenge

Now add data-driven testing with 3 different user IDs and expected names

Show Hint