How to enable filtering on all fields of a model in fastapi?

Member

by addison , in category: Third Party Scripts , 19 days ago

How to enable filtering on all fields of a model in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 18 days ago

@addison 

To enable filtering on all fields of a model in FastAPI, you can use the Query parameter with None as the default value for all fields in your endpoint definition. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from fastapi import FastAPI, Query

# Define your FastAPI app
app = FastAPI()

# Your model
class Item:
    def __init__(self, id: int, name: str, description: str):
        self.id = id
        self.name = name
        self.description = description

# Define your list of items
items = [
    Item(id=1, name='item1', description='description1'),
    Item(id=2, name='item2', description='description2'),
    Item(id=3, name='item3', description='description3')
]

# GET endpoint that accepts filters for all fields
@app.get("/items")
async def get_items(id: int = Query(None), name: str = Query(None), description: str = Query(None)):
    result = items

    if id is not None:
        result = [item for item in result if item.id == id]

    if name is not None:
        result = [item for item in result if item.name == name]

    if description is not None:
        result = [item for item in result if item.description == description]

    return result


In this example, the get_items endpoint accepts query parameters for all fields of the Item model. The endpoint filters the list of items based on the provided query parameters. If a query parameter is not provided, it defaults to None and is not used as a filter.


You can test this endpoint by running your FastAPI app and making GET requests with query parameters to filter the items based on the desired criteria.