0
0
Rest-apiHow-ToBeginner ยท 4 min read

How to Use Query Parameters for Filter in REST APIs

Use query parameters in the URL to filter data in REST APIs by adding key-value pairs after a question mark, like ?key=value. Multiple filters can be combined using &, for example, ?type=book&author=John. The server reads these parameters to return only matching results.
๐Ÿ“

Syntax

Query parameters are added to the URL after a ? mark. Each filter is a key=value pair. Multiple filters are joined by &.

  • ? starts the query string
  • key=value defines a filter
  • & separates multiple filters
http
https://api.example.com/items?color=red&size=medium
๐Ÿ’ป

Example

This example shows a simple REST API endpoint that filters a list of products by category and price using query parameters.

python
from flask import Flask, request, jsonify

app = Flask(__name__)

products = [
    {"id": 1, "name": "T-shirt", "category": "clothing", "price": 20},
    {"id": 2, "name": "Coffee Mug", "category": "kitchen", "price": 10},
    {"id": 3, "name": "Jeans", "category": "clothing", "price": 40},
    {"id": 4, "name": "Blender", "category": "kitchen", "price": 60}
]

@app.route('/products')
def get_products():
    category = request.args.get('category')
    max_price = request.args.get('max_price', type=float)

    filtered = products
    if category:
        filtered = [p for p in filtered if p['category'] == category]
    if max_price is not None:
        filtered = [p for p in filtered if p['price'] <= max_price]

    return jsonify(filtered)

if __name__ == '__main__':
    app.run(debug=True)
Output
Running the server and requesting /products?category=clothing&max_price=30 returns: [ {"id": 1, "name": "T-shirt", "category": "clothing", "price": 20} ]
โš ๏ธ

Common Pitfalls

Common mistakes when using query parameters for filtering include:

  • Not encoding special characters in values (like spaces or &)
  • Using incorrect parameter names that the server does not recognize
  • Assuming all parameters are strings without converting types (e.g., numbers)
  • Not handling missing or empty parameters gracefully
http
Wrong example:
https://api.example.com/items?color=red blue

Right example:
https://api.example.com/items?color=red%20blue
๐Ÿ“Š

Quick Reference

ConceptDescriptionExample
Start queryUse ? to begin query parametershttps://api.com/items?
Add filterUse key=value pairscategory=books
Multiple filtersSeparate with &category=books&price=20
Encode valuesReplace spaces with %20name=red%20shirt
Type conversionConvert strings to needed typesmax_price=30 (as number)
โœ…

Key Takeaways

Use query parameters after ? in the URL to filter API results.
Combine multiple filters with & to narrow down data.
Always encode special characters in query values.
Convert query parameter strings to correct data types in your code.
Handle missing or unexpected parameters gracefully to avoid errors.