If you want to use the "in" filter of FastAPI with values that have commas, you can pass them as a list. For example, if you want to filter a list of products based on their categories, and some categories have commas in their names, you can pass the list of categories as a list of strings, like this:
from typing import List
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/products/")
async def get_products(categories: List[str] = Query(None, alias="category__in")):
# assume products is a list of products with a "category" field
if categories:
selected_products = [p for p in products if p.category in categories]
else:
selected_products = products
return {"products": selected_products}
In this example, the alias parameter is used to rename the category__in parameter to categories for easier readability. The List[str] type indicates that the parameter accepts a list of strings. When a request is made with multiple categories, they should be passed as a comma-separated list in the query string, like this:
GET /products/?categories=electronics,clothing,household
This will return all products that have a category that is either "electronics", "clothing", or "household". If a category has a comma in its name (e.g. "kitchen, cookware"), it should be passed as a separate string element in the list:
GET /products/?categories=electronics,kitchen, cookware,clothing
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-09 15:34:25 +0000
Seen: 9 times
Last updated: Jul 09 '23