Module 4 · Testing behind the screen Lesson 10 of 15
Testing a REST API with pytest
An API test calls the endpoint and checks the status code and the body, without a browser. It runs in milliseconds, so you can cover far more cases than a UI test ever could.
The concept
Test the status code AND the shape of the body: a 200 that returns an error message inside the JSON is still a failure to the user.
Test the negative cases hardest - a missing field, an expired token, a duplicate record - because the happy path is the one the developer already clicked through by hand.
import requests
BASE = "https://jsonplaceholder.typicode.com"
def test_list_posts():
r = requests.get(BASE + "/posts", timeout=10)
assert r.status_code == 200
assert isinstance(r.json(), list)
def test_missing_post_is_404():
r = requests.get(BASE + "/posts/999999", timeout=10)
assert r.status_code == 404Worked example
requests.post(.../login, json=...) then assert r.status_code == 200 and assert "token" in r.json() checks the contract the front end depends on.
Your practice task
Write three API tests against a public test API: one success, one validation failure, one unauthorised.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
Test the status code AND the shape of the body: a 200 that returns an error message inside the JSON is still a failure to the user.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task — do them and the final project brief writes itself.
