Write the POST Endpoint
Exit

Write the POST Endpoint

Define the POST route and function that receives an Expense

💻

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

Where do expenses go?

Your API can validate expenses, but it has nowhere to put them. You need two things:

  • A storage dictionary (expenses = {}): holds every expense, keyed by its unique identifier.
  • An identifier counter (counter = 0): tracks the next identifier to assign. Each new expense gets counter + 1.

A dictionary works well here because you can look up any expense by its identifier in one step: expenses[1] returns expense number 1 instantly.

Decorators and status codes

The @app.post decorator registers a function to handle POST requests at a given URL path:

@app.post("/expenses", status_code=201)
def create_expense(expense: Expense):
    ...

The status_code=201 parameter tells FastAPI to return HTTP status 201 Created instead of the default 200. Status 201 signals to the client that a new resource was created, not just retrieved.

Type hint triggers validation

The expense: Expense parameter does all the work. FastAPI sees the Pydantic type and automatically:

  1. Reads JSON from the request body.
  2. Validates it against the Expense model.
  3. Returns a 422 error if the data is invalid.

Your function only runs if the data passes every validation rule you defined in your Expense model.

Instructions

Set up the storage and define the POST endpoint signature.

  1. Below the Expense class, add the storage dictionary expenses = {}.
  2. Below expenses, add the identifier counter counter = 0.
  3. Add the decorator @app.post("/expenses", status_code=201).
  4. Define a function named create_expense with an expense parameter of type Expense. Use pass as the function body.