Path Operations and Route Parameters

Path Operations and Route Parameters

Master the basics of routing in FastAPI. Learn about path operation decorators, naming conventions, and extracting variables from URLs.

Path Operations and Route Parameters

Routing is the "Dispatcher" of your API. It takes a URL like /users/42 and directs it to the specific function that knows how to handle user 42. In FastAPI, we call these Path Operations.

In this lesson, we master the decorators and path parameters that make your API navigable.


1. The Path Operation Decorator

A decorator in Python is the @ symbol prefixing a function. In FastAPI, the decorator tells the framework: "When a request comes to this URL with this Method, run this function."

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

Components of a Path Operation:

  • Path: /items/{item_id}
  • Operation: GET
  • Function: read_item
  • Parameter: item_id (Extracted from the URL)

2. Path Parameters and Type Validation

Whatever you put inside curly braces {} in the path becomes a variable in your function.

Why Type Hints are Critical:

If you define item_id: int, FastAPI will check the URL.

  • Success: /items/5 -> item_id becomes the integer 5.
  • Failure: /items/portal -> FastAPI returns a 422 Unprocessable Entity error automatically because "portal" is not an integer.

3. Order Matters!

FastAPI evaluates routes in the order they are defined. If you have two routes that could match the same URL, the first one wins.

@app.get("/users/me")
async def read_user_me():
    return {"user_id": "the current user"}

@app.get("/users/{user_id}")
async def read_user(user_id: str):
    return {"user_id": user_id}

If you swapped these, /users/me would match {user_id} and return {"user_id": "me"} instead of the intended "current user" logic.


4. Metadata: Summary and Tags

You can add metadata to your decorators to improve your automatic documentation.

@app.get(
    "/items/{item_id}", 
    summary="Fetch a specific item by ID",
    tags=["Inventory"]
)
async def read_item(item_id: int):
    """
    Detailed description that will appear in the Swagger docs.
    """
    return {"item_id": item_id}

Visualizing the Routing Logic

graph TD
    A["Request: GET /items/42"] --> B{Does /items/me match?}
    B -- No --> C{Does /items/{item_id} match?}
    C -- Yes --> D["Validate '42' is int"]
    D -- Success --> E["Run read_item(42)"]
    D -- Failure --> F["422 Error Response"]

Summary

  • Decorators map Methods and Paths to functions.
  • Path Parameters extract data directly from the URL.
  • Type Hints provide automatic validation and error handling.
  • Order of definition is crucial for overlapping paths.

In the next lesson, we’ll look at Query Parameters—the optional data often used for filtering and pagination.


Exercise: The Path Fixer

You have an endpoint @app.get("/files/{file_path}"). You want to make sure the user can only provide a file_path that ends in .txt. Note: We haven't covered custom validation yet, but based on what you know about Python types, could you use a specific type hint here?

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn