1

I have a HTML page with forms. I need to integrate it with fastapi such that it receives data from the forms.

main.py

`from fastapi import FastAPI, Request
from starlette.responses import FileResponse

app = FastAPI()


@app.get("/")
async def start():
    return FileResponse("./templates/home.html")`

home.html

<!doctype html>
<body>
<div>
<label for="age">Age</label> </div>
<div>
<input type="text" class="form-control" id="age" name="age" placeholder="Enter your Age">
</select>
</div>
<button type="submit" class="btn btn-dark" value="submit">Submit</button>
</body>
</html>

I was able to return a HTML page using "return FileResponse("./templates/home.html")". But I was not able to collect data via the form in HTML page.

Thoughts are appreciated. Thanks in advance.

pyComali
  • 44
  • 6
  • You need to make POST API that accepts form data. Start with the tutorial: https://fastapi.tiangolo.com/tutorial/request-forms/ – Gino Mempin Nov 13 '22 at 05:13
  • I'm a back-end programmer, so I may be wrong here...but don't you need a `
    ` tag to submit a form?
    – CryptoFool Nov 13 '22 at 05:15
  • @GinoMempin - The POST thing was my first thought. But I Googled it. It appears that you can do a form submission with either a GET or a POST request. In fact, in a `
    ` tag, the `method` attribute defaults to `GET`. When submitting via `GET`, form values are sent as query parameters.- See https://www.geeksforgeeks.org/which-http-method-is-used-to-send-the-form-data/
    – CryptoFool Nov 13 '22 at 05:17
  • @CryptoFool Using a GET API to pass form data _could_ work, but that is not a "good" practice, especially if it's the same API for returning the form. My main point was creating a _separate_ POST API to submit form data. They should have 2 APIs, a GET to return the rendered form and a POST to submit the form data. Alternatively, they can also use PUT and/or submit the data as a JSON in the body, not using forms _at all_, as described in the FastAPI tutorial: https://fastapi.tiangolo.com/tutorial/body/. Basically, don't get the data in the GET endpoint (yes it's ironic). – Gino Mempin Nov 13 '22 at 05:47
  • 1
    Plenty of examples can be found [here](https://stackoverflow.com/a/71365646/17865804), [here](https://stackoverflow.com/a/70771526/17865804) and [here](https://stackoverflow.com/a/74317758/17865804), as well as [here](https://stackoverflow.com/a/70640522/17865804), [here](https://stackoverflow.com/a/71665594/17865804) and [here](https://stackoverflow.com/a/73359311/17865804). – Chris Nov 13 '22 at 06:42

0 Answers0