📊 We use cookies & analytics to improve your experience. Learn more
Latest

Software Testing — Manual and Automation Module 4 · Lesson 10 of 15

0% Exit to course

Module 4 · Testing behind the screen Lesson 10 of 15

Testing a REST API with pytest

Learning objective

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.

Python
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 == 404

Worked 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.

Create free account or sign in

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.

Next recommended course Full-Stack Web Development Bootcamp