List All Expenses
Add a GET endpoint that returns all stored expenses
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
The problem
Right now, your API can create expenses but has no way to retrieve them. You can add data, but you cannot see what you added. A GET endpoint solves this by returning everything stored in the dictionary.
How it works
The expenses dictionary stores each expense as a value. Calling expenses.values() returns all the values, but FastAPI needs a list to serialize the response as JSON. Wrapping it in list() converts it to a format FastAPI can return.
list(expenses.values()) # [{"id": 1, "description": "Lunch", ...}, ...]
Instructions
- Add the
@app.get("/expenses")decorator above the function. - Define a function named
list_expensesthat takes no parameters. - Return
list(expenses.values()).
from datetime import datetime
from fastapi import FastAPI
from pydantic import BaseModel, Field, field_validator
from typing import Literal, Optional
app = FastAPI()
class Expense(BaseModel):
description: str = Field(min_length=1)
amount: float = Field(gt=0)
category: Literal["food", "transport", "entertainment", "utilities", "other"]
date: Optional[str] = None
@field_validator("date")
@classmethod
def validate_date_format(cls, v):
if v is not None:
try:
datetime.strptime(v, "%Y-%m-%d")
except ValueError:
raise ValueError("Date must be in YYYY-MM-DD format")
return v
expenses = {}
counter = 0
@app.post("/expenses", status_code=201)
def create_expense(expense: Expense):
global counter
counter += 1
expenses[counter] = {"id": counter, **expense.model_dump()}
return expenses[counter]
# Step 1: Add @app.get("/expenses")
# Step 2: Define list_expenses
# Step 3: Return list(expenses.values())
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding