Python / FastAPI Basics 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 |
More Related questions...