Submitting selected item from an HTML dropdown to a FastAPI backend

I’m looking for guidance on how to send the chosen value from an HTML dropdown list on my frontend to my FastAPI backend.

I have set up a basic form which includes a dropdown that should transmit the selected name upon submission. However, I’m encountering an error indicating that a required field is not provided during form submission.

Here’s the FastAPI code I’m working with:

from fastapi import FastAPI, Request, Form
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates/")

@app.get('/')
def home():
    return 'hello'

@app.get("/form")
def display_form(request: Request):
    message = "Please choose your name"
    return templates.TemplateResponse('form.html', context={'request': request, 'message': message})

@app.post("/form")
def submit_form(request: Request, message = Form(...)):
    return templates.TemplateResponse('form.html', context={'request': request, 'message': message})

And this is the associated HTML/Jinja2 template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Choose Your Name</title>
</head>
<body>
<form method="post">
    <select name="names" id="names">
        <option value="name1">Name 1</option>
        <option value="name2">Name 2</option>
        <option value="name3">Name 3</option>
        <option value="name4">Name 4</option>
    </select>
    <input type="submit" value="Submit">
</form>
    
<p>Selected Name: {{ message }}</p>

</body>
</html>

Whenever I submit, I encounter this error:

{"detail":[{"loc":["body","message"],"msg":"field required","type":"value_error.missing"}]}

I would like to select a name from the dropdown, click submit, and see my choice displayed on the page. How can I resolve this issue between the HTML form and the FastAPI backend?

Wait, are you trying to display the option text or just the value? Your dropdown sends “name1”, “name2” etc, but what if you want “Name 1” instead? What’s your use case? Might need a different approach depending on what you need.

hey, so like, you gotta update your backend to grab the correct input. ur dropdown’s name is names, but in FastAPI, you’re using message. just change that to names = Form(...) and you should be good to go!

Your error happens because there’s a mismatch between your HTML form and FastAPI parameter names. The dropdown uses name="names" but your backend expects message. FastAPI can’t find a field called message in your form data, so you get the “field required” error. Fix this by changing your POST endpoint to use names = Form(...) instead of message = Form(...). That’ll capture the dropdown value correctly. Also, you might want to update your template to use selected_name instead of message - it’s clearer about what the variable actually contains.