Python / FastAPI Interview Questions
What is the difference between path parameters and query parameters in FastAPI?
Path parameters are part of the URL path itself, declared with curly braces in the decorator and as function arguments. Query parameters are declared as function arguments that do not appear in the path string — FastAPI reads them from the URL query string automatically.
from fastapi import FastAPI
from enum import Enum
app = FastAPI()
# PATH parameter: part of the URL — /users/42
@app.get("/users/{user_id}")
def get_user(user_id: int): # int type enforced automatically
return {"user_id": user_id}
# QUERY parameters: after ? in URL — /items?skip=0&limit=10
@app.get("/items")
def list_items(
skip: int = 0, # optional, default 0
limit: int = 10, # optional, default 10
search: str | None = None, # fully optional
):
return {"skip": skip, "limit": limit, "search": search}
# Enum path param — validates allowed values
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
@app.get("/models/{model_name}")
def get_model(model_name: ModelName):
return {"model": model_name}| Aspect | Path param | Query param |
|---|---|---|
| URL example | /users/{id} | /users?id=42 |
| Declaration | In path string + function arg | Function arg only (not in path) |
| Required by default? | Yes — URL won't match without it | No if it has a default value |
| Type validation | Yes — automatic via type hint | Yes — automatic via type hint |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
