OpenAPI Generated for NamedTuple is Object, Not List #9310
Replies: 3 comments
-
|
In version 0.112 I get: For: UploadBenchmarkingData = NamedTuple(
"UploadBenchmarkingData",
[
("upload_interval", datetime.timedelta),
("payload_byte_size", PositiveInt),
("continent", str),
("country", CountryAlpha2),
("city", str),
],
)This is invalid, arrays are not supposed to have prefixItems, not sure what the right field is though. |
Beta Was this translation helpful? Give feedback.
-
|
The issue is that NamedTuple doesn't work well with FastAPI/Pydantic because of a schema mismatch. Use Pydantic BaseModel. |
Beta Was this translation helpful? Give feedback.
-
|
FastAPI and Pydantic treat typing.NamedTuple as an object with named fields, so the generated schema is an object with latitude and longitude. That is expected. If your endpoint should accept a two-element array like [lat, lon], model it as a tuple or a constrained list instead of a NamedTuple. On newer FastAPI with OpenAPI 3.1, tuples appear in JSON Schema using prefixItems. That is valid JSON Schema 2020-12, but some tools that only understand OpenAPI 3.0 may not handle it. You have three practical choices:
Option A. Two-element numeric tuple (OpenAPI 3.1 will use prefixItems) Option B. Constrained list with exact length 2 (plays nicely with OpenAPI 3.0) Option C. Keep object shape with validation (explicit names and ranges) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
LocationNamedTuple provides constraints and a better interface for accessing a [lat,long] coordinate array.Note that it defines Location to be an object with named properties; this is incompatible with what the /trip endpoint actually accepts.
Operating System
Linux
Operating System Details
ubuntu 20.04 run via Docker
FastAPI Version
0.95.0
Python Version
3.8.10
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions