0
0
Rest-apiHow-ToBeginner ยท 3 min read

How to Use Link Header for Pagination in REST APIs

Use the Link HTTP header to provide URLs for pagination in REST APIs by including relations like next, prev, first, and last. Each link is enclosed in angle brackets and followed by a rel attribute to indicate its role in navigation.
๐Ÿ“

Syntax

The Link header contains one or more links separated by commas. Each link has this format:

  • <URL>: The URL for the page.
  • rel="relation": Describes the link's role, such as next, prev, first, or last.

Example:

Link: <https://api.example.com/items?page=2>; rel="next", <https://api.example.com/items?page=5>; rel="last"
http
Link: <https://api.example.com/items?page=2>; rel="next", <https://api.example.com/items?page=5>; rel="last"
๐Ÿ’ป

Example

This example shows a simple HTTP response with a Link header for pagination. It provides URLs for the next page and the last page of results.

http
HTTP/1.1 200 OK
Content-Type: application/json
Link: <https://api.example.com/items?page=2>; rel="next", <https://api.example.com/items?page=5>; rel="last"

[
  {"id": 11, "name": "Item 11"},
  {"id": 12, "name": "Item 12"}
]
Output
[ {"id": 11, "name": "Item 11"}, {"id": 12, "name": "Item 12"} ]
โš ๏ธ

Common Pitfalls

  • Not including the rel attribute, which makes it unclear what each link represents.
  • Using incorrect URL formatting, such as missing angle brackets <>.
  • Providing incomplete pagination links, like only next without last or prev, which can confuse clients.
  • Forgetting to update the Link header on every paginated response.

Correct usage ensures clients can navigate pages easily.

http
Wrong:
Link: https://api.example.com/items?page=2; rel="next"

Right:
Link: <https://api.example.com/items?page=2>; rel="next"
๐Ÿ“Š

Quick Reference

PartDescriptionExample
URLThe link to the page, enclosed in < and >
relRelation type indicating the link's purposerel="next"
Multiple linksSeparate multiple links with commas; rel="next", ; rel="last"
Common rel valuesnext, prev, first, lastrel="prev"
โœ…

Key Takeaways

Use the Link header with angle brackets and rel attributes to indicate pagination URLs.
Include at least next and last relations for clear navigation.
Always update the Link header on every paginated response.
Avoid missing rel attributes or malformed URLs to prevent client confusion.
Separate multiple links with commas in a single Link header.