Bird
Raised Fist0
Testing Fundamentalstesting~15 mins

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

Choose your learning style10 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

Practice

(1/5)
1. What is the main purpose of API test automation?
easy
A. To design the user interface of an application
B. To check if different software parts communicate correctly
C. To write code for the backend server
D. To create database schemas

Solution

  1. Step 1: Understand API test automation goal

    API test automation focuses on verifying communication between software parts via APIs.
  2. Step 2: Eliminate unrelated options

    Designing UI, writing backend code, and creating database schemas are not related to API test automation.
  3. Final Answer:

    To check if different software parts communicate correctly -> Option B
  4. Quick Check:

    API test automation = communication check [OK]
Hint: API tests check communication, not UI or database [OK]
Common Mistakes:
  • Confusing API testing with UI testing
  • Thinking API tests create backend code
  • Mixing API testing with database design
2. Which of the following is the correct way to check the HTTP status code in an automated API test using Python's requests library?
easy
A. response.code == 200
B. response.status == 200
C. response.status_code == 200
D. response.statusCode == 200

Solution

  1. Step 1: Recall Python requests response attribute

    The correct attribute to get HTTP status code is status_code.
  2. Step 2: Match options with correct attribute

    Only response.status_code == 200 uses the correct attribute and syntax.
  3. Final Answer:

    response.status_code == 200 -> Option C
  4. Quick Check:

    requests status code = status_code [OK]
Hint: Use response.status_code to check HTTP status in Python [OK]
Common Mistakes:
  • Using incorrect attribute names like status or code
  • Confusing camelCase with snake_case
  • Forgetting double equals for comparison
3. Given this Python code snippet for an API test:
import requests
response = requests.get('https://api.example.com/data')
print(response.json()['status'])

What will be the output if the API response JSON is {"status": "success", "data": []}?
medium
A. "success"
B. KeyError
C. {'status': 'success'}
D. success

Solution

  1. Step 1: Understand response.json() output

    response.json() returns a Python dictionary parsed from JSON.
  2. Step 2: Access the 'status' key value

    Accessing ['status'] returns the string "success" without quotes in print output.
  3. Final Answer:

    success -> Option D
  4. Quick Check:

    Print dict value = string without quotes [OK]
Hint: Print of string value shows without quotes in Python [OK]
Common Mistakes:
  • Expecting quotes around printed string
  • Confusing JSON string with Python print output
  • Assuming KeyError without checking keys
4. You wrote this API test code snippet:
response = requests.post('https://api.example.com/login', data={'user': 'admin', 'pass': '1234'})
assert response.status_code = 200

What is the error and how to fix it?
medium
A. Use '==' for comparison in assert, not '='
B. Change 'data' to 'json' in requests.post() call
C. Use 'response.status' instead of 'response.status_code'
D. Add parentheses around assert condition

Solution

  1. Step 1: Identify syntax error in assert statement

    The assert statement uses '=' which is assignment, not comparison.
  2. Step 2: Correct assert syntax

    Replace '=' with '==' to compare response.status_code to 200.
  3. Final Answer:

    Use '==' for comparison in assert, not '=' -> Option A
  4. Quick Check:

    Assert needs '==' for comparison [OK]
Hint: Assert uses '==' to compare, '=' assigns [OK]
Common Mistakes:
  • Using '=' instead of '==' in assert
  • Confusing 'data' and 'json' parameters (not error here)
  • Using wrong attribute like response.status
5. You want to automate testing an API that returns a list of users with their ages. You need to verify the API only returns users aged 18 or older. Which approach best fits this requirement?
hard
A. Send a GET request, parse JSON response, then assert all ages >= 18
B. Send a POST request with age filter, then check status code 200
C. Check only the first user's age in the response
D. Verify the response content type is 'text/html'

Solution

  1. Step 1: Understand requirement to verify all users' ages

    We must check every user's age is 18 or older in the response data.
  2. Step 2: Choose approach that parses response and asserts condition on all users

    Sending GET, parsing JSON, and asserting all ages >= 18 matches the need.
  3. Final Answer:

    Send a GET request, parse JSON response, then assert all ages >= 18 -> Option A
  4. Quick Check:

    Check all data items for condition [OK]
Hint: Check all items, not just one, for correct data [OK]
Common Mistakes:
  • Checking only first user age
  • Using wrong HTTP method for retrieval
  • Verifying wrong response content type
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard