Missing key in request.form (or other request mapping)
- Example
- title = request.form['title']
- Fix
- Check the field name in the HTML form and the client, or read it with a default
Find why Flask returns 400: a missing form key raising BadRequestKeyError, or an explicit abort(400). Fix it and return JSON errors instead of HTML.
Flask returns 400 Bad Request when a Werkzeug BadRequest exception is raised. The most common source is request.form['name'] with a missing field, which raises BadRequestKeyError, a KeyError that is also a BadRequest. Your own abort(400) calls do the same. Read the field name in the error, then validate input or use a default.
Four quick questions, then a straight answer.
From your answers, this is quietly costing you traffic and nobody has the hours to chase it. Scaplet finds every affected page, drafts the fixes and tracks how AI answers mention you.
A data platform shipped 46 fixes without a ticket.
This looks handled. Re-check after a redesign, a migration or a big content push; that is when it breaks.
Your site is small and you have the time. Work through the steps on this page, starting with the pages that get the most traffic.
BadRequest is the exception behind every 400. Its docs describe it as raised when the browser sends something the application or server cannot handle. In practice three things raise it:The Werkzeug docs say accessing a missing form field raises BadRequestKeyError, which behaves like a KeyError but is also a BadRequest. When the application handles HTTP exceptions, a missing key becomes a 400 response, so you do not have to check every key first. The result for your user is a plain black-and-white page unless you register a handler.
Now send your own Flask route one request with the field and one without. This needs your dev server (flask run, default port 5000; replace the route and field):
curl -s -o /dev/null -w "%{http_code}\n" -X POST -d 'title=hello' http://127.0.0.1:5000/posts
curl -s -o /dev/null -w "%{http_code}\n" -X POST -d 'other=1' http://127.0.0.1:5000/posts
# Expect: success status for the first, 400 for the second if the route reads
# request.form['title'] with no default.If both calls return 400, the problem is not that one key. Print request.form and request.get_data() inside the route to see what actually arrived.
curl -s -o /dev/null -w "%{http_code}\n" https://httpbin.org/status/400
# Expect: 400from flask import abort, request
@app.route("/profile")
def user_profile():
username = request.args.get("username")
# if a username isn't supplied in the request, return a 400 bad request
if username is None:
abort(400)
...from flask import json
from werkzeug.exceptions import HTTPException
@app.errorhandler(HTTPException)
def handle_exception(e):
"""Return JSON instead of HTML for HTTP errors."""
# start with the correct headers and status code from the error
response = e.get_response()
# replace the body with JSON
response.data = json.dumps({
"code": e.code,
"name": e.name,
"description": e.description,
})
response.content_type = "application/json"
return response@app.errorhandler(werkzeug.exceptions.BadRequest)
def handle_bad_request(e):
return 'bad request!', 400
# or, without the decorator
app.register_error_handler(400, handle_bad_request)abort() also takes a description, which the error handler can use as the message. To turn every Flask error page into JSON, register a handler for HTTPException. Note the docs' warning: it also triggers for 404 and 405 errors raised during routing, so keep the original code and name in the body.
If you only want to change 400 pages, register for BadRequest. The docs stress that a handler does not set the response status for you, so return it yourself:
Google handles 400 like the other 4xx codes except 429: content from the URL is ignored. Crawlers send GET requests with the parameters in the URL, so a route that calls abort(400) when a query parameter is absent returns 400 to a crawler that requests the bare path. If that path should be indexable, give it a default instead of a 400. See 400 Bad Request for the status in general, 4xx errors, and the matching Django guide, 400 in Django.
3 questions people ask next, answered from the sources on this page.
It is raised when you read a missing key such as request.form['title']. It acts like a KeyError and is also a BadRequest, so the response is a 400.
Register an errorhandler for HTTPException or BadRequest that builds a JSON body and returns it with the 400 status. A handler does not set the status for you.
Yes. Werkzeug's abort raises the HTTP exception for the code, and abort(400) raises BadRequest.
Run the free audit, then approve the fixes. Every change can be undone.