FastAPI and "complex objects" in URL arguments #11413
Torxed
started this conversation in
Show and tell
Replies: 1 comment
-
Handling complex objects directly in FastAPI path parameters isn’t straightforward. FastAPI and Pydantic aren’t set up for complex types in URLs because they expect simple, scalar values that map easily from path strings. For more complex data, you’re better off using query parameters or request bodies. Overriding this behavior in FastAPI would mean altering core functionalities, which could introduce bugs and security vulnerabilities. Stick to the conventions: keep path parameters simple and manage complex data with the tools designed for it, like POST bodies. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I feel obligated to start by saying that this isn't production friendly code, it's an itch that needed scratching, and that there are other ways to solve this problem such as writing a Depends just as one of many examples. I'm strictly exploring the option of directly supporting complex objects in path elements of FastAPI as shown here:
But to avoid the following (expected) error:
In order to explore this, the only way I found possible for FastAPI to support direct type annotations like this, was to perform some sacrilegious interventions of FastAPI definitions (and this is where it will briefly go outside of what anyone should do, but bear with me):
This allows for direct type annotation of path elements with possibility of internally handling validation within the ExampleCustomType type.
And what I wanted to do here was to discuss if this type of direct annotation would be desirable? What kind of issues could come from allowing these complex types here?
I'm assuming there's a reason for why complex objects are not supported. Or is the "only reason" the fact that pydantic-core can't perform validation against the internal type annotation of
type
andid
because the input is a singlestr
and that's it?And if so, would a
app = fastapi.FastAPI(allow_complex_types=True)
be a feasible "advanced" feature that developers could leverage to assume responsibility of performing type conforming on the input data during initialization of the obj?Again, this was a intrusive thought that I wanted to explore, and perhaps there is an actual intended and supported useage for this already and I missed it?
Beta Was this translation helpful? Give feedback.
All reactions