3

I'm using FastAPI and I'm trying to send a JSON array of JSON objects to my post endpoint, in the body. My endpoint is defined as:

@router.post("/create_mails")
def create_mails(notas: List[schemas.Nota], db: Session = Depends(get_db)):

My body in Postman looks like:

{
    "notas": [{"a":"1","b":"2","c":"3","d":"4"},
              {"a":"1","b":"2","c":"3","d":"4"}]
}

However, I keep getting the 422 unprocessable entity error from FastAPI, with the error detail:
value is not a valid list

I also tested it with a modified endpoint:

@router.post("/create_mails")
def create_mails(notas: List[str] = Body([]), db: Session = Depends(get_db)):

and with a simple string array, but the same error is returned.

Am I missing FastAPI's definition of a valid list?

1 Answer 1

9

Your POST method parameter needs to model the entire request body, which is indeed a single object, and not a list.
To match the body you're trying to send, you'd need something like:

class NotaList(BaseModel):
    notas: List[Nota]

and then:

def create_mails(body: schemas.NotaList)

Note that the parameter name in your function is not part of the data model, it just represents the "top-level" body object. I've renamed it to body here to clarify that. The notas in the request body will get assigned to the notas member of the class, so inside your method you'll access things like (for example):

for nota in body.notas:
    # do stuff
Sign up to request clarification or add additional context in comments.

4 Comments

I tried this with class: class NotaList(BaseModel): list: List[schemas.Nota] , and tested with data: { "notas": {"list": [{"a":"1","b":"2","c":"3","d":"4"}, {"a":"1","b":"2","c":"3","d":"4"}]} } But I get the error: {"detail":[{"loc":["body","list"],"msg":"field required","type":"value_error.missing"}]}
@Simon if your NotaList class attribute is named list then the post variable also has to be "list" -- why are you wrapping it in an extra "notas" ?
Ahh thanks this was my mistake! I thought it had to be in an extra "notas" because my method parameter was called like that. But using only list is the trick!
Your method parameter's name is only relevant to your own code, and it represents the "nameless" top-level dictionary in the POST.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.