HTTP Methods (Flask)

In Flask, the methods argument on a route declares which HTTP verbs (GET, POST, PUT, DELETE, etc.) the view accepts. By default a route handles only GET, so you must opt in to POST and others.

Flask

HTTP methods describe the intent of a request: GET fetches data, POST creates it, PUT/PATCH update it, and DELETE removes it. Flask lets one URL serve several methods so a form page and its submission can share a route.

You typically branch on request.method inside the view to render a form on GET and process it on POST. If a client uses a method the route does not allow, Flask returns 405 Method Not Allowed automatically.

Adding 'GET' also gives you HEAD and OPTIONS for free, since Flask handles those automatically based on the GET handler.

Syntax

@app.route("/login", methods=["GET", "POST"])

Examples

Python

from flask import request

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        return f"Logging in {request.form['user']}"
    return "<form method='post'><input name='user'></form>"

Learn it in a lesson

See also

Back to the Dictionary