question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Response model with pydantic's arbitrary_types_allowed not working

See original GitHub issue

I use pydantic model with custom type. Set in config arbitrary_types_allowed=True. Without setting a parameter “response_model” it’s work. But when I set this model in param:

fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class 'Foo'> is a valid pydantic field type 

Pydantic class definition example:

import Foo

class Model(BaseModel):
    id: str
    custom: Optional[Foo] = Field(None)
    status: str = None
    fail_message: Optional[str] = None
    params: Dict[str, Any] = None

    @validator('custom')
    def deserialize_model(cls, v):
        return Foo.loads(v)

    class Config:
        arbitrary_types_allowed = True
        json_encoders = {Foo: lambda v: v.dumps()}

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:16
  • Comments:14 (4 by maintainers)

github_iconTop GitHub Comments

17reactions
fubupccommented, Aug 23, 2020

Same problem here:

from pydantic import BaseModel
from fastapi import FastAPI


class Pair:
    def __init__(self, x: int, y: int):
        self.x: int = x
        self.y: int = y


class M(BaseModel):
    pair: Pair
    other: int

    class Config:
        arbitrary_types_allowed = True


app = FastAPI()


@app.get("/m/", response_model=M)
def just_m():
    return M(pair=Pair(x=5, y=7), other=8)

will report error:

fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class 'test.Pair'> is a valid pydantic field type
7reactions
bcbcommented, Aug 3, 2020

I ended up using a custom Pydantic field validator, instead of using arbitrary_types_allowed:

class AssociationList(_AssociationList):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if not isinstance(v, _AssociationList):
            raise TypeError("AssociationList required")
        return [UserOut.from_orm(u) for u in v]


class TeamOut(TeamBase):
    members: AssociationList
    ...
Read more comments on GitHub >

github_iconTop Results From Across the Web

Invalid args for response field! Hint: check that <class 'typing ...
I have no idea what's going on! class ParameterSchema(BaseModel): expiryDate = Optional[datetime] class Config: arbitrary_types_allowed = ...
Read more >
fastapi.exceptions.fastapierror: invalid args for response field ...
The error says your type you pass to predict must be pydantic BaseModel (or ... Response model with pydantic's arbitrary_types_allowed not working#1186.
Read more >
tiangolo/fastapi - Gitter
In this case, what I'd really like to do is return a pydantic model with a derived field for the count of the...
Read more >
Getting Started with MongoDB and FastAPI
So, it's not unusual to create models when working with a MongoDB database. Our application has two models, the StudentModel and the ...
Read more >
Extra Models - FastAPI
Pydantic models have a .dict() method that returns a dict with the model's data. ... issues (when you update in one place but...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found