FastAPI中如何获取名称为Python关键字的查询参数?
Got it, this is a super common gotcha when working with external APIs that use query param names conflicting with Python keywords. Luckily, FastAPI has a built-in way to handle this without changing your production query string—no need to switch libraries!
Here's the working code example tailored exactly to your use case:
from fastapi import FastAPI, Query xr = FastAPI() @xr.get('/v2/click/rates') # Adjusted path to match your production endpoint template def get_rates( from_: str = Query(..., alias="from"), to: str = Query(...), ticks: bool = Query(...), ts: int = Query(...) ): # Use `from_` in your code instead of the reserved keyword `from` return { "requested_from": from_, "requested_to": to, "ticks_enabled": ticks, "timestamp": ts }
Key Details to Note:
- We use FastAPI's
Queryclass with thealiasparameter to map the actual production query param name (from) to a valid Python variable name (from_). This keeps your code syntactically legal while fully honoring the existing query string format. - The
...insideQuery(...)marks each parameter as required, which matches your production template's mandatory params. - All other params (
to,ticks,ts) work normally since their names don't clash with Python keywords.
How It Works in Practice:
When a request hits your endpoint like https://your-stub-domain/v2/click/rates?from=USD&to=EUR&ticks=true&ts=1699999999, FastAPI will automatically:
- Recognize the
fromquery param via the alias configuration - Assign its value to the
from_variable in your function - Keep all FastAPI perks intact: automatic type validation, OpenAPI documentation generation, and error handling
Alternative (Less Preferred) Fallback:
If you ever need a quick workaround (though we don't recommend it over the alias method), you could access the raw request object to pull the param directly—but this skips FastAPI's built-in validation and type checking:
from fastapi import FastAPI, Request xr = FastAPI() @xr.get('/v2/click/rates') def get_rates(request: Request): from_param = request.query_params.get("from") to = request.query_params.get("to") # ... rest of your stub logic
Stick with the Query alias approach—it's cleaner, more maintainable, and aligns with FastAPI's best practices.
内容的提问来源于stack exchange,提问作者gerladeno

