question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] One or more objects in request body?

See original GitHub issue

Description

I’d like to have an endpoint in my API that accepts one or more objects in the request body. For example, I would like both of these to be valid request bodies:

{
  "name": "foo"
}
[
  {"name": "foo"},
  {"name": "bar"}
]

I’m not sure how to do this in fastapi/pydantic. Is it even possible? Any advice?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
dmontagucommented, Jul 10, 2019

@kevlar1818

Union is currently somewhat finicky in pydantic due to the way it is implemented – the order matters because it will try to parse types in the provided order. For what it’s worth, if you have issues with pydantic Union parsing, I would encourage you to open a github issue over on the pydantic repository – if the problem isn’t a bug (which it might be), you’ll probably get a suggestion for how to accomplish your goal.


For what it’s worth, the following script does work for me:

from typing import List

from pydantic import BaseModel, Union


class Name(BaseModel):
    name: str


class NameData(BaseModel):
    name_data: Union[Name, List[Name]]


data1 = {
    "name_data": {
        "name": "foo"
    }
}

data2 = {
    "name_data": [
        {"name": "foo"},
        {"name": "bar"}
    ]
}

print(NameData(**data1))
# NameData name_data=<Name name='foo'>

print(NameData(**data2))
# NameData name_data=[<Name name='foo'>, <Name name='bar'>]

If your issue with the container approach is that you don’t want to write a container model for every list-or-object type you want to have, you can leverage pydantic.generics.GenericModel:

from typing import List, TypeVar, Generic

from pydantic import BaseModel, Union
from pydantic.generics import GenericModel

T = TypeVar("T")


class Name(BaseModel):
    name: str


class ListOrObject(GenericModel, Generic[T]):
    contained: Union[T, List[T]]


data1 = {
    "contained": {
        "name": "foo"
    }
}

data2 = {
    "contained": [
        {"name": "foo"},
        {"name": "bar"}
    ]
}

data3 = {
    "contained": "string1"
}

data4 = {
    "contained": ["string1", "string2"]
}

print(ListOrObject[Name](**data1).contained)
# Name name='foo'

print(ListOrObject[Name](**data2).contained)
# [<Name name='foo'>, <Name name='bar'>]

print(ListOrObject[str](**data3).contained)
# string1

print(ListOrObject[str](**data4).contained)
# ['string1', 'string2']

(The above script runs for me as is.)

I believe this plays nicely with FastAPI as well.

0reactions
tiangolocommented, Jul 29, 2019

Thanks for the help @dmontagu 🌮!

Thanks @kevlar1818 for reporting back and closing the issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Is it possible to pass multiple objects in @RequestBody?
Here i am assuming that you want to send two class objects in a single responsebody response. Create an additional inner class in...
Read more >
Error : JSON request body must be an object
@kishore Try the suggested solution from @devendra as: req.setBody('{"jsonBodyList":' + JSON.serialize(jsonBodyList) + '}' and with the above ...
Read more >
JSON request body with Arrays - Appian Community
Integration Object - Test Request - JSON request body with Arrays ... the request body based on the solution to the above question...
Read more >
Request and response objects - Django documentation
The raw HTTP request body as a bytestring. This is useful for processing data in different ways than conventional HTML forms: binary images,...
Read more >
Programatically change the request body in Postman - YouTube
Mutating the request body in Postman is something that many people ... me create more videos like this one, please consider subscribing.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found