2

I'm currently working on a API that returns scraped data. The data is stored as an array but when I go return that array as a response on an endpoint, I get the following error:

pydantic.error_wrappers.ValidationError: 1 validation error for InnerObject
response
  value is not a valid dict (type=type_error.dict)

Here's a simplified version of what I'm trying to achieve:

class InnerObject(BaseModel):
    foo: str

class OuterObject(BaseModel):
    bar: List[InnerObject]

@app.get("/test_single", response_model=InnerObject)
def test():
    return InnerObject(foo="Hello Mars")

@app.get("/test_multiple", response_model=OuterObject)
def test():
    objects = [InnerObject]

    objects.append(InnerObject(foo="Hello Earth"))
    objects.append(InnerObject(foo="Hello Mars"))

    return objects

I have an array of objects that I want to return as a response. It's also possible that I don't need outer/inner models but I have also attempted this and set the response_model to be response_model=List[InnerObject]. Returning a single InnerObject as seen in the "/test_single" endpoint works fine, so I assume it's to do with trying to return a [InnerObject]

Thanks for any responses in advance

Solution

Thanks kosciej16, the problem was that I was adding the object name when declaring the list. So I was going objects = [InnerObject] when I should have been going objects = []

1 Answer 1

4

Generally fastapi tries to create OuterObject from thing you return.

In such case you have few options.

  1. Create object explicitly
@app.get("/test_multiple", response_model=OuterObject)
def test():
    objects = []

    objects.append(InnerObject(foo="Hello Earth"))
    objects.append(InnerObject(foo="Hello Mars"))

    return OuterObject(bar=objects)
  1. Change response_model
@app.get("/test_multiple", response_model=List[InnerObject])
def test():
    objects = []

    objects.append(InnerObject(foo="Hello Earth"))
    objects.append(InnerObject(foo="Hello Mars"))

    return objects
  1. Change definition of OuterObject
class OuterObject(List[InnerObject]):
    pass
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.