Skip to content

pydantic object __init()__ function call revealed in fastAPI type_error payload #4679

@Syffe

Description

@Syffe

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 fastapi import FastAPI
import pydantic

app = FastAPI()

@pydantic.dataclasses.dataclass
class TestPayload:
    message: str = dataclasses.field(
        metadata={"description": "test message"}
    )

@app.put('/test_endpoint')
def create(test_payload: TestPayload) -> TestPayload:
    return test_payload


payload = {"false_key": "test message"}

app.put("/test_endpoint",
        json=payload,
      )

Description

Hi,

When trying to use a pydantic model as a parameter for an endpoint, if this said payload isn't matching the pydantic model defined, with, in this case, a wrong key, fastAPI will return an error payload as follows:

# fastAPI error payload returned
{
'loc': ('body',), 
'msg': "TestPayload.__init__() got an unexpected keyword argument 'false_key'", 
'type': 'type_error'
}

The error message reveals that .init() is called from the pydantic object, and this kind of message is not quiet what an API user would like to see following a key error.
The question then being, Is it the good behavior following those kind of errors ? Is it ok to reveal this kind of call information ?
May be it is a bug, or an error that isn't correctly catched on the server side

Operating System

macOS

Operating System Details

No response

FastAPI Version

0.74.1

Python Version

Python 3.10.2

Additional Context

No response

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