Free auditStart free
GuideError · HTTP status codes

400 Bad Request in Flask

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.

3 min
read
3
sources
Oct 29, 2026
updated
Scaplet Editorial Team
author
The short answer

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.

  1. Where a Flask 400 comes from
  2. Reproduce and check it in 2 minutes
  3. Fixes: validate, default, or answer in JSON
  4. What it means for SEO and crawlers
30-second check

Where does your site stand?

Four quick questions, then a straight answer.

1/4Have you checked your own site for this?
Summarize this page withChatGPTClaudePerplexityGoogleAI Mode
01What raises BadRequest in a Flask app

Where a Flask 400 comes from

Flask sits on Werkzeug, and Werkzeug's 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:
Trigger

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
Trigger

Your own abort(400)

Example
if username is None: abort(400)
Fix
Intended: make sure the client sends the parameter
Trigger

Any code raising werkzeug.exceptions.BadRequest

Example
A validation helper in your app or a library
Fix
Read the traceback for the raiser

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.

02Check it

Reproduce and check it in 2 minutes

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):

Your own app: with and without the form 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.

Public endpoint: a known 400
curl -s -o /dev/null -w "%{http_code}\n" https://httpbin.org/status/400
# Expect: 400
03Fix it on your stack

Fixes: validate, default, or answer in JSON

Decide whether a missing field is the client's fault. If it is, keep the 400 and make it explicit and readable. If the field is optional, stop indexing with brackets:
Explicit 400 with a reason, from the Flask docs' pattern
from 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)
    ...
JSON instead of HTML for HTTP errors (Flask docs)
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
A 400-only handler
@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:

Keep the 400 if
  • The client omitted a required parameter
  • You can name the missing field in the response
Change the code path if
  • The field is optional and a default makes sense
  • Your own form or script uses a different field name than the route
04Explained

What it means for SEO and crawlers

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.

Questions

Asked a lot.

3 questions people ask next, answered from the sources on this page.

01What is BadRequestKeyError in Flask?

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.

02How do I return a JSON 400 instead of an HTML page?

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.

03Does abort(400) raise an exception?

Yes. Werkzeug's abort raises the HTTP exception for the code, and abort(400) raises BadRequest.

Sources · 3

Every fact, linked and dated.

Official docs first. The date is when we last opened each page.
  • palletsprojects.com
  • google.com
  1. 01Werkzeug: HTTP exceptions (BadRequest, BadRequestKeyError, abort)werkzeug.palletsprojects.com · checked 2026-11-01
  2. 02Flask: handling application errorsflask.palletsprojects.com · checked 2026-11-01
  3. 03How HTTP status codes affect Google's crawlersdevelopers.google.com · checked 2026-11-01
Free · 2 minutes

Tools point. Agencies advise. This one ships.

Run the free audit, then approve the fixes. Every change can be undone.

Free, no card60 secondsNobody will call you
  • 46 fixes shipped without a ticket Brightpipe
  • 0→7 ChatGPT citations in six weeks Paylane