API TESTING

Testing API Responses That Differ by Content-Type Header

A pattern that shows up often in mature APIs — and in legacy ones even more — is a single endpoint that returns completely different response bodies depending on the Accept or Content-Type header the client sends. Ask for application/json and you get a structured object. Ask for application/xml and you get the same data wrapped in tags. Ask for text/plain and you might get a flat string summary. The business logic is identical; the wire format is not. Most test suites I've seen cover exactly one of those formats and silently ignore the rest.

That silence is expensive. When the XML serializer is broken but the JSON path is green, your CI pipeline passes and your enterprise integration partners start filing bugs. Content-type negotiation is a first-class contract between your API and its consumers, and it deserves first-class test coverage. That means separate, explicit assertions for each negotiated format — not a single happy-path test that happens to use whatever default the server picks.

In this article I'll walk through how I structure content-type-aware tests in Python using requests and pytest, what to assert beyond just the header value itself, and where teams typically leave gaps that let real bugs through. Everything here is directly portable to a real test suite.

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

How Content-Type Negotiation Actually Works in a Test Request

Before writing a single assertion, it helps to be precise about which header does what. The Accept header is what the client sends to say "I want this format." The Content-Type header on the response is what the server sends back to say "here's what I actually gave you." When you're testing format negotiation, you're setting Accept on the request and asserting Content-Type on the response — plus asserting that the body actually matches the declared format.

A lot of bugs live in the gap between those two things. A server might return Content-Type: application/json in the header but actually serialize the body as XML, or vice versa. Your test needs to check both. Here's a minimal pytest fixture pattern I use to drive the same endpoint with different format requests:

import pytest
import requests

BASE_URL = "https://api.example.com/v1/products/42"

@pytest.fixture(params=["application/json", "application/xml", "text/plain"])
def format_response(request):
    accept_type = request.param
    resp = requests.get(BASE_URL, headers={"Accept": accept_type})
    return accept_type, resp

Parametrizing over the accepted formats means pytest generates a separate test run for each one — you get three independent results in your output, not one blended pass/fail. That matters when you need to triage which format is broken.

The first assertion I always write is a content-type check that strips the charset suffix, because servers routinely append ; charset=utf-8 and a naive equality check fails:

def test_content_type_header_matches_request(format_response):
    accept_type, resp = format_response
    returned_type = resp.headers.get("Content-Type", "").split(";")[0].strip()
    assert returned_type == accept_type, (
        f"Requested {accept_type} but server returned {returned_type}"
    )

This is the baseline. If this test fails, everything else is noise — you can't trust the body assertions until you know the server is actually honouring the negotiation.

One more thing worth noting: some APIs ignore the Accept header entirely and always return JSON. That's a valid (if limiting) design choice, but your tests should document it explicitly rather than accidentally passing because the default happens to match your assertion. If the API only supports one format, write one test and add a comment explaining why the others are absent — future you will thank present you.

Asserting the Body Structure for Each Negotiated Format

Once you've confirmed the header is correct, you need to assert that the body is actually valid and structurally complete for that format. This is where most teams stop short — they check the status code, maybe the content-type header, and call it done. But a malformed XML document with a 200 status and a correct content-type header is still a broken response.

For JSON, resp.json() will raise a JSONDecodeError if the body isn't valid JSON, which is a useful free assertion. But you should go further and check that the expected keys are present and that their types are correct. This is exactly the kind of coverage I wrote about when discussing catching data type mismatches early — the same principle applies here, except the risk is that the XML and plain-text serializers might drop fields or change types that the JSON path preserves.

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

For XML, I reach for xml.etree.ElementTree from the standard library. Parse first, assert second:

import xml.etree.ElementTree as ET

def test_xml_body_structure(xml_response):
    root = ET.fromstring(xml_response.text)
    assert root.tag == "product"
    assert root.find("id") is not None
    assert root.find("name") is not None
    assert root.find("price") is not None
    # Verify the price is a parseable number, not an empty tag
    price_text = root.find("price").text
    assert price_text is not None
    float(price_text)  # raises ValueError if not numeric

For text/plain, you're usually asserting against a known pattern. A regex is cleaner than a substring check here because it's self-documenting about what the format is supposed to look like:

import re

def test_plain_text_body_format(plain_response):
    pattern = r"^Product: .+, ID: \d+, Price: \d+\.\d{2}$"
    assert re.match(pattern, plain_response.text.strip()), (
        f"Plain text body didn't match expected format: {plain_response.text!r}"
    )

The key discipline here is that each format gets its own structural assertion, not a shared one that silently passes for the wrong reasons. If your product API returns a discount field in JSON but the XML serializer was never updated to include it, a shared field-count check won't catch that. Explicit field-by-field assertions for each format will.

It's also worth cross-checking the values across formats when you can. If the same product endpoint returns "price": 9.99 in JSON and <price>9.99</price> in XML, those should agree. A divergence in values across formats is a serialization bug, and it's the kind of bug that only surfaces in production when a partner using the XML endpoint sees different pricing than the web app using JSON. A small parametrized cross-format value test catches this early.

Handling Unsupported Formats and Edge Cases in Content Negotiation Tests

The happy path — "client asks for JSON, server returns JSON" — is the easy part. The test coverage that actually prevents production incidents lives in the edge cases: what happens when the client asks for a format the server doesn't support? What about wildcard accepts? What about a missing Accept header altogether?

RFC 7231 says a server that can't honour an Accept header should return a 406 Not Acceptable status. In practice, I've seen servers return a 200 with their default format, return a 400, or return a 500 because the format-dispatch code throws an unhandled exception. All three of those are testable behaviours, and all three should be documented in your suite. This connects directly to testing error responses beyond the happy path — format negotiation failures are error conditions that deserve the same rigour as a missing required parameter.

def test_unsupported_accept_type_returns_406():
    resp = requests.get(BASE_URL, headers={"Accept": "application/x-custom-binary"})
    assert resp.status_code == 406, (
        f"Expected 406 for unsupported format, got {resp.status_code}"
    )

def test_missing_accept_header_returns_default_format():
    resp = requests.get(BASE_URL)  # No Accept header
    returned_type = resp.headers.get("Content-Type", "").split(";")[0].strip()
    # Document what the API's default is — don't just assert 200
    assert resp.status_code == 200
    assert returned_type == "application/json", (
        "API should default to JSON when no Accept header is provided"
    )

The second test there is doing something important: it's making the API's default format a documented contract, not an assumption. If someone changes the server's default from JSON to XML, this test fails loudly instead of silently breaking every client that omits the header.

Wildcard accepts (Accept: */*) are another edge case worth covering. Some servers treat this as "give me your default," others as "give me the first format in your priority list." Your test should pin whichever behaviour your API promises:

def test_wildcard_accept_returns_server_default():
    resp = requests.get(BASE_URL, headers={"Accept": "*/*"})
    assert resp.status_code == 200
    returned_type = resp.headers.get("Content-Type", "").split(";")[0].strip()
    assert returned_type == "application/json"

One organisational note: when your API returns different shapes for different roles and different formats, the test matrix grows fast. I've found it useful to keep content-type negotiation tests in their own module, separate from role-based shape tests (which I cover in the context of responses that change shape by user role). Mixing the two concerns in a single parametrized fixture produces a combinatorial explosion that's hard to read and harder to debug when one combination fails.

The bottom line: content-type negotiation is a contract, and contracts need tests that cover both the happy path and the boundary conditions. Check the header, parse the body, validate the structure, cross-check the values, and explicitly test what happens when the negotiation fails. That's the full picture — and it's the kind of coverage that catches real bugs before your integration partners do.