How to Expand Related Resources with a Mock Embed in Python
Simulate API response embedding by attaching mock embedded data to each related resource in a list using a simple Python class.
Python code
25 linesimport json
class EmbedMock:
def __init__(self, resources):
self.resources = resources
def expand(self):
for resource in self.resources:
resource["embedded"] = self._generate_embed()
def _generate_embed(self):
return {
"id": 1,
"type": "mock",
"data": {"message": "Expanded resource"}
}
if __name__ == "__main__":
resources = [
{"name": "users", "url": "/api/users"},
{"name": "posts", "url": "/api/posts"}
]
embedder = EmbedMock(resources)
embedder.expand()
print(json.dumps(resources, indent=2))
Output
[
{
"name": "users",
"url": "/api/users",
"embedded": {
"id": 1,
"type": "mock",
"data": {
"message": "Expanded resource"
}
}
},
{
"name": "posts",
"url": "/api/posts",
"embedded": {
"id": 1,
"type": "mock",
"data": {
"message": "Expanded resource"
}
}
}
]
How it works
The EmbedMock class holds a list of resource dictionaries. The expand method iterates over each resource and inserts a new embedded key with mock data. _generate_embed returns a dictionary that simulates an expanded related resource. This pattern mirrors how APIs like JSON:API or GraphQL embeds relationships in responses. Printing with json.dumps with indent ensures the output is readable and shows the expanded structure.
Common mistakes
- Mutating resources without deep copying can cause side effects in other parts of the code. Use `copy.deepcopy` if you need to preserve the original.
- Assuming every resource has the same embedded structure; in real APIs, related resources differ by type.
- Forgetting to handle missing resource keys when expanding in production code.
- Overwriting existing 'embedded' keys without checking whether the resource already has related data.
Variations
- Use a dict comprehension to build a new list of resources with embedded data instead of modifying in place.
- Make `_generate_embed` accept a resource type to produce different mock embeds per relationship.
Real-world use cases
- Mocking API responses in unit tests to verify your client handles embedded relationships correctly without a live server.
- Prototyping a REST API endpoint that returns related resources inline, allowing frontend teams to develop against realistic data.
- Generating sample payloads for API documentation or performance testing to simulate how embedded resources will look in production.
Sponsored
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.