REST API testing basics in Testing Fundamentals - Build an Automation Script
import unittest import requests class TestGetUserAPI(unittest.TestCase): def setUp(self): self.base_url = "https://api.example.com/users" def test_get_user_details(self): user_id = 123 url = f"{self.base_url}/{user_id}" try: response = requests.get(url) except requests.RequestException as e: self.fail(f"Request failed: {e}") self.assertEqual(response.status_code, 200, f"Expected status code 200 but got {response.status_code}") content_type = response.headers.get('Content-Type', '') self.assertIn('application/json', content_type, f"Expected Content-Type application/json but got {content_type}") try: data = response.json() except ValueError: self.fail("Response is not valid JSON") self.assertEqual(data.get('id'), user_id, f"Expected user id {user_id} but got {data.get('id')}") self.assertIn('name', data, "Response JSON missing 'name' field") self.assertIn('email', data, "Response JSON missing 'email' field") if __name__ == '__main__': unittest.main()
This test uses Python's unittest framework and the requests library to automate the manual test case.
In setUp, the base URL is defined for reuse.
The test method test_get_user_details sends a GET request to the user endpoint with ID 123.
It asserts the HTTP status code is 200, ensuring the request succeeded.
It checks the Content-Type header includes 'application/json' to confirm the response format.
The response body is parsed as JSON. If parsing fails, the test fails with a clear message.
Finally, it asserts the JSON contains the expected user ID, and the 'name' and 'email' fields exist.
Try-except blocks handle request errors and JSON parsing errors gracefully, providing clear failure reasons.
This structure keeps the test clear, independent, and easy to maintain.
Now add data-driven testing with 3 different user IDs: 123, 456, and 789
Practice
Solution
Step 1: Understand REST API testing goal
REST API testing focuses on verifying communication between client and server using HTTP requests and responses.Step 2: Identify the correct purpose
Among the options, only checking data exchange over the web matches REST API testing.Final Answer:
To check if the API correctly sends and receives data over the web -> Option CQuick Check:
REST API testing = data exchange check [OK]
- Confusing API testing with UI design
- Thinking API testing means coding the API
- Mixing API testing with database design
Solution
Step 1: Recall HTTP methods and their uses
GET is used to request data, POST to send data, DELETE to remove data, and PUT to update data.Step 2: Match method to retrieving data
Retrieving data means reading it without changing, which is the GET method.Final Answer:
GET -> Option BQuick Check:
Retrieve data = GET method [OK]
- Choosing POST instead of GET for data retrieval
- Confusing PUT with GET
- Using DELETE to get data
{"status":200, "body": {"name": "Alice", "age": 30}}What does the status code 200 mean?
Solution
Step 1: Understand HTTP status codes
Status code 200 means OK, indicating success. 404 means not found, 500 means server error, 401 means unauthorized.Step 2: Match code 200 to meaning
Since the response shows 200, it means the request succeeded and data is returned.Final Answer:
The request was successful and data is returned -> Option AQuick Check:
Status 200 = success [OK]
- Confusing 200 with error codes
- Thinking 200 means unauthorized
- Ignoring the status code meaning
response = send_request('GET', '/users/1')
assert response.status_code = 200What is the error in this code?
Solution
Step 1: Check assertion syntax
In Python, '=' is for assignment, '==' is for comparison. Assertions need '==' to compare values.Step 2: Identify the error in the assertion line
The code uses '=' which causes a syntax error. It should be '==' to check if status_code equals 200.Final Answer:
Using '=' instead of '==' in the assertion -> Option DQuick Check:
Assertion needs '==' not '=' [OK]
- Confusing assignment '=' with comparison '=='
- Ignoring syntax errors in assertions
- Assuming single quotes cause error here
Solution
Step 1: Understand the test goal for empty user list
The API should return an empty list with a success status (200) when no users exist.Step 2: Evaluate each option for correctness
Send a GET request and verify the response body is an empty list and status code is 200 correctly sends GET and expects empty list and 200. Send a POST request with user data and check for status code 201 is about creating users, not testing empty list. Send a DELETE request to remove all users and expect status code 404 expects 404 after deletion, which is incorrect for empty list response. Send a GET request and expect status code 500 when no users exist expects 500 error, which is wrong for empty data.Final Answer:
Send a GET request and verify the response body is an empty list and status code is 200 -> Option AQuick Check:
Empty list test = GET + empty list + 200 [OK]
- Expecting error codes for empty data
- Using wrong HTTP methods for retrieval
- Confusing creation or deletion tests with retrieval
Ready to prove it?
Pass the test and this pattern moves unknown
