Skip to content

Filtering in REST APIs — Complete Guide

DodaTech Updated 2026-06-28 3 min read

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

  1. No filtering at all — Returning all resources without filtering forces clients to download and filter on their end, wasting bandwidth and processing power.
  2. Inconsistent filter parameter names — Using ?user_id= in one endpoint and ?userId= in another makes the API unpredictable.
  3. Allowing uncontrolled filtering — Letting clients filter on any field without validation can expose sensitive data or cause slow queries.
  4. Not documenting supported filters — Clients should know which fields are filterable without trial and error.
  5. Ignoring filter injection attacks — Filter parameters can be used for injection attacks if not properly sanitized.

Practice Questions

  1. How do you implement range filtering for numeric fields?
  2. What is the purpose of the q query parameter in search?
  3. How do you handle OR conditions in filtering?
  4. Why should you whitelist filterable fields?
  5. 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

Should I use ?filter[name]=value or ?name=value?

?name=value is simpler and more common. Use a filter object syntax (?filter[name]=value) only when you need complex nested filters.

How do I implement case-insensitive filtering?

Convert both the stored value and the filter parameter to lowercase before comparison. This is usually done in the database query.

What is the best way to filter by date range?

Use ?created_at_gte=2026-01-01&created_at_lte=2026-06-28 where gte means greater than or equal and lte means less than or equal.

Should I allow filtering on all fields?

No, whitelist filterable fields on the server. Some fields may be expensive to filter on or may expose internal data.

How do I handle OR conditions in filtering?

Use comma-separated values: ?status=pending,processing means OR. Use separate parameters for AND: ?category=books&in_stock=true.

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