Python Flask Routers

In the last tutorial, we have learned about setting the Flask local development environment. In this tutorial, we are going to cover the Flask routers.

Routers are simply a way to assign URLs to functions. Every web framework provides routing and Flask is no exception. Here is a simple Flask router.

from flask import Flask
app = Flask(__name__)

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

Flask provides a built-in function called route() that is accesible using the @app variable i.e instance of Flask.

By default, Flask routers accept all HTTP methods. You can limit or restrict the HTTP methods using the following code.

from flask import Flask
app = Flask(__name__)

@app.route("/api/v1/users/", methods=['GET', 'POST'])
def users():
    if request.method == 'GET':
       return 'It's a GET request'
    if request.method == '
POST':
       return '
It's a POST request'

You can also provide variables in the routes. Here is the code for the same.

from flask import Flask
app = Flask(__name__)

@app.route("/api/v1/users/<int:userId>", methods=['GET', 'POST'])
def users(userId):
  ...rest of the code

Routers variables can accept the following data types:

  1. string: Accepts any text without a slash (the default).
  2. int: Accepts integers.
  3. float: Accepts numerical values containing decimal points.
  4. path: Similar to a string, but accepts slashes.

When we want to send the response back to the user, we can do it in multiple ways. You can either return a simple text or render a HTML template. It’s up to you and the requirements of the application. Let’s look over the code to handle some of the common responses.

Here is the code to return simple text.

from flask import Flask
app = Flask(__name__)

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

Here is the code to return a custom header’s response. We need to import make_response package.

from flask import Flask, make_response
app = Flask(__name__)

@app.route("/api/v1/users")
def users():
    headers = {"Content-Type": "application/json"}
    return make_response('Hello World!',
                         200,
                         headers=headers)

We can also render templates in the response, we need to import render_template to do the same. Here is the sample code.

from flask import Flask, render_template
app = Flask(__name__,
            template_folder="templates")

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

We will learn about Flask templating in detail in the upcoming tutorial.

We can also perform the URL redirect from the routes. We need to import url_for package for the same. Here is the sample code.

from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route("/login")
def login():
    return redirect(url_for('dashboard'))

It’s a best practice to redirect to the route not URL directly.

This is it for the Flask routers. In the next tutorial, we will learn about Flask templating.

Pankaj Kumar
Pankaj Kumar
Articles: 207