W

Ward
GitHub logo
216 stars, 18 forks

Test a REST API with httpx

This tutorial will explain how you can test a JSON REST API using Ward and httpx, a modern HTTP client library similar to requests. The API could be written in any language, but rather than implementing our own, we'll use JSONPlaceholder. JSONPlaceholder is a mock API that contains some example endpoints that can be used for testing.

Let's begin by installing Ward and httpx:

$
pip install ward httpx

Testing GET requests

Let's write a test to check that the endpoint https://jsonplaceholder.typicode.com/todos/1 returns the todo with the correct ID (1).

import httpx
from ward import test
BASE_URL = "https://jsonplaceholder.typicode.com/"
@test("/todos/1 returns todo with id 1")
def _():
# Send the GET request
response = httpx.get(f"{BASE_URL}todos/1")
# Get the ID from the response
todo_id = response.json()["id"]
# Check that the ID is 1
assert todo_id == 1
# Raise an exception to fail the test if
# the status code is not a successful one
response.raise_for_status()

Now we can run our test by running ward from the command line:

$
ward

It's a PASS! We've confirmed that JSONPlaceholder returns the correct todo:

PASS test_rest:6:
/todos/1 returns todo with id 1

Now we'll check that passing a non-existent ID ("invalid") to the endpoint results in a 404:

@test("/todos/invalid returns a 404")
def _():
response = httpx.get(f"{BASE_URL}todos/invalid")
code = response.status_code
assert code == httpx.codes.NOT_FOUND

Running our tests again, we see that JSONPlaceholder does indeed return a 404 when we pass a non-existent ID:

PASS test_rest:6:
/todos/1 returns todo with id 1
PASS test_rest:15:
/todos/invalid returns a 404