0
0
FastAPIframework~5 mins

Path parameters in FastAPI

Choose your learning style9 modes available
Introduction

Path parameters let you get values directly from the URL. This helps your app respond differently based on what the user asks for.

You want to get a user ID from the URL to show their profile.
You need to fetch a product by its ID from the URL.
You want to create URLs that change based on the item requested.
You want to build REST APIs where resources are identified by URL parts.
Syntax
FastAPI
from fastapi import FastAPI

app = FastAPI()

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

Use curly braces {} in the path to mark a path parameter.

Define the parameter in the function with the same name and type.

Examples
Get a user ID from the URL and return it.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    return {"user_id": user_id}
Use :path to capture a path parameter that can include slashes.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
    return {"file_path": file_path}
Path parameter can be string type too.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/orders/{order_id}")
async def get_order(order_id: str):
    return {"order_id": order_id}
Sample Program

This app returns a message with the book ID taken from the URL path.

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/books/{book_id}")
async def read_book(book_id: int):
    return {"book_id": book_id, "message": f"You requested book {book_id}"}
OutputSuccess
Important Notes

Path parameters are required by default. The URL must include them.

FastAPI converts the parameter to the declared type automatically.

Use descriptive names for path parameters to keep URLs clear.

Summary

Path parameters let you get values from the URL path.

Use curly braces {} in the route to declare them.

They help make your API flexible and dynamic.