Link headers help clients find related pages or resources easily when using APIs. They guide navigation without needing extra data in the response body.
Link headers for navigation in Rest API
Link: <url1>; rel="relation1", <url2>; rel="relation2"
The Link header contains one or more links separated by commas.
Each link has a URL in angle brackets and a rel attribute describing its relation (like next, prev, first, last).
Link: <https://api.example.com/items?page=2>; rel="next"
Link: <https://api.example.com/items?page=1>; rel="first", <https://api.example.com/items?page=5>; rel="last"
Link: <https://api.example.com/items?page=3>; rel="prev", <https://api.example.com/items?page=5>; rel="next"
This Flask API returns a list of items in pages of 10. It adds a Link header with URLs for next, previous, first, and last pages to help clients navigate easily.
from flask import Flask, jsonify, request, Response app = Flask(__name__) items = list(range(1, 51)) # 50 items PAGE_SIZE = 10 @app.route('/items') def get_items(): page = int(request.args.get('page', 1)) start = (page - 1) * PAGE_SIZE end = start + PAGE_SIZE data = items[start:end] links = [] base_url = request.base_url if end < len(items): links.append(f'<{base_url}?page={page + 1}>; rel="next"') if page > 1: links.append(f'<{base_url}?page={page - 1}>; rel="prev"') links.append(f'<{base_url}?page=1>; rel="first"') last_page = (len(items) + PAGE_SIZE - 1) // PAGE_SIZE links.append(f'<{base_url}?page={last_page}>; rel="last"') link_header = ', '.join(links) response = jsonify({"page": page, "items": data}) response.headers['Link'] = link_header return response if __name__ == '__main__': app.run(debug=True)
Always use rel values that clearly describe the link's purpose.
Clients can read the Link header to know where to go next without guessing URLs.
Link headers keep navigation info separate from the main data, making APIs cleaner.
Link headers provide URLs for navigating between related API pages or resources.
They use the rel attribute to describe the link's role, like next or prev.
Using link headers helps clients find data easily and keeps API responses organized.