[FEATURE] Convert Tuple attribute of pydantic model to List in json schema
See original GitHub issueIs your feature request related to a problem
I have a model Foo
to be used as response class:
from pydantic import BaseModel
class Foo(BaseModel):
span: Tuple[int, int]
@app.get("/", response_class=Foo)
async def main():
return Foo(span=(1, 2))
However, this generates empty typed json schema:
I want Foo
to be generated [interger]
in json shcema.
The solution you would like
Tuple
is converted to List
in json schema.
Describe alternatives you’ve considered
Rewrite Foo.span
type annotation to List[int]
.
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (4 by maintainers)
Top Results From Across the Web
How to parse list of models with Pydantic - Stack Overflow
How can I convert this dict to a list of User instances? My solution for now is user_list = [] for user in...
Read more >Pydantic V2 Plan
One of the features people have long requested is the ability to convert data to JSON compliant types while converting a model to...
Read more >Exporting models - pydantic
Exporting models. As well as accessing model attributes directly via their names (e.g. model.foobar ), models can be converted and exported in a...
Read more >Pydantic exporting models - The Blue Book
This is the primary way of converting a model to a dictionary. Sub-models will be recursively converted to dictionaries. Arguments: include : Fields...
Read more >Body - Nested Models - FastAPI
The string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such. Attributes with lists of...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
The thing is that OpenAPI explicitly forbids lists with multiple sub-schemas (tuples). So, you can’t declare tuples with OpenAPI even though you can with JSON Schema.
If you need to have tuples in your model (i.e. you can’t declare it as a list) the best way to go would probably be as @dmontagu says by adding a
schema_extra
method that updates the schema.Thanks for following up. Yeah I’m not sure what the best thing to do is here. Given how much there is to support I’m generally okay with it if we just properly support what’s the same in both JSON Schema and OpenAPI. I’d be open to changing the behavior (or trying to get it changed anyway) given enough interest. Or if @tiangolo thinks it’s best.
You can manually override the generated schema using
Config.schema_extra
so I would just do that for now if you need this (maybe with a utility function if you want to do it in many places).