Path Parameters and Error Handling
Exit

Path Parameters and Error Handling

Understand how FastAPI extracts values from the URL and how to return proper error responses

The problem with the list endpoint

Your API has a GET /expenses endpoint that returns every expense. But a client often needs just one. A mobile app displaying expense details needs to fetch a single record by its unique identifier. Returning all expenses and filtering on the client side wastes bandwidth and processing.

You need an endpoint that accepts an identifier in the URL and returns that one expense.

Path parameters

A path parameter is a dynamic segment in the URL. You declare it with curly braces in the route path:

@app.get("/expenses/{expense_id}")
def get_expense(expense_id: int):
    ...

When a client sends GET /expenses/3, FastAPI extracts 3 from the URL. Because the function parameter has the type hint int, FastAPI converts the string "3" to the integer 3 automatically. If a client sends GET /expenses/abc, FastAPI rejects the request with a 422 validation error — no extra code needed.

Handling missing resources

What happens when a client requests GET /expenses/999 and expense 999 does not exist? Without error handling, your code would return null or raise a KeyError. Neither gives the client useful information.

The standard HTTP response for a missing resource is 404 Not Found. FastAPI provides HTTPException to return the right status code with a clear message:

from fastapi import FastAPI, HTTPException

@app.get("/expenses/{expense_id}")
def get_expense(expense_id: int):
    if expense_id not in expenses:
        raise HTTPException(status_code=404, detail="Expense not found")
    return expenses[expense_id]

The raise statement stops the function immediately. FastAPI catches the exception and sends a JSON response with the status code and detail message:

{"detail": "Expense not found"}

The client receives a 404 status code and a message it can display to the user.

What you will build next

In the next two chapters, you will add two endpoints: one to retrieve a single expense by its identifier, and one to delete an expense. Both use path parameters and the same HTTPException pattern for missing resources.

Next Chapter →