AskReference
CauseIntermediate

Why does an HTML form with method="get" and a form field named 'name' fail to submit the value to a FastAPI endpoint that expects a Form parameter, while the same form with method="post" works?

Because in an HTML GET form, the browser serializes form fields as URL query parameters, not as a request body. FastAPI's Form parameter expects the value in the body as form-encoded data, so a GET form never provides that body field and FastAPI returns a 422 validation error. Switching the method to POST sends the form data in the body, which FastAPI can read with Form.

FastAPI normally expects JSON input, and to read traditional HTML form data it provides the Form dependency, which extracts values from an encoded request body. When a standard HTML form uses method="get", the browser follows the HTML specification and places the form field values into the URL as query parameters, so the request looks like GET /who2?name=Bob instead of putting name in the body. FastAPI's endpoint declares name as a body field via Form(), but the GET request has no body, so validation fails with "field required" and a 422 response. The book notes that this is a documented HTML behavior, and also mentions that if the URL already had query parameters they would be replaced by the form fields. The correct fix, per the HTML specification and the book's recommendation, is to change the form's action method to post, which causes the browser to send the form data in the request body where FastAPI's Form can read it. A POST endpoint for the same path then works correctly.

Key points

  • HTML GET forms put field values into the URL query string, not into the request body.
  • FastAPI's Form parameter reads form fields from the encoded request body.
  • A GET request with Form() therefore returns a 422 error because the body field is missing.
  • Changing the form method to POST sends the data in the body, so FastAPI can parse it.
  • The book calls this an HTML weirdness and says to use POST for HTML form submissions.
Source:FastAPI: Modern Python Web Development· Forms and Templates· p. 233–238
Cover of FastAPI: Modern Python Web Development

FastAPI: Modern Python Web Development

Bill Lubanovic;

First Edition · O'Reilly Media, Inc.

View this ebook