Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
Custom Pydantic classes as FastAPI body parameters

Pydantic says that you can create custom classes by simply defining the __get_validators__ method. This is useful if you want to parse into a class with its own metaclass or for some other reason do not want to inherit from BaseModel.

However, this fails in strange places in FastAPI. For example, FastAPI does not detect such a class as a body parameter, but always thinks it is a query parameter.

from fastapi import FastAPI, Body
from fastapi.testclient import TestClient

app = FastAPI()

class NastyMetaClass(type):
    pass

class Foo(metaclass=NastyMetaClass):
    @classmethod
    def __get_validators__(cls):
        yield lambda value: True

@app.post("/implicit")
def foo(foo: Foo):  # This is supposed to work, but does not
    return "It worked"

@app.post("/explicit")
def foo_body(foo: Foo = Body(...)):  # The `= Body(...)` fixes it
    return "It worked"

client = TestClient(app)

response = client.post("/implicit", json={})
print(response.json())
# {'detail': [{'loc': ['query', 'foo'], 'msg': 'field required', 'type': 'value_error.missing'}]}

response = client.post("/explicit", json={})
print(response.json())
# It worked

How can I make FastAPI recognize custom Pydantic classes?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

As per FastAPI documentation, when using Body(...) you instruct FastAPI to treat a parameter as a body key. Thus, using foo: Foo = Body(...) is one way to tell your endpoint to expect a JSON body with the attributes of a Foo.

Alternatively, you could delcare the Foo parameter using Dependencies, as shown below:

from fastapi import Depends
@app.post("/implicit")
def foo(foo: Foo = Depends(Foo)):  # This should work
    return "It worked"

You could even simply use Depends() (i.e., foo: Foo = Depends()) as a shortcut to avoid code repetition.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda