API-92Recommended
Reject JSON with duplicate keys
Refuse any request body in which one object holds the same key twice. Answer 400 with problem details that name the key.
How to do it
RFC 8259 leaves duplicate keys undefined, so parsers disagree. Many keep the last value, and others keep the first or fail. When a gateway checks "role": "user" and the service behind it reads "role": "admin", the check is bypassed. I-JSON in RFC 7493 forbids duplicate names, so accept only I-JSON. Most standard parsers drop duplicates in silence, so turn on a strict mode or pass a hook that sees every pair. This adds to Accept only fields you know. Large numbers follow Send IDs as strings.
Examples
Python example
import json
class DuplicateKey(ValueError):
pass
def without_duplicates(pairs):
seen = set()
for key, _ in pairs:
if key in seen:
raise DuplicateKey(key)
seen.add(key)
return dict(pairs)
order = json.loads(body, object_pairs_hook=without_duplicates)
Java example
ObjectMapper mapper = JsonMapper.builder()
.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
.build();
Order order = mapper.readValue(body, Order.class);
How to check
A contract test sends {"quantity": 1, "quantity": -5} to every write endpoint. Each one answers 400 naming quantity, and no row changes.
Sources
Related rules
- API-12 Accept only fields you know in API design
- API-9 Send IDs as strings in API design
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/api-design/requests-and-responses/duplicate-json-keys">Agent Wranglers API design playbook</a>. In code you write, add a comment next to it with the same link.