Search Descriptions
Exit

Search Descriptions

Add a search query parameter to GET /expenses using contains

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Searching inside text

The last query addition lets clients find expenses by keyword. A search for "coffee" should return any expense whose description contains that word, regardless of case or position.

SQLModel's .contains() method maps to a SQL LIKE query:

if search:
    statement = statement.where(Expense.description.contains(search))

Expense.description.contains(search) generates WHERE description LIKE '%coffee%'. The % wildcards match any characters before or after the search term. SQLite's LIKE is case-insensitive for ASCII characters by default, so searching for "coffee" also matches "Coffee" or "COFFEE".

This chains with the existing conditions — you can combine ?category=food&search=coffee to find food expenses that mention coffee in the description.

Instructions

Add a search query parameter to list_expenses.

  1. Add search: Optional[str] = None as a new parameter to list_expenses, after end.
  2. After the if end: block, add an if search: block. Inside it, reassign statement = statement.where(Expense.description.contains(search)).