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

Skip to content

jsonable_encoder alters json_encoders of Pydantic objects #4962

@slackner

Description

@slackner

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.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from pydantic import BaseModel, SecretStr
from fastapi.encoders import jsonable_encoder


class Credentials(BaseModel):
    password: SecretStr


ENCODERS = {SecretStr: lambda v: v.get_secret_value() if v is not None else None}

creds = Credentials(password="helloworld")

a = jsonable_encoder(creds)
print(a)  # {'password': '**********'}, as expected
b = jsonable_encoder(creds, custom_encoder=ENCODERS)
print(b)  # {'password': 'helloworld'}, as expected
c = jsonable_encoder(creds)
print(c)  # gives {'password': 'helloworld'}, but should be {'password': '**********'}?


creds = Credentials(password="123456789")

d = jsonable_encoder(creds)
print(d)  # gives {'password': '123456789'}, but should be {'password': '**********'}?

Description

  • I'm using jsonable_encoder at multiple locations in the code, sometimes with custom_encoder and sometimes without.
  • My understanding is that passing custom_encoder should only affect the current call and not modify any global state.
  • What actually happens is that it modifies __config__.json_encoders, and as a result, public API endpoints might suddenly start returning secret values that should be filtered.

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.78.0

Python Version

Python 3.9.2

Additional Context

Using Pydantic version 1.9.1.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions