How to Aggregate Mock API Routes by Method in Python
Groups mock API routes by path and method, collecting response bodies and counts into a nested dictionary structure.
Python code
33 linesfrom collections import defaultdict
def aggregate_mock_routes(routes):
"""Aggregate mock API routes by method and aggregate their response bodies."""
aggregated = defaultdict(lambda: defaultdict(list))
for route in routes:
method = route["method"]
path = route["path"]
response = route["response"]
aggregated[path][method].append(response)
result = {}
for path, methods in aggregated.items():
result[path] = {}
for method, responses in methods.items():
result[path][method] = {
"count": len(responses),
"responses": responses,
}
return result
if __name__ == "__main__":
mock_routes = [
{"method": "GET", "path": "/users", "response": {"id": 1, "name": "Alice"}},
{"method": "GET", "path": "/users", "response": {"id": 2, "name": "Bob"}},
{"method": "POST", "path": "/users", "response": {"created": True}},
{"method": "GET", "path": "/health", "response": {"status": "ok"}},
]
print(aggregate_mock_routes(mock_routes))
Output
{' /users': {'GET': {'count': 2, 'responses': [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]}, 'POST': {'count': 1, 'responses': [{'created': True}]}}, ' /health': {'GET': {'count': 1, 'responses': [{'status': 'ok'}]}}}
How it works
Using defaultdict(lambda: defaultdict(list)) creates a two-level dictionary where missing keys automatically initialize to a list. This avoids manual key existence checks and reduces boilerplate. The outer loop populates the nested structure by appending each response to the list for its path and method. Finally, converting to a regular dict with count and responses keys gives a clean, serializable result. The pattern is efficient, reading the input in one pass and producing grouped output in O(n) time.
Common mistakes
- Forgetting to convert defaultdict back to a regular dict, which can cause unexpected behavior with missing keys later.
- Assuming routes are sorted, leading to hard-to-trace order issues; the result order depends on insertion order, not input sorting.
- Mutating the original route dictionaries when collecting responses, altering subsequent processing.
Variations
- Use `defaultdict` only for the inner lists with `defaultdict(list)` per path, then handle methods manually.
- Use `itertools.groupby`, but only after sorting by path and method.
Real-world use cases
- Grouping and counting mock server responses for endpoint testing in CI environments.
- Aggregating API response samples for contract validation or schema drift detection.
- Summarizing load test results by endpoint and HTTP verb for performance dashboards.
Sponsored
More from System design patterns
- Build a BFF (Backend for Frontend) Mock Aggregator in Python medium
- Builder pattern for mocking complex objects in Python easy
- Circuit Breaker Pattern in Python: Closed, Open, and Half-Open States medium
- Create a Data Helper Class in Python easy
- Domain Driven Design Aggregate Root Example in Python medium
- Facade Pattern in Python with Mock Simplification medium
Keep learning
Related tutorials and quizzes for this topic.