0
0
Rest APIprogramming~5 mins

Query parameters for filtering in Rest API

Choose your learning style9 modes available
Introduction

Query parameters help you ask for only the data you want from a list. They make responses smaller and faster.

You want to find all books by a certain author from a big library database.
You want to see only active users in a user list.
You want to get products cheaper than a certain price in an online store.
You want to search for events happening after a specific date.
You want to filter blog posts by category or tag.
Syntax
Rest API
/resource?key1=value1&key2=value2

Use ? to start query parameters after the main URL.

Use & to add more filters.

Examples
Get books where the author is Jane Austen.
Rest API
/books?author=Jane%20Austen
Get users who are active and 30 years old.
Rest API
/users?status=active&age=30
Get products with price less than 50.
Rest API
/products?price_lt=50
Sample Program

This small web app shows how to filter books by author using query parameters. If you visit /books?author=Jane%20Austen, it returns only books by Jane Austen.

Rest API
from flask import Flask, request, jsonify

app = Flask(__name__)

# Sample data
books = [
    {"id": 1, "title": "Pride and Prejudice", "author": "Jane Austen"},
    {"id": 2, "title": "1984", "author": "George Orwell"},
    {"id": 3, "title": "Emma", "author": "Jane Austen"}
]

@app.route('/books')
def get_books():
    author = request.args.get('author')
    if author:
        filtered = [book for book in books if book['author'].lower() == author.lower()]
    else:
        filtered = books
    return jsonify(filtered)

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

Query parameters are case-sensitive in URLs but you can handle case in your code.

Always encode special characters in query parameters (like spaces become %20).

Filtering on the server side helps reduce data sent over the internet.

Summary

Query parameters let you ask for specific data from a big list.

They start with ? and use & to add more filters.

Use them to make your app faster and easier to use.