🎓 A1Learner
🔍
0 of 50 lessons completed

Flask HTTP Methods

An HTTP method says what a request wants to do. GET asks for a page, and POST sends data.

Make the app

This line makes the Flask app. The two routes below belong to it.

from flask import Flask

app = Flask(__name__)

A GET-only route

This route has no methods list, so it answers GET only.

@app.route("/hello")
def hello():
    return "Hello!"

A route that takes both

The methods list lets this route take GET and POST.

@app.route("/both", methods=["GET", "POST"])
def both():
    return "Both"

Ask with GET and POST

The prints show the status of each ask. POST to the GET-only route gives 405.

client = app.test_client()
print(client.get("/hello").status_code)
print(client.post("/hello").status_code)
print(client.get("/both").status_code)
print(client.post("/both").status_code)

Example

from flask import Flask

app = Flask(__name__)

@app.route("/hello")
def hello():
    return "Hello!"

@app.route("/both", methods=["GET", "POST"])
def both():
    return "Both"

client = app.test_client()
print(client.get("/hello").status_code)
print(client.post("/hello").status_code)
print(client.get("/both").status_code)
print(client.post("/both").status_code)

Key points

  • A route answers GET requests unless methods says otherwise.
  • methods=["GET", "POST"] lets one route take both methods.
  • Use GET for reading and POST for sending.
  • A POST to a GET-only route returns a 405 status.

In this example, /hello answers GET only, and /both takes GET and POST. The test client asks each route with each method. GET to /hello prints 200, and POST to /hello prints 405. Both methods to /both print 200.

Note

A browser address bar always sends GET.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What status does a POST to a GET-only route return?