'How to validate ObjectId query param in FastAPI

I have an endpoint that recibe and id field used to get data from MongoDB's _id:

from fastapi import APIRouter
from bson import ObjectId

router = APIRouter()

@router.get("/get-data")
async def get_strategies(order_id: ObjectId):
    return Manager().get_data(order_id)

I want validate if order_id is valid as ObjectId, if later, inside the function, order_id is a str or ObjectId it doesn't matter.

How can I do this? Thanks for help!



Solution 1:[1]

I found this validator: Query, this is used to validate http GET parameters.
Also there is this validator: Path to validate path parameters, below I left and example:

from fastapi import APIRouter, Path, Query
from bson import ObjectId

router = APIRouter()

@router.get("/get-data")
async def get_strategies(order_id: str = Query(..., regex=r"^[0-9a-f]{24}$")):
    return Manager().get_data(order_id)


@router.get("/get-data/{order_id}")
async def get_strategies(order_id: str = Path(..., regex=r"^[0-9a-f]{24}$")):
    return Manager().get_data(order_id)
  • The ... inside Query and Path is to indicate parameter is required.

  • ObjectId is an hexadecimal string with 24 characters. that is mached with the regex

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cristian Contrera