API TESTING

Testing API Responses That Change Shape by User Role

One of the sneakiest gaps I see in API test suites is the shape-shift: an endpoint returns one JSON structure for an admin, a different one for a regular user, and something smaller again for a guest. The API is doing what it was designed to do. But if the suite only ever authenticates as one role, it covers one shape and ignores the rest, and that gap sits quietly in the pipeline until someone sees a field they shouldn't.

This gap is getting easier to create. Ask a coding agent to write tests for /users/{id} and it will use whatever token is in the environment, which is usually a powerful one, and assert on whatever comes back. You get a tidy, passing test of the admin shape and nothing else. Meanwhile, more APIs are being called by LLM agents acting on behalf of a user. Whatever fields that user's role returns end up in the model's context, so a field leaking to the wrong role is now also a field leaking into a prompt.

In this article I'll walk through how I map expected shapes per role, assert both presence and absence, handle nested objects and GraphQL, and write the rules down so an agent produces role tests instead of a single admin test.

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

Map the contract per role before writing tests

The first mistake is jumping straight to code. I start with a simple matrix: roles on one axis, fields on the other, and each cell marked "present" or "must be absent." It's quick to write and it becomes the specification the tests enforce. For a GET /users/{id} endpoint it might look like this:

  • Admin: id, email, role, internal_notes, created_at, last_login_ip
  • Owner: id, email, role, created_at
  • Member: id, email

internal_notes and last_login_ip are admin-only, which means absent for everyone else: not null, not an empty string, absent. That distinction matters. Returning "internal_notes": null to a member still leaks the field name and invites probing. Agree with the team which behaviour is intended, then test for exactly that. Catching missing fields before prod does goes deeper on presence checks; here the absence half is just as important.

Then turn the matrix into data the tests can use:

ROLE_SHAPES = {
    "admin": {
        "required": ["id", "email", "role", "internal_notes", "created_at", "last_login_ip"],
        "forbidden": [],
    },
    "owner": {
        "required": ["id", "email", "role", "created_at"],
        "forbidden": ["internal_notes", "last_login_ip"],
    },
    "member": {
        "required": ["id", "email"],
        "forbidden": ["internal_notes", "last_login_ip", "role", "created_at"],
    },
}

This dictionary is the living spec. When a field or role is added, you change one structure and every test driven from it follows. It's also the thing a human should review closely, because it's where intent lives.

Assert presence and absence for every role

Every role gets two passes: required fields exist, and forbidden fields don't.

import pytest


def assert_shape(body: dict, role: str) -> None:
    spec = ROLE_SHAPES[role]
    for field in spec["required"]:
        assert field in body, f"[{role}] expected field {field!r} is missing"
    for field in spec["forbidden"]:
        assert field not in body, f"[{role}] forbidden field {field!r} is present"


@pytest.mark.parametrize("role", ["admin", "owner", "member"])
def test_user_profile_shape_by_role(role, client_for_role, shared_user_id):
    response = client_for_role(role).get(f"/users/{shared_user_id}")
    assert response.status_code == 200
    assert_shape(response.json(), role)

client_for_role is a fixture that returns an HTTP client authenticated as that role, with tokens coming from the environment or a token endpoint rather than being pasted into the test. shared_user_id is a fixture-created user that all three roles are allowed to read. If a member gets a 403 instead, that's a separate access-control test, not a shape test; keep the concerns apart.

Two refinements once the map settles. Add expected types, because "last_login_ip": 0 is present but wrong. And if your team reads Gherkin, the same rules read well as scenarios: "Given I am a read-only member, when I request a user profile, then the response must not include internal_notes." That doubles as documentation of access-control intent.

Nested objects and GraphQL

Flat bodies are the easy case. For nested objects, extend the map with dot-separated paths:

def find_path(body: dict, path: str) -> bool:
    node = body
    for key in path.split("."):
        if not isinstance(node, dict) or key not in node:
            return False
        node = node[key]
    return True


ROLE_SHAPES_NESTED = {
    "admin": {"required": ["id", "billing.plan", "billing.card_last4"], "forbidden": []},
    "member": {"required": ["id"], "forbidden": ["billing"]},
}


def assert_nested_shape(body: dict, role: str) -> None:
    spec = ROLE_SHAPES_NESTED[role]
    for path in spec["required"]:
        assert find_path(body, path), f"[{role}] required path {path!r} missing"
    for path in spec["forbidden"]:
        assert not find_path(body, path), f"[{role}] forbidden path {path!r} present"

GraphQL works differently, because the client chooses the fields. A field the caller isn't allowed to see usually comes back as null with an entry in the response's errors array, or the whole query is rejected, depending on how the server implements authorization. So I send one maximal query for every role and assert, per role, which fields resolved with data and which came back null with an authorization error. Writing a smaller query per role hides the gap instead of testing it.

When the caller is an agent acting for a user

If your product has an assistant or agent that calls your API on a user's behalf, role-based shapes become part of your AI safety story. The agent should call the API with the user's own credentials, so it receives the member shape when the user is a member. If it runs with a service account instead, every admin-only field lands in the model's context and can surface in a generated answer, even though no human ever opened the admin view.

The test for that sits at the tool boundary, not the HTTP layer. Run the agent's tool function as a member and assert on what it returns before anything reaches the model:

def test_profile_tool_returns_member_shape_for_member(profile_tool, member_session):
    result = profile_tool(session=member_session, user_id="self")
    assert_shape(result, "member")

This is a deterministic test, even though the feature uses a model. It doesn't need multiple runs or a judge, because you're checking the data the tool hands over, which is exactly where a leak would start.

Writing the rules down for coding agents

When Copilot or another agent drafts role tests, the default output is a single happy-path test with whichever token it found. I head that off in the repository instructions (.github/copilot-instructions.md or your agent's equivalent):

## Role-dependent endpoints
- Expected fields per role live in tests/role_shapes.py. Never derive them from a live response.
- Every role-dependent endpoint gets a test parametrized over all roles in that file.
- Assert forbidden fields are absent (not null) for lower-privilege roles.
- Use the client_for_role fixture; never use an admin token for a non-admin test.

Then in review I spend my time on the shape map, not the generated test bodies. If the map is right and the tests are driven from it, the rest is mechanical.

Where these tests run

Role shape tests are fast and need little state, so they belong in the pull request run. A developer who accidentally exposes an admin field to members should find out within minutes, not from a security review. Also encode the access-control cousin of this problem: an endpoint that should return a reduced 200 to members but returns 403, or worse, returns 200 with the full admin payload. A shape test catches the second case; a status-only test never will. Testing API error responses beyond the happy path covers the 403 side. If you want to build role-aware fixtures and scenarios from scratch, my API testing courses cover auth, fixtures and Copilot-assisted test writing end to end.