惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
J
Java Code Geeks
V
V2EX
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
F
Fortinet All Blogs
aimingoo的专栏
aimingoo的专栏
B
Blog
A
About on SuperTechFans
有赞技术团队
有赞技术团队
月光博客
月光博客
Microsoft Azure Blog
Microsoft Azure Blog
阮一峰的网络日志
阮一峰的网络日志
腾讯CDC
美团技术团队
大猫的无限游戏
大猫的无限游戏
爱范儿
爱范儿
N
Netflix TechBlog - Medium
C
Check Point Blog
Recent Announcements
Recent Announcements
博客园 - Franky
博客园 - 叶小钗
T
Tailwind CSS Blog

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
How to Parse Query Param With Multiple Values in FastAPI
2023-07-14 · via jdhao's digital space

In HTTP request, same query parameter with multiple values are allowed. For example, for query parameter brand, the query string looks like this: brand=foo&brand=bar. How to parse value of this parameter to a list in FastAPI? There are several different ways.

Using Type annotation and Query#

If you already know which parameter is going to have multiple values, you can use the following method (based on discussion here):

from fastapi import FastAPI, Request, Query

app = FastAPI()

@app.get('/multi_value')
def multi_value(brand: List[str] = Query(default=None)):
    return {"brand": brand}

In this way, the query parameter brand will be known by FastAPI to have a list of values. If you access the API like this: http://127.0.0.1:8000/multi_value?brand=foo&brand=bar, you can get correct response:

Deal with the request directly#

If you do not know which parameter is going to have multiple values, you can also directly handle it with using the request object from FastAPI.

@app.get('/foo')
def foo(request: Request):
    query_params = request.query_params
    params_dict = {}
    for k in query_params.keys():
        params_dict[k] = query_params.getlist(k]
    return params_dict

If a query parameter can appear multiple time in the query, we shouldn’t use query_params.get() to get its values, because it will only return the last value. Similarly, query_params.items() and query_params.values() also only contain the last value for the query parameter.

Another way is to use parse_qs from urllib to parse the query string manually.

@app.get('/foo')
def foo(request: Request):
    # `request.url` is the complete URL for the HTTP request.
    # `request.url.query` contains only the query part from the whole URL. For example, if your complete
    # URL is http://127.0.0.1:8000/search2/foo?q=schuhe&color=blue&color=black, then the value for
    # request.url.query would be "q=schuhe&color=blue&color=black"
    params_dict = parse_qs(request.url.query, keep_blank_values=True)
    return params_dict

parse_qs() can handle parameter with several values correctly. It has a parameter keep_blank_values, if it is set to True, query parameter with no value will also be kept in the parsed result, and the corresponding value is set to an empty string.