Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI variable query parameters

Tags:

python

fastapi

I am writing a Fast API server that accepts requests, checks if users are authorized and then redirects them to another URL if successful.

I need to carry over URL parameters, e.g.

http://localhost:80/data/?param1=val1&param2=val2 should redirect to http://some.other.api/?param1=val1&param2=val2, thus keeping previously allotted parameters.

The parameters are not controlled by me and could change at any moment.

How can I achieve this?

Code:

from fastapi import FastAPI
from starlette.responses import RedirectResponse

app = FastAPI()

@app.get("/data/")
async def api_data():
    params = '' # I need this value
    url = f'http://some.other.api/{params}'
    response = RedirectResponse(url=url)
    return response

like image 340
Werner Avatar asked Jun 09 '20 09:06

Werner


2 Answers

In the docs they talk about using the Request directly, which then lead me to this:

from fastapi import FastAPI, Request
from starlette.responses import RedirectResponse

app = FastAPI()

@app.get("/data/")
async def api_data(request: Request):
    params = request.query_params
    url = f'http://some.other.api/?{params}'
    response = RedirectResponse(url=url)
    return response
like image 136
Werner Avatar answered Sep 23 '22 18:09

Werner


As mention in docs of FastAPI https://fastapi.tiangolo.com/tutorial/query-params-str-validations/.

 @app.get("/")
 def read_root(param1: Optional[str] = None, param2: Optional[str] = None):
     url = f'http://some.other.api/{param1}/{param2}'
     return {'url': str(url)}

output

enter image description here

enter image description here

like image 29
qaiser Avatar answered Sep 23 '22 18:09

qaiser