Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Query Parameters as Dictionary in FastAPI [duplicate]

I spent last month learning Flask, and am now moving on to Pyramid and FastAPI. One of the requirements for my application is to get all the query parameters in a dictionary (there are multiple combinations, and I can assume all keys are unique and have a single value)

In Flask, for request like GET /?foo=1&bar=2 I can get the foo and bar parameters from a dictionary like this:

from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def root():
     if 'foo' in request.args:
         return f"foo was provided: {request.args['foo']}", 200
     else:
         return "I need your foo, fool!", 400

I cannot figure out how to do the same easily in FastAPI / Starlette. Best solution I've come up with is to manually build the dictionary by splitting up request.query_params:

from fastapi import FastAPI, Request
app = FastAPI()

@app.get("/")
@app.get("/{path:path}")
def root(path, request: Request):

    request_args = {}
    if request.query_params:
        for _ in str(request.query_params).split("&"):
            [key, value] = _.split("=")
            request_args[key] = str(value)

It certainly seems there should be an easier way?

like image 418
John Heyer Avatar asked Apr 18 '26 08:04

John Heyer


1 Answers

This is simple, just isn't documented very well. The Request class has an attribute called query_params. It's a mulitdict, but can easily be converted to a standard dictionary via the dict() function:

def root(path, req: Request):
    request_args = dict(req.query_params)
like image 157
John Heyer Avatar answered Apr 20 '26 21:04

John Heyer