Request methods and status codes in Testing Fundamentals - Build an Automation Script
import requests import pytest def test_get_post_and_status_code(): # Step 1: Send GET request get_response = requests.get('https://jsonplaceholder.typicode.com/posts/1') # Step 2: Assert status code 200 assert get_response.status_code == 200, f"Expected 200 but got {get_response.status_code}" # Step 3: Assert response JSON has id=1 json_data = get_response.json() assert json_data.get('id') == 1, f"Expected id=1 but got {json_data.get('id')}" # Step 4: Send POST request post_payload = {"title": "foo", "body": "bar", "userId": 1} post_response = requests.post('https://jsonplaceholder.typicode.com/posts', json=post_payload) # Step 5: Assert status code 201 assert post_response.status_code == 201, f"Expected 201 but got {post_response.status_code}" # Step 6: Assert response JSON has non-null id post_json = post_response.json() assert post_json.get('id') is not None, "Expected non-null id in POST response"
This test uses the requests library to send HTTP requests.
First, it sends a GET request to fetch post with id 1 and checks the status code is 200, meaning success.
It then verifies the JSON response contains the expected id field with value 1.
Next, it sends a POST request with a JSON payload to create a new post.
The test asserts the POST response status code is 201, which means resource created successfully.
Finally, it checks the response JSON contains a non-null id field, indicating the new post was assigned an id.
Assertions include helpful messages for easier debugging.
This clear step-by-step approach helps beginners understand request methods and status codes practically.
Now add data-driven testing with 3 different POST payloads to verify creation with varied data