Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Casting dictionary in response_model_include/response_model_exclude to set. #2007

@Rubikoid

Description

@Rubikoid

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to one of:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

Example

Here's a self-contained, minimal, reproducible, example with my use case:

from fastapi import FastAPI
from pydantic import BaseModel

class Test(BaseModel):
    foo: str
    bar: str

class Test2(BaseModel):
    test: Test
    baz: str

app = FastAPI()
@app.get(
    "/",
    response_model=Test2,
    response_model_include={'baz': ..., 'test': {'foo'}},
    response_model_exclude={'test': {'bar'}}
    )
def item():
    return Test2(test=Test(foo="visible field", bar="invisible field"), baz="also visible field")

Description

Dictionary, passed to response_mode_include/exclude casts to set.

  • Open the browser and call the endpoint /.
  • It returns a JSON with {"baz":"also visible field"}.
  • But I expected it to return {"baz":"also visible field", "test": {"foo": "visible field"}}.

Environment

  • OS: Windows
  • FastAPI Version: 0.60.1
  • Python version: Python 3.7.3

Additional context

So, this happens due to cast of include and exclude params to set at https://github.com/tiangolo/fastapi/blob/master/fastapi/encoders.py#L37 and https://github.com/tiangolo/fastapi/blob/master/fastapi/encoders.py#L39.

According to pydantic docs, this is a normal usage of include/exclude.

So, i think, fix can be simple, like appending ... and not isinstance(include, dict) to conditions. But i'm not familiar with fastapi, and not sure that fix can break something.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions