0
0
Rest APIprogramming~5 mins

Pagination links in Rest API

Choose your learning style9 modes available
Introduction

Pagination links help break large lists of data into smaller pages. This makes it easier and faster to get and show data step by step.

When you have many items and want to show only a few per page in an app or website.
When your API returns a long list and you want to let users get data page by page.
When you want to save bandwidth by sending smaller chunks of data.
When you want to improve user experience by loading data faster in parts.
Syntax
Rest API
Link: <https://api.example.com/items?page=2&size=10>; rel="next",
      <https://api.example.com/items?page=5&size=10>; rel="last"

Each link is inside angle brackets <> and followed by a rel attribute describing its role.

Common rel values are next, prev, first, and last.

Examples
Only the next page link is provided.
Rest API
Link: <https://api.example.com/items?page=2&size=10>; rel="next"
Links for first, previous, and last pages are included.
Rest API
Link: <https://api.example.com/items?page=1&size=10>; rel="first",
      <https://api.example.com/items?page=3&size=10>; rel="prev",
      <https://api.example.com/items?page=5&size=10>; rel="last"
Sample Program

This Flask app returns items in pages. It adds Link headers with URLs for next and previous pages if available.

Rest API
from flask import Flask, request, jsonify, url_for

app = Flask(__name__)

items = list(range(1, 51))  # 50 items

@app.route('/items')
def get_items():
    page = int(request.args.get('page', 1))
    size = int(request.args.get('size', 10))
    start = (page - 1) * size
    end = start + size
    data = items[start:end]

    links = []
    if end < len(items):
        next_url = url_for('get_items', page=page + 1, size=size, _external=True)
        links.append(f'<{next_url}>; rel="next"')
    if page > 1:
        prev_url = url_for('get_items', page=page - 1, size=size, _external=True)
        links.append(f'<{prev_url}>; rel="prev"')

    link_header = ', '.join(links)

    response = jsonify(data)
    if link_header:
        response.headers['Link'] = link_header
    return response

# To run the app, use: flask run

# Example request: GET /items?page=2&size=10
OutputSuccess
Important Notes

Pagination links are usually sent in the HTTP Link header.

Clients use these links to navigate pages without building URLs themselves.

Always include rel to describe the link's purpose clearly.

Summary

Pagination links split data into pages for easier access.

They use URLs with rel attributes like next and prev.

APIs send these links in the Link header to guide clients.