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.

Easy Python 3.9+ Aug 9, 2026 System design patterns 13 views 0 copies

Python code

33 lines
Python 3.9+
from 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

stdout
{' /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

  1. Use `defaultdict` only for the inner lists with `defaultdict(list)` per path, then handle methods manually.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from System design patterns

Related tutorials and quizzes for this topic.