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.
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.
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.
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:
- string: Accepts any text without a slash (the default).
- int: Accepts integers.
- float: Accepts numerical values containing decimal points.
- 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.
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.
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.
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.
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.