Skip to content

Bad loc on validation error, if payload represended by one model #1088

@Dock1100

Description

@Dock1100

Describe the bug

Really like your framework, but there is, indeed, an annoying issue with loc on validation error with one object as payload.

To Reproduce

Code sample

from typing import List

from fastapi import FastAPI, Body
from pydantic import BaseModel
app = FastAPI()

class NameModel(BaseModel):
    name: str

@app.post("/test", response_model=NameModel)
def test(obj: NameModel, ):  # bad
    return obj

@app.post("/test_embed", response_model=NameModel)
def test(obj: NameModel = Body(..., embed=True)):  # ok
    return obj

@app.post("/test_multiple", response_model=List[NameModel])
def test(obj1: NameModel, obj2: NameModel):  # ok
    return obj1, obj2

When you make a request to endpoint (/test) with the wrong payload (e.g.: {}), it always includes the variable name into error location, despite it has no relation to request.

It makes no sense, moreover, it complicates the logic for error printing on fronted, because they just don't know and not required to know the name of the backend`s internal variable.

{
    "detail": [
        {
            "loc": [
                "body",
                "obj",
                "name"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

it should be

{
    "detail": [
        {
            "loc": [
                "body",
                "name"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

With the embedded object (/test_embed) or multiple objects (/test_multiple), it works as expected, putting the variable name into location, because it should be in the payload.

Expected behavior

Don't include the variable name into location error, if it is not reflected in schema / not embedded / not expected to be in payload.

Environment

  • OS: macOS
  • FastAPI 0.52.0
  • Python 3.6.8

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions