Bird
Raised Fist0
FastAPIframework~5 mins

Filtering and sorting in FastAPI

Choose your learning style10 modes available
Introduction

Filtering and sorting help you get just the data you want from a list or database. It makes your app faster and easier to use.

You want to show only items that match a search term.
You want to order a list of products by price or name.
You want users to find data by date or category.
You want to reduce the amount of data sent to the user.
You want to create a simple API that returns filtered results.
Syntax
FastAPI
from fastapi import FastAPI, Query
from typing import List, Optional

app = FastAPI()

@app.get("/items/")
async def read_items(
    q: Optional[str] = Query(None, min_length=3, max_length=50),
    sort_by: Optional[str] = Query(None, regex="^(name|price)$")
):
    # Your filtering and sorting logic here
    pass

Use Query to declare query parameters with validation.

Optional parameters can be used to filter or sort if provided.

Examples
This example shows filtering by category and sorting by price or name.
FastAPI
from fastapi import FastAPI, Query
from typing import Optional

app = FastAPI()

@app.get("/products/")
async def get_products(
    category: Optional[str] = Query(None),
    sort_by: Optional[str] = Query(None, regex="^(price|name)$")
):
    return {"category": category, "sort_by": sort_by}
This example sorts a fixed list of items by the given field.
FastAPI
from fastapi import FastAPI

app = FastAPI()

items = [
    {"name": "apple", "price": 5},
    {"name": "banana", "price": 3},
    {"name": "carrot", "price": 4}
]

@app.get("/items/")
async def read_items(sort_by: str = "name"):
    sorted_items = sorted(items, key=lambda x: x[sort_by])
    return sorted_items
Sample Program

This FastAPI app has an endpoint /items/ that lets you filter items by a search term q and sort them by name or price. If you don't provide q, it returns all items sorted.

FastAPI
from fastapi import FastAPI, Query
from typing import Optional

app = FastAPI()

items = [
    {"name": "apple", "price": 5},
    {"name": "banana", "price": 3},
    {"name": "carrot", "price": 4}
]

@app.get("/items/")
async def read_items(
    q: Optional[str] = Query(None, min_length=1),
    sort_by: Optional[str] = Query("name", regex="^(name|price)$")
):
    # Filter items by name containing q if q is given
    filtered = [item for item in items if q.lower() in item["name"]] if q else items
    # Sort filtered items by sort_by key
    sorted_items = sorted(filtered, key=lambda x: x[sort_by])
    return sorted_items
OutputSuccess
Important Notes

Use Optional with query parameters to make them optional.

Use Query to add validation like minimum length or regex patterns.

Sorting keys should be checked to avoid errors if invalid keys are passed.

Summary

Filtering lets you get only the data you want by checking conditions.

Sorting arranges data in order, like alphabetically or by number.

FastAPI makes it easy to add filtering and sorting with query parameters.

Practice

(1/5)
1. In FastAPI, what is the main purpose of using query parameters for filtering and sorting?
easy
A. To select only the data that meets certain conditions and order it
B. To change the server settings dynamically
C. To update the database records automatically
D. To create new API endpoints

Solution

  1. Step 1: Understand query parameters in FastAPI

    Query parameters allow clients to send extra information to filter or sort data returned by the API.
  2. Step 2: Identify filtering and sorting purpose

    Filtering selects data based on conditions, and sorting arranges data in a specific order.
  3. Final Answer:

    To select only the data that meets certain conditions and order it -> Option A
  4. Quick Check:

    Filtering and sorting = select and order data [OK]
Hint: Filtering means choosing data; sorting means ordering it [OK]
Common Mistakes:
  • Confusing filtering with updating data
  • Thinking sorting changes server settings
  • Assuming query parameters create new endpoints
2. Which of the following is the correct way to declare a query parameter for sorting by a field named price in a FastAPI endpoint?
easy
A. def get_items(price: str):
B. def get_items(sort: str = Query(None)):
C. def get_items(sort: int):
D. def get_items(sort: bool = True):

Solution

  1. Step 1: Recognize query parameter declaration

    FastAPI uses function parameters with default values or Query() to declare query parameters.
  2. Step 2: Identify correct type and usage for sorting

    Sorting fields are usually strings naming the field, so sort: str = Query(None) is correct.
  3. Final Answer:

    def get_items(sort: str = Query(None)): -> Option B
  4. Quick Check:

    Sort parameter is a string query [OK]
Hint: Sorting fields are strings, use Query for optional params [OK]
Common Mistakes:
  • Using int or bool for sorting parameter
  • Naming parameter incorrectly (like price instead of sort)
  • Not setting default or Query for optional params
3. Given this FastAPI endpoint code, what will be the output if the query parameter sort is set to name?
from fastapi import FastAPI, Query
app = FastAPI()
items = [{"name": "apple", "price": 5}, {"name": "banana", "price": 3}, {"name": "cherry", "price": 7}]

@app.get("/items")
def get_items(sort: str = Query(None)):
    if sort == "name":
        return sorted(items, key=lambda x: x["name"])
    return items
medium
A. [{"name": "banana", "price": 3}, {"name": "apple", "price": 5}, {"name": "cherry", "price": 7}]
B. [{"name": "apple", "price": 5}, {"name": "cherry", "price": 7}, {"name": "banana", "price": 3}]
C. [{"name": "apple", "price": 5}, {"name": "banana", "price": 3}, {"name": "cherry", "price": 7}] sorted by price
D. [{"name": "apple", "price": 5}, {"name": "banana", "price": 3}, {"name": "cherry", "price": 7}]

Solution

  1. Step 1: Understand sorting by name

    The code sorts the list of items by the "name" key alphabetically when sort == "name".
  2. Step 2: Check alphabetical order of names

    Names are "apple", "banana", "cherry" which is already sorted alphabetically.
  3. Final Answer:

    [{"name": "apple", "price": 5}, {"name": "banana", "price": 3}, {"name": "cherry", "price": 7}] -> Option D
  4. Quick Check:

    Sorted by name = original order [OK]
Hint: Check if sorting changes order; if already sorted, output same [OK]
Common Mistakes:
  • Assuming sorting by name changes order when already sorted
  • Confusing sorting by price instead of name
  • Thinking output includes sorting description text
4. Identify the error in this FastAPI endpoint that tries to filter items by minimum price:
from fastapi import FastAPI
app = FastAPI()
items = [{"name": "apple", "price": 5}, {"name": "banana", "price": 3}]

@app.get("/items")
def get_items(min_price: int):
    return [item for item in items if item["price"] > min_price]
medium
A. The items list is not defined properly
B. The comparison operator should be <= instead of >
C. The endpoint will fail if min_price is not provided in the query
D. The list comprehension syntax is incorrect

Solution

  1. Step 1: Check parameter declaration

    The parameter min_price has no default value, so it is required in the query.
  2. Step 2: Understand what happens if parameter missing

    If the client does not provide min_price, FastAPI returns a 422 error because the parameter is missing.
  3. Final Answer:

    The endpoint will fail if min_price is not provided in the query -> Option C
  4. Quick Check:

    Required query param missing causes failure [OK]
Hint: Required query params must be provided or cause error [OK]
Common Mistakes:
  • Thinking comparison operator is wrong
  • Believing list comprehension syntax is invalid
  • Assuming items list is undefined
5. You want to create a FastAPI endpoint that returns items filtered by a minimum price and sorted by either name or price. Which code snippet correctly implements this filtering and sorting logic?
hard
A. def get_items(min_price: int = 0, sort: str = None): filtered = [item for item in items if item["price"] >= min_price] if sort == "name": return sorted(filtered, key=lambda x: x["name"]) elif sort == "price": return sorted(filtered, key=lambda x: x["price"]) return filtered
B. def get_items(min_price: int, sort: str): filtered = [item for item in items if item["price"] > min_price] if sort == "name": return sorted(items, key=lambda x: x["name"]) return filtered
C. def get_items(min_price: int = None, sort: str = "price"): filtered = [item for item in items if item["price"] > min_price] return sorted(filtered, key=lambda x: x[sort])
D. def get_items(min_price: int = 0, sort: str = None): filtered = [item for item in items if item["price"] >= min_price] if sort == "price": return sorted(filtered, key=lambda x: x["price"]) return filtered

Solution

  1. Step 1: Check filtering logic

    def get_items(min_price: int = 0, sort: str = None): filtered = [item for item in items if item["price"] >= min_price] if sort == "name": return sorted(filtered, key=lambda x: x["name"]) elif sort == "price": return sorted(filtered, key=lambda x: x["price"]) return filtered filters items with price >= min_price, which is correct and uses a default value for optional param.
  2. Step 2: Check sorting logic

    def get_items(min_price: int = 0, sort: str = None): filtered = [item for item in items if item["price"] >= min_price] if sort == "name": return sorted(filtered, key=lambda x: x["name"]) elif sort == "price": return sorted(filtered, key=lambda x: x["price"]) return filtered sorts filtered items by name or price if requested, otherwise returns filtered list.
  3. Step 3: Verify other options

    def get_items(min_price: int, sort: str): filtered = [item for item in items if item["price"] > min_price] if sort == "name": return sorted(items, key=lambda x: x["name"]) return filtered does not sort by price and uses > instead of >=; def get_items(min_price: int = None, sort: str = "price"): filtered = [item for item in items if item["price"] > min_price] return sorted(filtered, key=lambda x: x[sort]) may fail if min_price is None; def get_items(min_price: int = 0, sort: str = None): filtered = [item for item in items if item["price"] >= min_price] if sort == "price": return sorted(filtered, key=lambda x: x["price"]) return filtered only sorts by price, missing name sorting.
  4. Final Answer:

    Option A correctly filters and sorts by name or price with defaults -> Option A
  5. Quick Check:

    Filter with default and conditional sort = def get_items(min_price: int = 0, sort: str = None): filtered = [item for item in items if item["price"] >= min_price] if sort == "name": return sorted(filtered, key=lambda x: x["name"]) elif sort == "price": return sorted(filtered, key=lambda x: x["price"]) return filtered [OK]
Hint: Use defaults and check both filter and sort conditions [OK]
Common Mistakes:
  • Not providing default values for query parameters
  • Sorting original list instead of filtered list
  • Using > instead of >= for filtering
  • Not handling both sorting options
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard