0
0
Rest APIprogramming~5 mins

Pagination with limit and offset in Rest API

Choose your learning style9 modes available
Introduction

Pagination helps to split large lists of data into smaller parts. This makes it easier and faster to get and show data step by step.

When showing a list of products on an online store page.
When loading user comments on a blog post little by little.
When fetching search results from a database in chunks.
When displaying messages in a chat app page by page.
When limiting data sent over the internet to save bandwidth.
Syntax
Rest API
GET /items?limit=10&offset=20

limit tells how many items to get.

offset tells where to start counting items from.

Examples
Get the first 5 users starting from the beginning.
Rest API
GET /users?limit=5&offset=0
Get 10 posts starting from the 11th post (offset 10 means skip first 10).
Rest API
GET /posts?limit=10&offset=10
Get 3 comments starting from the 7th comment.
Rest API
GET /comments?limit=3&offset=6
Sample Program

This small web app uses Flask to create an API endpoint /items. You can add limit and offset as query parameters to get parts of the list of numbers from 1 to 100.

For example, /items?limit=5&offset=10 returns 5 items starting from the 11th number.

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():
    try:
        limit = int(request.args.get('limit', 10))
        offset = int(request.args.get('offset', 0))
    except ValueError:
        return jsonify({'error': 'limit and offset must be integers'}), 400

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

    return jsonify({
        'limit': limit,
        'offset': offset,
        'items': sliced_items
    })

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

Always check that limit and offset are valid numbers to avoid errors.

Use reasonable limit values to avoid sending too much data at once.

Offset starts at 0, meaning the first item is at offset 0.

Summary

Pagination splits data into smaller parts using limit and offset.

limit controls how many items to get, offset controls where to start.

This helps apps load data faster and saves internet bandwidth.