Getting Query Parameters as Dictionary in FastAPI [duplicate]

2024/9/8 9:06:29

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']}", 200else: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?

Answer

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)
https://en.xdnf.cn/q/72242.html

Related Q&A

Python Generated Signature for S3 Post

I think Ive read nearly everything there is to read on base-64 encoding of a signature for in-browser, form-based post to S3: old docs and new docs. For instance:http://doc.s3.amazonaws.com/proposals/…

Bringing a classifier to production

Ive saved my classifier pipeline using joblib: vec = TfidfVectorizer(sublinear_tf=True, max_df=0.5, ngram_range=(1, 3)) pac_clf = PassiveAggressiveClassifier(C=1) vec_clf = Pipeline([(vectorizer, vec)…

how to count the frequency of letters in text excluding whitespace and numbers? [duplicate]

This question already has answers here:Using a dictionary to count the items in a list(10 answers)Closed last year.Use a dictionary to count the frequency of letters in the input string. Only letters s…

Fastest algorithm for finding overlap between two very large lists?

Im trying to build an algorithm in Python to filter a large block of RDF data. I have one list consisting of about 70 thousand items formatted like <"datum">.I then have about 6GB worth…

Call Postgres SQL stored procedure From Django

I am working on a Django Project with a Postgres SQL Database. I have written a stored procedure that runs perfectly on Postgres.Now I want to call that stored procedure from Django 1.5 .. I have writt…

How can I mix decorators with the @contextmanager decorator?

Here is the code Im working with:from contextlib import contextmanager from functools import wraps class with_report_status(object):def __init__(self, message):self.message = messagedef __call__(self, …

supervisord always returns exit status 127 at WebFaction

I keep getting the following errors from supervisord at webFaction when tailing the log:INFO exited: my_app (exit status 127; not expected) INFO gave up: my_app entered FATAL state, too many start retr…

One dimensional Mahalanobis Distance in Python

Ive been trying to validate my code to calculate Mahalanobis distance written in Python (and double check to compare the result in OpenCV) My data points are of 1 dimension each (5 rows x 1 column). I…

DeprecationWarning: please use dns.resolver.Resolver.resolve()

I am using resolver() as an alternative to socket() as I found that when multiple connections are made to different IPs it ends up stopping working. Anyway it returns a warning to me that I should use …

python cannot find module when using ssh

Im using python on servers. When I run a python command which needs numpy module, if I do ssh <server name> <python command>that server will complain no module named numpy found.However, if…