API TESTING

Testing API Responses That Differ by Content-Type Header

A pattern that shows up in mature APIs, and in legacy ones even more, is a single endpoint that returns different bodies depending on the Accept header. Ask for application/json and you get an object. Ask for application/xml and you get the same data in tags. Ask for text/plain and you might get a one-line summary. The business logic is identical; the wire format isn't. Most suites I've seen cover one format and quietly ignore the rest, which is how a broken XML serializer sits behind a green pipeline until an integration partner reports it.

Content negotiation has picked up a new case too. Endpoints backed by a language model often offer two shapes: a complete JSON response, or a streamed response as text/event-stream so the user sees text arriving. Coding agents writing tests for those endpoints almost always test whichever one the example in the docs used. And when an agent consumes your API as a tool, it relies on the declared Content-Type to decide how to parse what it got back.

In this article I'll walk through how I structure content-type-aware tests in Python with requests and pytest: header checks, per-format body assertions, cross-format value checks, unsupported formats and defaults, and testing a streamed LLM endpoint without depending on what the model happens to say.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Accept goes out, Content-Type comes back

Be precise about which header does what. Accept on the request says what the client wants. Content-Type on the response says what the server claims it sent. A negotiation test sets the first, asserts the second, and then checks that the body really is that format, because a server can declare JSON and send XML.

import pytest
import requests

PRODUCT_URL = "https://api.example.test/v1/products/42"
FORMATS = ["application/json", "application/xml", "text/plain"]


def media_type(response) -> str:
    return response.headers.get("Content-Type", "").split(";")[0].strip().lower()


@pytest.fixture(params=FORMATS)
def negotiated(request):
    response = requests.get(PRODUCT_URL, headers={"Accept": request.param}, timeout=10)
    return request.param, response


def test_content_type_matches_accept(negotiated):
    wanted, response = negotiated
    assert response.status_code == 200
    assert media_type(response) == wanted, f"Asked for {wanted}, got {media_type(response)}"

Parametrising the fixture gives one test result per format, so triage starts with "XML is broken" rather than a single blended failure. The media_type helper strips parameters like ; charset=utf-8, which servers add routinely and which make a naive equality check fail.

If the API deliberately supports only JSON, write one test and a comment saying so. Documenting that the other formats are intentionally absent beats a suite that passes by accident because the default matched.

Assert the body for each format

A 200 with the right header and a malformed body is still broken, so each format gets its own structural check. For JSON, check keys and types. Note that JSON numbers like 10 decode as int in Python, so a price check should accept both:

def get_as(accept: str):
    response = requests.get(PRODUCT_URL, headers={"Accept": accept}, timeout=10)
    assert response.status_code == 200
    return response


def test_json_body_structure():
    data = get_as("application/json").json()
    assert isinstance(data["id"], int)
    assert isinstance(data["name"], str)
    assert isinstance(data["price"], (int, float))

For XML, the standard library parser is enough. Parse first, then assert:

import xml.etree.ElementTree as ET


def test_xml_body_structure():
    root = ET.fromstring(get_as("application/xml").text)
    assert root.tag == "product"
    for name in ("id", "name", "price"):
        element = root.find(name)
        assert element is not None and element.text, f"<{name}> missing or empty"
    float(root.find("price").text)  # raises ValueError if not numeric

For plain text, a regex documents the expected format better than a substring check:

import re


def test_plain_text_body_format():
    text = get_as("text/plain").text.strip()
    assert re.fullmatch(r"Product: .+, ID: \d+, Price: \d+\.\d{2}", text), repr(text)

Then cross-check values. If JSON says the price is 9.99 and XML says 10.99, that's a serialization bug that only shows up when a partner on the XML path sees different pricing from the web app:

def test_price_agrees_across_formats():
    json_price = float(get_as("application/json").json()["price"])
    xml_price = float(ET.fromstring(get_as("application/xml").text).find("price").text)
    assert json_price == pytest.approx(xml_price)

Field-by-field checks per format matter. If a new discount field was added to the JSON serializer and never to the XML one, only an explicit assertion will notice. The same thinking applies to type drift, which I cover in writing API tests that catch data type mismatches early.

Unsupported formats, missing headers and wildcards

The edge cases are where negotiation bugs actually hurt. The HTTP spec gives a server a choice when it can't satisfy Accept: it can return 406 Not Acceptable, or it can ignore the header and send its default. Both are allowed. What isn't acceptable is a 500 because the format dispatch threw an exception. Decide which behaviour your API promises and pin it:

def test_unsupported_accept_returns_406():
    response = requests.get(PRODUCT_URL, headers={"Accept": "application/x-custom-binary"}, timeout=10)
    assert response.status_code == 406


def test_missing_accept_defaults_to_json():
    response = requests.get(PRODUCT_URL, timeout=10)
    assert response.status_code == 200
    assert media_type(response) == "application/json"


def test_wildcard_accept_defaults_to_json():
    response = requests.get(PRODUCT_URL, headers={"Accept": "*/*"}, timeout=10)
    assert media_type(response) == "application/json"

One caveat on the missing-header test: requests sends Accept: */* by default, so it isn't truly header-less. If the distinction matters for your API, remove the header explicitly by passing a session with that default header deleted. The default-format tests matter because they turn an assumption into a contract. If someone changes the default to XML, these fail loudly instead of breaking every client that never set the header.

Negotiation failures are error conditions and deserve the same care as any other; see testing API error responses beyond the happy path.

Streamed responses from LLM-backed endpoints

If your API has a model-backed endpoint, say a product description generator, it may return full JSON for Accept: application/json and server-sent events for Accept: text/event-stream. That's content negotiation too, and both paths need tests. The trick is to assert on the protocol and structure, not on the generated words, which vary from run to run:

def test_description_streams_as_server_sent_events(fake_model_env):
    response = requests.post(
        "https://api.example.test/v1/products/42/description",
        headers={"Accept": "text/event-stream"},
        json={"tone": "plain"},
        stream=True,
        timeout=30,
    )
    assert response.status_code == 200
    assert media_type(response) == "text/event-stream"

    data_lines = [
        line[len("data:"):].strip()
        for line in response.iter_lines(decode_unicode=True)
        if line and line.startswith("data:")
    ]
    assert data_lines, "stream produced no data events"

The fake_model_env fixture points the service at a stub model that returns fixed text, so this test checks your API's streaming behaviour deterministically and runs on every pull request. The event format inside each data: line is whatever your API defines, often JSON chunks followed by a final "done" marker; assert on that structure. Then, separately and less often, run the same endpoint against the real model and judge the output over several runs, because a single run of a non-deterministic feature tells you very little.

Also check that the JSON path and the streamed path agree on structure: if the JSON response has description and model_version fields, the stream's final event should carry the same information. That's the streaming version of the cross-format value check above.

Keeping the matrix manageable

When an API varies by role and by format, the combinations grow fast. I keep negotiation tests in their own module, separate from role-based shape tests, so a failure points at one concern. I also put the format rules in the agent instructions file, for example "every endpoint that supports more than one Accept value gets a parametrized test per format, plus 406 and default-format tests", because otherwise an assistant will test only the format in the first example it sees.

Content negotiation is a contract: check the header, parse the body, validate the structure, cross-check values, and pin what happens when negotiation fails. If you'd like to practise building suites like this with GitHub Copilot as a co-writer, my API testing courses are the place to start.