1. Home
  2. Blog
  3. Test Automation

Test Automation

API Testing in Python: Build a Pytest and Requests Suite Step by Step

API testing in Python needs only pytest, requests and a few good habits. Build a real suite with fixtures, status code and header checks, JSON schema validation, a full create-read-delete flow, negative and auth tests, and see what happened when we planted a bug in the API.

10 min read
API testing in Python with pytest and requests

Key takeaways

  • API testing in Python needs three libraries: pytest to run tests, requests to call the API, and jsonschema to check response shapes.
  • Put the base URL and an authenticated session in fixtures so every test stays short.
  • Test far more than 200 OK: headers, schemas, bad payloads, missing auth and error codes. 9 of our 13 tests were negative or edge cases.
  • When we planted a type bug in the API, schema validation caught it with a precise message. It also showed that JSON Schema treats 450.0 as a valid integer.

APIs are the contract between your frontend, mobile apps, partners and microservices. A UI test can tell you a page broke; an API test tells you exactly which response changed, in milliseconds, without a browser. That makes API tests the fastest, most stable layer for most automation suites, as the test pyramid suggests.

In this tutorial we build a complete API testing in Python suite against a small book API we wrote with Python’s http.server, running on 127.0.0.1. We used pytest 9.2, requests 2.34.2 and jsonschema 4.26.0 on Python 3.13.6, and every result shown came from those runs.

Why test at the API level?

  • Speed: our 13 tests finished in under 1.6 seconds.
  • Stability: no selectors, rendering delays or browser quirks.
  • Precision: a failure points at one endpoint and one field.
  • Early feedback: APIs can be tested before the UI exists, which fits shift-left testing.

The tool stack

pip install pytest requests jsonschema

pytest discovers and runs tests and gives you fixtures and parametrisation. requests sends HTTP calls. jsonschema validates that a JSON body has the expected fields and types. Optional extras such as pytest-xdist for parallel runs and pytest-html for reports can come later. If you prefer a GUI first, our Postman API testing guide covers the same ideas without code.

The API under test

Our book API has these endpoints:

Method and path Behaviour
GET /books List books, optional max_price filter
GET /books/{id} One book, 404 if missing, 400 if the id is not a number
POST /books Create; needs a bearer token; 201 with a Location header; 422 for invalid data; 400 for broken JSON
DELETE /books/{id} Delete; needs a token; 204 on success
GET /me Current user; 401 with WWW-Authenticate: Bearer without a token

The token is a dummy value, test-token, that only exists in this local test server. Never put real credentials in test code; load them from environment variables in CI.

Fixtures: base URL and an authenticated session

# conftest.py
import pytest, requests
from server import start

@pytest.fixture(scope="session")
def base_url():
    srv = start(8766)                 # start the local API once per run
    yield "http://127.0.0.1:8766"
    srv.shutdown()

@pytest.fixture
def api(base_url):
    s = requests.Session()
    s.headers["Authorization"] = "Bearer test-token"
    s.base = base_url
    yield s
    s.close()

The base_url fixture runs once per session, starts the server and stops it at the end. The api fixture gives each test a fresh, authenticated Session. In a real project, base_url would read an environment variable such as API_BASE_URL so the same suite can target local, staging or a container. Our pytest fixtures guide explains scopes in depth.

Testing status codes and headers

def test_list_books_returns_json_array(api):
    r = api.get(f"{api.base}/books", timeout=5)
    assert r.status_code == 200
    assert r.headers["Content-Type"].startswith("application/json")
    for book in r.json():
        validate(book, BOOK_SCHEMA)

def test_filter_by_max_price(api):
    r = api.get(f"{api.base}/books", params={"max_price": 300}, timeout=5)
    assert all(b["price"] <= 300 for b in r.json())

Assert the exact status code, not just “success”. A 200 where you expected 201 can signal a real bug, such as a create endpoint that silently updated an existing record. Checking Content-Type catches servers that return an HTML error page with a 200 status. Every call passes timeout=, so a hung API fails the test instead of freezing the run; our Python requests guide explains why.

