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.

[BUG] Pydantic __root__ model - incorrect handling

See original GitHub issue

Describe the bug

https://pydantic-docs.helpmanual.io/usage/models/#custom-root-types Pydantic allows to create models with only __root__ field. In such scenario the model behaves as transparent wrapper for this single type.

When such model is used in response (request also?) fastapi does not treat it correctly and renders it as object with __root__ field.

Object is treated correctly by pydantic itself.

To Reproduce

from typing import List
from fastapi import FastAPI
from pydantic.main import BaseModel

app = FastAPI()


class RootTestClass(BaseModel):
    __root__: List[str]


@app.get("/")
async def root():
    response = RootTestClass(__root__=['a', 'b', 'c'])
    print(response.json())  # ["a", "b", "c"] so it's OK
    print(RootTestClass.schema())  # {'title': 'RootTestClass', 'type': 'array', 'items': {'type': 'string'}} this is also OK
    return response  # Wrong value in http response

Expected behavior

The response should be:

["a", "b", "c"]

but at the moment is:

{"__root__":["a","b","c"]}

Screenshots

N/A

Environment

  • OS: Linux
  • FastAPI Version: 0.47.1
  • Python version: Python 3.7.5

Additional context

N/A

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:17
  • Comments:12 (5 by maintainers)

github_iconTop GitHub Comments

12reactions
davideasafcommented, Apr 27, 2020

as @sidmani also mentioned, I’m running into wanting the ability to be able to say:

pydantic_list_as_root.dict()

and the above output a dict. Rather than having to manually loop through my List[pydantic_entity] and call dict() on each one.

However, I do appreciate what @tiangolo is trying to achieve by keeping things as pythonic as possible, but I would imagine that many if not all FastAPI implementations heavily rely on Pydantic for defining schemas. Therefore, I think it would be a great idea to embrace all/most of its capabilities.

4reactions
sidmanicommented, Feb 23, 2020

@tiangolo Supporting pydantic root types would allow a single validator (defined in the wrapper class) to be run on all objects of a certain type- otherwise, the validator must be specified in each object that has a child of that type (as far as I can tell- I’m new to fastAPI, please let me know if there’s a better way).

Read more comments on GitHub >

github_iconTop Results From Across the Web

Pydantic validation error for BaseSettings model with local ...
If the environment file isn't being picked up, most of the time it's because it isn't placed in the current working directory.
Read more >
Models - pydantic
a utility for loading any object into a model with error handling if the object is not a dictionary; cf. helper functions; parse_raw():...
Read more >
csvcubed-pydantic - PyPI
Fix bug where use of complex fields on sub-models could cause fields to be incorrectly configured, #1015 by @samuelcolvin ...
Read more >
How to Validate Your Data with Custom Validators of Pydantic ...
Pydantic is a popular Python library for data validation and settings ... First, let's create a standard pydantic model and use the default ......
Read more >
Pydantic Hidden Features - Gideon's Blog -
Use field aliases to play nicely with external formats; Copy & set don't perform type validation; Adding constraints to models; Enforcing ...
Read more >

github_iconTop Related Medium Post

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