Accept only GET Request in Flask


Flask - Accept only GET Request

In a flask application, we can specify a route with specific URL to accept only GET request using methods parameter of route() decorator.

The following is a simple code snippet to write route() decorator which specifies that the route must accept only GET request.

@app.route("/page-url", methods=["GET"])

You may replace page-url with the required URL.

methods parameter takes an array of allowed HTTP requests. In this case as our URL must accept only GET request, we specify only one element i.e., "GET" in the array.

GET request is usually used to get information from the server.

Example

In this example, we build a flask application where we have following project structure.

We define a route with the URL "/books" to accept only GET request, as shown in the following Python program.

main.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home_page():
    return render_template("index.html")

@app.route("/books", methods=["GET"])
def home_page():
    return render_template("show-books.html")

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

show-books.html

<!DOCTYPE html>
<html>
  <body>
   <h1>Show Books Page</h1>
   <p>Flask application by <a href="/">PythonExamples.org</a>.</p>
   <p>This is "show books" page.</p>
  </body>
</html>

Run Application

Open terminal or command prompt at the root of the application, and run the Python file main.py.

Run Flask Application

The flask application is up and running at URL http://127.0.0.1:8080/.

1. Send GET Request

We have used POSTMAN application, and sent a GET request to the URL http://127.0.0.1:8080/books.

Python Flask - Access only GET Request

The server responded with "show-books.html" template as instructed in the Python code, with a status code of 200.

2. Send POST Request

Now, let us try sending a POST request to the same URL, and observe the output.

Python Flask - Access only GET Request - Negative Scenario

The server responded with 405 METHOD NOT ALLOWED as shown in the above screenshot.

Project ZIP

Summary

In this Python Flask Tutorial, we learned how to define a route in Flask Application to accept only GET requests.