Validating the JSON schema

from jsonschema import validate

BOOK_SCHEMA = {
    "type": "object",
    "required": ["id", "title", "price"],
    "properties": {
        "id": {"type": "integer"},
        "title": {"type": "string", "minLength": 1},
        "price": {"type": "integer", "minimum": 0},
    },
    "additionalProperties": False,
}

One schema check replaces a dozen individual asserts. It confirms required fields exist, types are right, values are in range and no unexpected fields leaked out, such as an internal cost_price. Keep schemas in a shared module so every test that touches a book uses the same contract. For contracts shared between teams, see our API contract testing guide.

A full create, read, delete flow

def test_create_then_fetch_then_delete(api):
    r = api.post(f"{api.base}/books", json={"title": "API Testing", "price": 399}, timeout=5)
    assert r.status_code == 201
    new = r.json(); validate(new, BOOK_SCHEMA)
    assert r.headers["Location"] == f"/books/{new['id']}"
    assert api.get(f"{api.base}/books/{new['id']}", timeout=5).json() == new
    assert api.delete(f"{api.base}/books/{new['id']}", timeout=5).status_code == 204
    assert api.get(f"{api.base}/books/{new['id']}", timeout=5).status_code == 404

This one test proves the create response, the Location header, that the record can be read back unchanged, that delete works, and that the record is really gone. It also cleans up after itself, so the test can run repeatedly without polluting data. Self-cleaning tests are essential when suites run against shared environments.

Negative tests with parametrize

@pytest.mark.parametrize("payload,code", [
    ({"title": "No price"}, 422),
    ({"title": "Negative", "price": -5}, 422),
    ({"title": "Text price", "price": "10"}, 422),
    ([], 422),
])
def test_create_rejects_bad_payloads(api, payload, code):
    r = api.post(f"{api.base}/books", json=payload, timeout=5)
    assert r.status_code == code
    assert "error" in r.json()

def test_invalid_json_body(api):
    r = api.post(f"{api.base}/books", data="{bad json",
                 headers={"Content-Type": "application/json"}, timeout=5)
    assert r.status_code == 400

Negative tests matter more than happy paths, because they guard the validation that protects your data. pytest parametrize turns one function into a test per payload, each reported separately. The ideas come straight from boundary value analysis and negative testing: missing fields, wrong types, out-of-range values and malformed bodies.

Authentication tests

def test_requires_auth(base_url):
    r = requests.post(f"{base_url}/books", json={"title": "x", "price": 1}, timeout=5)
    assert r.status_code == 401
    assert requests.get(f"{base_url}/me", timeout=5).headers["WWW-Authenticate"] == "Bearer"

This test deliberately uses plain requests instead of the authenticated fixture. Always test that protected endpoints reject missing, expired and wrong tokens, and that one user cannot read another user’s data. Security bugs in APIs are often just missing authorisation checks.

Error codes

@pytest.mark.parametrize("path,code", [("/books/99", 404), ("/books/abc", 400), ("/nope", 404)])
def test_error_codes(api, path, code):
    assert api.get(api.base + path, timeout=5).status_code == code

A missing resource should be 404, a malformed id 400, and an unknown route 404. Servers that return 500 for bad input are leaking unhandled exceptions. Our HTTP status codes cheat sheet lists what each code should mean.

A simple response time budget

def test_response_time_budget(api):
    r = api.get(f"{api.base}/books/1", timeout=5)
    assert r.elapsed.total_seconds() < 0.5

A loose budget catches big regressions, such as a missing database index that turns 50 ms into 5 seconds. Keep it generous to avoid flaky tests on busy CI machines, and use real tools for load testing, as covered in our load vs stress testing guide.

Running the suite

