Filtering in REST APIs — Complete Guide
In this tutorial, you will learn about Filtering in REST APIs. We cover key concepts, practical examples, and best practices to help you master this topic.
Filtering in REST APIs narrows result sets based on field values using query parameters, enabling clients to retrieve only the data matching specific conditions without fetching and processing all resources.
flowchart LR
A[Client] -->|GET /users?role=admin| B[Server]
B --> C{Apply Filter}
C -->|role = admin| D[Filtered Results]
A -->|GET /users?age>=18| E[Server]
E --> F[Apply Range Filter]
style A fill:#e1f5fe
style D fill:#c8e6c9
Filtering typically uses query parameters matching field names. A simple equality filter is ?role=admin. Range filters use operators like ?age__gte=18 or ?price[gte]=100. Text search uses ?q=searchterm or ?name__contains=alice.
Think of filtering like searching for a book in a library catalog. Without filtering, you get every book. With filtering, you specify the author, genre, and publication year to find exactly what you want.
Example: Simple Equality Filtering
import requests
# Filter by single field
response = requests.get(
"https://api.example.com/users",
params={"role": "admin"}
)
users = response.json()
for user in users:
print(f"{user['name']} - {user['role']}")
Expected output:
Admin User - admin
Super Admin - admin
Example: Multiple Filter Parameters
import requests
response = requests.get(
"https://api.example.com/products",
params={
"category": "electronics",
"in_stock": True,
"price_gte": 100,
"price_lte": 500
}
)
print(f"Products found: {len(response.json())}")
print(f"URL: {response.url}")
Expected output:
Products found: 12
URL: https://api.example.com/products?category=electronics&in_stock=True&price_gte=100&price_lte=500
Example: Text Search and Complex Filters
import requests
# Text search across multiple fields
response = requests.get(
"https://api.example.com/users",
params={"q": "alice", "search_fields": "name,email"}
)
print(f"Search results: {response.json()}")
# Combined filters
response = requests.get(
"https://api.example.com/orders",
params={
"status": "pending,processing",
"created_at_gte": "2026-01-01",
"created_at_lte": "2026-06-28",
"sort": "-total"
}
)
print(f"Orders found: {len(response.json())}")
Expected output:
Search results: [{"id": 1, "name": "Alice"}, {"id": 42, "name": "Alice Smith"}]
Orders found: 5
Common Mistakes
- No filtering at all — Returning all resources without filtering forces clients to download and filter on their end, wasting bandwidth and processing power.
- Inconsistent filter parameter names — Using
?user_id=in one endpoint and?userId=in another makes the API unpredictable. - Allowing uncontrolled filtering — Letting clients filter on any field without validation can expose sensitive data or cause slow queries.
- Not documenting supported filters — Clients should know which fields are filterable without trial and error.
- Ignoring filter injection attacks — Filter parameters can be used for injection attacks if not properly sanitized.
Practice Questions
- How do you implement range filtering for numeric fields?
- What is the purpose of the q query parameter in search?
- How do you handle OR conditions in filtering?
- Why should you whitelist filterable fields?
- Challenge: Design a filter system for a hotel booking API that supports filtering by price range, star rating, amenities (Wifi, pool), location, and availability dates.
FAQ
Mini Project
Build a Python function that takes a dictionary of filter parameters and constructs a SQL WHERE clause with proper sanitization. Support operators like eq, neq, gte, lte, contains, and in. Test with various filter combinations.
What's Next
Now learn about sorting in REST API Design.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro