7

I try to migrate from Flask to FastAPI, and I was wondering if there is something similar to Flask's:

payload = request.form.to_dict(flat=False)
payload = {key:payload[key][0] for key in payload}

for FastAPI.

Until now I've found only some hacks, were you still had to implement one-by-one all the form's arguments to a function:

from pydantic import BaseModel
class FormData(BaseModel):
    alfa: str=Form(...)
    vita: str=Form(...)
async def Home(request: Request, form_data:FormData)

This example is of course better in readability than the standard form handling:

async def Home(username: str = Form(...), something_else: str = Form(...)):

But still it's quite restricting, due to the necessary declaration of all form fields.

Is there any other more agnostic & elegant approach?

Thanks in advance & I apologize if this a trivial question I've failed to find through googling :)

davidism
  • 121,510
  • 29
  • 395
  • 339
Lopofsky
  • 518
  • 6
  • 15
  • **Option 1** of [this answer](https://stackoverflow.com/a/74015930/17865804) demonstrates how to use `request.form()` in FastAPI to retrieve both Form data and Files. – Chris Feb 14 '23 at 07:24

1 Answers1

13

You can get the underlying starlette request and use its request.form() method. It requires python-multipart to work:

from fastapi import FastAPI, Request

app = FastAPI()

@app.post("/example")
async def example(request: Request):
    form_data = await request.form()
    return form_data

Example of calling it:

C:\>curl -X POST "http://localhost:8000/example" -d "hello=there&another=value"
{"hello":"there","another":"value"}
clockwatcher
  • 3,193
  • 13
  • 13
  • Why is this not the first solution to the form problem, even the form examples don't even work from the FastApi site. This really helped me a lot . – kinsley kajiva Dec 17 '21 at 23:19
  • @clockwatcher If my HTML page has more
    tags and different names, Can I use this name to choose a specific name for this?
    – NHT_99 Aug 23 '22 at 03:31