pytest -v test_books_api.py
test_list_books_returns_json_array PASSED
test_filter_by_max_price PASSED
test_create_then_fetch_then_delete PASSED
test_create_rejects_bad_payloads[payload0-422] PASSED
test_create_rejects_bad_payloads[payload1-422] PASSED
test_create_rejects_bad_payloads[payload2-422] PASSED
test_create_rejects_bad_payloads[payload3-422] PASSED
test_invalid_json_body PASSED
test_requires_auth PASSED
test_error_codes[/books/99-404] PASSED
test_error_codes[/books/abc-400] PASSED
test_error_codes[/nope-404] PASSED
test_response_time_budget PASSED
13 passed in 0.90s

Planting a bug: does the suite catch it?

A suite that never fails proves little. We changed the server so one book’s price came back as a string, "450", a common serialisation bug. The suite reported 2 failed, 11 passed, with a clear message from the schema check:

E   jsonschema.exceptions.ValidationError: '450' is not of type 'integer'
E   Failed validating 'type' in schema['properties']['price']:
E       {'type': 'integer', 'minimum': 0}

The second failure came from the price filter test. The server’s filter code crashed with a TypeError comparing the string with a number and closed the connection, so the test saw requests.exceptions.ConnectionError: Remote end closed connection without response. One small type bug broke two features. Our first attempt at planting a bug was more surprising: we changed the price to 450.0 and every test still passed. JSON Schema defines an integer as any number with no fractional part, so 450.0 is valid. If your API must return true integers, add an explicit check such as isinstance(book["price"], int). Planting bugs on purpose, the idea behind mutation testing, is the best way to learn what your suite really guards.

Tip: run the suite against a deliberately broken build at least once. If nothing fails, your tests are checking too little.

Project structure for a growing suite

api-tests/
  conftest.py          # fixtures: base_url, api session, test data
  schemas.py           # shared JSON schemas
  clients/books.py     # small wrapper: create_book(), get_book()
  tests/
    test_books.py
    test_auth.py
  pyproject.toml       # pytest settings and markers

As the suite grows, move repeated calls into a small client module, so tests read like book = books.create(title="x"). Group slow or destructive tests with pytest markers, and keep test data creation in fixtures.

Running API tests in CI

Start the API (or a container of it), set API_BASE_URL, and run pytest -q. Fail the pipeline on any test failure, publish a JUnit XML report with --junitxml=report.xml, and run the suite on every pull request. Our GitHub Actions guide shows a complete workflow.

Final thoughts

Good API testing in Python is not about clever code. It is about checking the full contract: status, headers, schema, behaviour, errors and security, with fixtures that keep each test short and self-cleaning. Start with the suite above, plant a bug to prove it bites, and grow it endpoint by endpoint. It will become the fastest and most trusted part of your automation.

FAQ

Which Python library is best for API testing?

Most teams use pytest with requests, plus jsonschema for response validation. httpx is a good alternative when you need async support.

How do I validate a JSON response in pytest?

Parse it with response.json and check it against a JSON schema using jsonschema.validate, then add asserts for specific values that matter.

What should an API test check besides the status code?

Headers such as Content-Type, the response schema, field values, error messages, authentication rules, side effects such as created records, and response time.

Should API tests hit a real server or a mock?

Both have a place. Tests against a real or containerised API catch integration bugs, while mocks keep client unit tests fast and isolated.

How do I keep API tests from leaving test data behind?

Create data inside the test or a fixture and delete it at the end, ideally in fixture teardown, so cleanup runs even when an assertion fails.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Software Development

Python Deepcopy vs Copy: Fix Nested Lists

Python deepcopy vs shallow copy explained with tested code: aliasing, nested lists, the [[0]*3]*3 trap, memo and cycles, custom __deepcopy__,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
Software Development

Base64 Encoding Explained, With Python Code

Base64 encoding turns bytes into 64 safe text characters. See the bit-level steps, padding, URL-safe base64, the 33% size cost,…

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Software Development

JavaScript Classes: Private Fields and Extends

JavaScript classes explained with tested Node.js code: constructors, methods, #private fields, getters, static members, extends and super, plus the errors…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →