[FEATURE] Combining Form() with Arbitrary dicts
See original GitHub issueI just spent a lot of time trying to get this to work:
app.post("/post-form-here")
def process_this_form(form_data: Dict[str, str] = Form(...)):
# this does not work
pass
The documentation needs to be updated to make clear this will not work. At first it looks like you should be able to combine Form Data with Bodies of Arbitrary dict
s. I could be wrong but I think there’s no way to do this in FastAPI. If you are using Form()
you have to explicitly define every form field one by one no matter how many fields you have, like so:
app.post("/post-form-here")
def process_this_form(
parameter_a: str = Form(...),
parameter_b: str = Form(...),
parameter_c: str = Form(...),
parameter_d: str = Form(...),
parameter_e: str = Form(...),
parameter_f: str = Form(...),
parameter_g: str = Form(...),
parameter_h: str = Form(...),
parameter_i: str = Form(...),
parameter_j: str = Form(...),
parameter_k: str = Form(...),
parameter_l: str = Form(...),
parameter_m: str = Form(...),
parameter_n: str = Form(...),
parameter_o: str = Form(...),
parameter_p: str = Form(...),
parameter_q: str = Form(...)):
# this works
pass
And you cannot have any arbitrary Form()
fields either.
The solution I would like would be either to make this work like in Flask, where you have available request.form
(a dict containing all x-www-form-urlencoded data.) Or else have the documentation explicitly state that you can’t combine these two concepts Form Data with Bodies of Arbitrary dict
s, and there is just no way to do it in FastAPI.
In my case I have 27 fields that go into a NamedTuple which goes into a table. To put 27 Form()
parameters into one Python function def is going to be the longest def I’ve ever written, but I’d rather do that than waste a weekend beating my head against a wall.
I understand it may not be possible with the current design to read request.form
like in Flask but please save people frustration by stating this up front in the documentation for Form()
.
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
@tfishr Hi! I suppose that you are looking for
request.form()
method from theStarlette
on whichFastAPI
is based. You can pass theRequest
object fromStarlette
as described here. This asynchronous method will return a dict-like object that can be used for your purposes:Since the
request.form()
method is asynchronous, you cannot use it directly in your example with synchronous endpoint, but you can wrap receiving of your data from the form in a separate dependency and return either the data received fromrequest.form()
or the object that you create from this data:Nevermind, I just reread this and read dependencies I’m clear now, thanks