You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中如何获取名称为Python关键字的查询参数?

Solution for Handling Python Keyword Query Params in FastAPI

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 Query class with the alias parameter 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 ... inside Query(...) 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:

  1. Recognize the from query param via the alias configuration
  2. Assign its value to the from_ variable in your function
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:03:15