0
0
Rest APIprogramming~5 mins

Offset-based pagination in Rest API

Choose your learning style9 modes available
Introduction

Offset-based pagination helps you get a small part of a big list of data, so you don't load everything at once.

When showing search results page by page on a website.
When loading posts in a social media feed little by little.
When displaying products in an online store in chunks.
When you want users to jump to any page of data easily.
When your data source supports skipping items by number.
Syntax
Rest API
GET /items?offset=number&limit=number

offset tells how many items to skip from the start.

limit tells how many items to get after skipping.

Examples
Get the first 10 items, starting from the beginning.
Rest API
GET /items?offset=0&limit=10
Skip the first 10 items, then get the next 10 items (items 11 to 20).
Rest API
GET /items?offset=10&limit=10
Skip 20 items, then get 5 items (items 21 to 25).
Rest API
GET /items?offset=20&limit=5
Sample Program

This small web app shows how to use offset and limit to return parts of a list. You can try URLs like /items?offset=10&limit=5 to get items 11 to 15.

Rest API
from flask import Flask, request, jsonify

app = Flask(__name__)

# Sample data: list of 100 numbers
items = list(range(1, 101))

@app.route('/items')
def get_items():
    # Get offset and limit from query parameters, with defaults
    offset = int(request.args.get('offset', 0))
    limit = int(request.args.get('limit', 10))

    # Get the slice of items
    paged_items = items[offset:offset+limit]

    # Return as JSON
    return jsonify({
        'offset': offset,
        'limit': limit,
        'items': paged_items
    })

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Offset-based pagination is simple but can be slow if the offset is very large because the server skips many items.

It works well when users want to jump to any page number directly.

Remember to validate offset and limit to avoid errors or too large requests.

Summary

Offset-based pagination uses offset to skip items and limit to get a chunk.

It helps load data in small parts for better speed and user experience.

Common in REST APIs for showing pages of results.