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.

Easy Python 3.6+ Aug 9, 2026 API design & gRPC 13 views 0 copies

Python code

17 lines
Python 3.6+
import 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

stdout
{
  "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

  1. Use a dataclass with a custom `to_dict` method for more concise code.
  2. 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

Run this sample

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

Open editor

More from API design & gRPC

Related tutorials and quizzes for this topic.