How to Add HATEOAS Links to a Python API Response
Build a Python API resource class that adds self and next HATEOAS links to JSON responses, with a mock example for pagination.
Python code
17 linesimport json
class Resource:
def __init__(self, name, data, next_page=None):
self.links = {"self": f"/api/resources/{name}"}
if next_page is not None:
self.links["next"] = f"/api/resources?page={next_page}"
self.data = data
def to_dict(self):
return {"links": self.links, "data": self.data}
if __name__ == "__main__":
resource = Resource("item-42", {"id": 42, "value": "example"}, next_page=3)
print(json.dumps(resource.to_dict(), indent=2))
Output
{
"links": {
"self": "/api/resources/item-42",
"next": "/api/resources?page=3"
},
"data": {
"id": 42,
"value": "example"
}
}
How it works
The Resource class encapsulates HATEOAS link generation in a reusable way. The self link is always set, while the next link is conditionally added only when a next_page value is provided. The to_dict method converts the resource into a dictionary with links and data keys, ready for JSON serialization. Using json.dumps with indent=2 produces readable, formatted output for API clients. This pattern keeps your API response structure consistent and discoverable.
Common mistakes
- Forgetting to conditionally include the next link when there is no next page.
- Hardcoding link URLs instead of generating them dynamically from resource context.
- Not separating the link structure from the data payload, breaking HATEOAS conventions.
Variations
- Use a dataclass with a custom `to_dict` method for more concise code.
- Generate links using a URL builder function that takes a request context.
Real-world use cases
- Building a paginated REST API that lets clients navigate to the next page via a self-describing link.
- Implementing discoverable API endpoints where clients traverse related resources without hardcoding paths.
- Creating a mock API server for testing frontends that rely on HATEOAS navigation.
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.