How to use date in "dd.mm.YYYY" format in FastAPI

59 views Asked by At

I'm learning FastAPI on my own, trying to make a tutorial project, but I'm running into some difficulties. I need the api to receive a date in the format “dd.mm.YYYY” and the output to be in the same format. I'm using a schema inherited from BaseModel with a "date" field. In the function, I take as input an object corresponding to this scheme, and the output is dict, where the keys can be a date in the desired format. I tried to search, but ran into the problem "I'm sorry. My responses are limited. You must ask the right questions." I couldn’t find an option to use minimal crutches to make the same date validation for input (in BaseModel) and output (in typing).

I want to get something similar:

class MyTestSchema(BaseModel):
    date: Date_dd_mm_YYYY
    # another fields


class MyTestClass:
@classmethod
def my_test_func(data: MyTestSchema) -> dict[Date_dd_mm_YYYY, str]
    # function


@app.post("")
def my_test_api(data: Annotated[MyTestSchema, Body()]) -> dict[Date_dd_mm_YYYY, str]:
    return MyTestClass.my_test_func(data)

I assumed that maybe I needed to write a separate class for the date and define the “validate” method in it, but firstly I couldn’t make it work correctly for both input and output, and secondly I thought that maybe there were some solutions instead inventing your own bicycle.

0

There are 0 answers