Path Parameters in FastAPI

What are Path Parameters?

Path parameters are dynamic parts of a URL that allow you to pass data directly within the path, enabling more flexible and readable API endpoints.

Note:

Path parameters are always required in FastAPI. Even if you assign a default value in the function definition, FastAPI will still expect the value to be present in the URL path. Default values do not make path parameters optional.

Basic Code Example
from fastapi import FastAPI

app = FastAPI()

@app.get('/greet/{name}')
async def greet_user(name):
    greeting_msg = f"Hello!, Good morning {name}."
    return {"message": greeting_msg}

Using Multiple Path Parameters

Multiple path parameters enable capturing and passing dynamic values in the URL, enhancing endpoint flexibility. Each parameter is enclosed in curly braces {}.

Multiple Path Params Example
from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}/posts/{post_id}")
def get_user_post(user_id: int, post_id: int):
    message = "Post details fetched successfully"
    return {"user_id": user_id, "post_id": post_id, "message": message}
                

Path Parameter Type Conversion

FastAPI automatically converts path parameters to the specified data types, such as int, float, or str. This ensures that the values passed in the URL are correctly interpreted and validated according to the function's parameter type.

Type Conversion Example
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}/price/{price}")
def get_item(item_id: int, price: float):
    return {"item_id": item_id, "price": price}

Path Parameters with Enum

You can use Enums in FastAPI as path parameters to restrict values to a set of predefined options. This makes sure the path only accepts specific values.

model.value: Returns the value of the enum member (e.g., "Books").

model.name: Returns the name of the enum member (e.g., "books").

Enum Path Params Example
from fastapi import FastAPI
from enum import Enum

app = FastAPI()

class Category(str, Enum):
    electronics = "Electronics"
    clothing = "Clothing"
    books = "Books"

@app.get("/items/{category}")
def get_items_by_category(category: Category):
    message = f"Fetching items in {category} category"
    # Get value and name of the enum
    value = category.value  # Output: Books
    name = category.name  # Output: books
    return {"category": category, "message": message}

Path Parameters with Slashes (Path Converters)

Path converters let you capture values in URLs with slashes, like /items/123/details/456. This is helpful for dealing with nested or related data. FastAPI automatically converts these captured values into function parameters for easy use.

Path Converter Example
from fastapi import FastAPI

app = FastAPI()

@app.get("/files/{file_path:path}")
def read_file(file_path: str):
    message = "File path received successfully"
    return {"file_path": file_path, "message": message}

The Order of Path Parameters Matters

In FastAPI, the order in which you define routes affects how requests are matched. If a dynamic route like /blog/{blog_id} is defined before a specific one like /blog/latest, then a request to /blog/latest will be wrongly handled as if "latest" is a blog_id.

To avoid this, always place specific routes before dynamic ones.

Correct Order of Routes
from fastapi import FastAPI

app = FastAPI()

@app.get("/blog/latest")
async def get_latest_blog():
    return {"message": "This is the latest blog post."}

@app.get("/blog/{blog_id}")
async def get_blog(blog_id: str):
    return {"message": f"Fetching blog post with ID: {blog_id}"}

Exercise

  1. Fill in the Blanks:
    • - Django is a __________ written in Python that simplifies web development.
    • - Django follows the __________ architecture, which stands for __________.
    • - To install Django, the package manager used is __________.
    • - You can check the installed Django version using the command __________.
    • - MVC stands for __________.