3

I can read JS FormData with Python FastAPI from my HTML code like this:

<form>
 <input type ="number" name="test1">
</form>

Python FastAPI:

@app.post("/zip")
async def buildScaffolding( test1: int=Form(...)):
    print(test1)
    return ""

But now I want to change the HTML form dynamically. Like when you buy items in a shop:

<form>
 <input type ="number" name="numberItems">
 <!-- item 1-->
 <input type ="text" name="item_1">
 <!-- item 2-->
 <input type ="text" name="item_2">
 ...
 <!-- item n-->
 <input type ="text" name="item_n">
</form>

Question: How can I process the input with Python FastAPI, if I don´t know how many items will be sent?

Umbrella Brothers
  • 327
  • 1
  • 5
  • 15
  • For anyone coming across this in the future, see https://stackoverflow.com/questions/62386287/fastapi-equivalent-of-flasks-request-form-for-agnostic-forms as well. – MatsLindh Jul 07 '21 at 13:45

3 Answers3

4

In the current case, we dont know how many inputs, to keep it simple, in the case of dynamically created inputs, it is preferrable to take request as request contains form which is added once we press submit or enter. That means, after submitting whatever the input is, the request will carry it as form to the api.

from fastapi.encoders import jsonable_encoder
@app.post('/check')
async def check(request: Request):
    da = await request.form()
    da = jsonable_encoder(da)
    print(da)
    return da

we can use jsonable_encoder to convert the form inputs into json format. curl it to check how it works. for example,

curl -i -d "param1=value1&param2=value2" http://localhost:8000/check

Krish Na
  • 91
  • 1
  • 2
2

Below code will help you to get dynamic form data.


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

-1

You can create an Enum dynamically, this will let you create your query parameters dynamically.

from fastapi import FastAPI, Form
from enum import Enum

app = FastAPI()

DynamicEnum = Enum("DynamicEnum", names={"item1":"items", "item2": "comes", "item3": "from", "item4": "database"})


@app.post("/select")
async def select_item(item: DynamicEnum = Form(...)):
    return item

Let's check the /docs and make sure FastAPI rendered that correctly.

enter image description here

Yagiz Degirmenci
  • 16,595
  • 7
  • 65
  • 85
  • But the dynamic part happens on the frontend. This is not the solution for the "n items with parameters are selected" problem, but maybe helpful for others. – Umbrella Brothers Oct 24 '20 at 17:32