1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How to define query parameters using Pydantic model in FastAPI?

Discussão em 'Python' iniciado por Stack, Setembro 14, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to have an endpoint like /services?status=New

    status is going to be either New or Old

    Here is my code:

    from fastapi import APIRouter, Depends
    from pydantic import BaseModel
    from enum import Enum

    router = APIRouter()

    class ServiceStatusEnum(str, Enum):
    new = "New"
    old = "Old"


    class ServiceStatusQueryParam(BaseModel):
    status: ServiceStatusEnum


    @router.get("/services")
    def get_services(
    status: ServiceStatusQueryParam = Query(..., title="Services", description="my desc"),
    ):
    pass #my code for handling this route.....


    The result is that I get an error that seems to be relevant to this issue here

    The error says AssertionError: Param: status can only be a request body, using Body()


    Then I found another solution explained here.

    So, my code will be like this:

    from fastapi import APIRouter, Depends
    from pydantic import BaseModel
    from enum import Enum

    router = APIRouter()

    class ServiceStatusEnum(str, Enum):
    new = "New"
    old = "Old"


    class ServicesQueryParam(BaseModel):
    status: ServiceStatusEnum


    @router.get("/services")
    def get_services(
    q: ServicesQueryParam = Depends(),
    ):
    pass #my code for handling this route.....


    It is working (and I don't understand why) - but the question is how and where do I add the description and title?

    Continue reading...

Compartilhe esta Página