gerladeno
gerladeno

Reputation: 13

Is it possible to get query params using fastapi if param's name is a python keyword?

I'm having a following issue.

We're developing our own custom testing framework, and for testing purposes I have to create a stub for one of our services. The idea is to implement it using FastApi, however I've encountered a problem. Query string to that service looks as follows:

xrRequestTmpl = `%s/v2/click/rates?from=%s&to=%s&ticks=true&ts=%v`

As you can see, one of the query params is 'from' which is a python keyword, so I can't use

from fastapi import FastApi

xr = FastAPI()
@xr.get('/v2/click/{path}')
def rates(path, from, to, ticks, ts):
    pass

python obviously interprets 'from' as a import-related keyword and doesn't allow such syntax. Unfortunately I absolutely cannot change the syntax of a query string since it is already integrated in prod env, so I have to somehow receive these parameters.

I would be very grateful for a working code example or at least a tip. Using another library (not fastapi) is a really less preferable solution due to specifics of said testing framework.

Upvotes: 1

Views: 1499

Answers (1)

Yagiz Degirmenci
Yagiz Degirmenci

Reputation: 20756

Yes it is possible, you can use an alias.

from fastapi import FastAPI

app = FastAPI()

@app.get('/my_path')
def rates(_from: str = Query(..., alias="from")):
    pass

Upvotes: 4

Related Questions