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=mediumExample
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
| Concept | Description | Example |
|---|---|---|
| Start query | Use ? to begin query parameters | https://api.com/items? |
| Add filter | Use key=value pairs | category=books |
| Multiple filters | Separate with & | category=books&price=20 |
| Encode values | Replace spaces with %20 | name=red%20shirt |
| Type conversion | Convert strings to needed types | max_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.