Performance: Basic query parameter declaration
This affects how quickly the server can parse and handle incoming query parameters, impacting response time and user experience.
from fastapi import FastAPI app = FastAPI() @app.get("/items") def read_items(q: str | None = None): # Let FastAPI handle query parameter parsing automatically return {"q": q}
from fastapi import FastAPI app = FastAPI() @app.get("/items") def read_items(q: str = None): # Manually parse query string inside the function # instead of using FastAPI's automatic parsing import urllib.parse query_string = "q=example" params = urllib.parse.parse_qs(query_string) q_value = params.get('q', [None])[0] return {"q": q_value}
| Pattern | CPU Overhead | Code Complexity | Response Time Impact | Verdict |
|---|---|---|---|---|
| Manual query parsing inside endpoint | High (extra parsing) | High (more code) | Increases by ~5-10ms | [X] Bad |
| FastAPI automatic query parameter declaration | Low (built-in) | Low (simple code) | Minimal impact | [OK] Good |
def read_item(q: str = None) -> Option Ditem_id of type int in FastAPI?def read_item(item_id: int): declares item_id as an int without a default, making it required.def read_item(item_id: int): -> Option Afrom fastapi import FastAPI
app = FastAPI()
@app.get('/items/')
def read_items(q: str = 'default'):
return {'q': q}q has a default value of 'default', so it is optional.from fastapi import FastAPI
app = FastAPI()
@app.get('/users/')
def get_user(user_id: int = None):
return {'user_id': user_id}user_id: int = None makes it optional with default None.user_id as an optional query parameter.q which is optional with default None, and limit which is required and an integer. Which is the correct function signature?limit is required (no default), so it must come before optional q with default None.def read_items(limit: int, q: str = None): -> Option APass the test and this pattern moves unknown