Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Flask Route – How to Perform URL Routing in Flask?

Flask Route

This article will deal with the Flask route to perform URL routing in Flask and then implement it in our flask application. So let’s get started!!

What is URL Routing?

URL routing is used to link a particular function (with the web page content) to its web page URL.

When we hit an endpoint, the web page will display its content, which is the function’s output linked to the URL endpoint using the route.

We can do the URL routing in the following ways:

How to route an URL to a Function

Let’s learn the different ways to setup a Flask route.

1. Using app.route()

Here, the syntax used is as follows:

@app.route('<endpoint>')

Therefore an example of Flask application webpage with URL – “localhost:5000/page” will look like:

from flask import Flask

app = Flask(__name__)

@app.route('/blogs')
def blogs():
    return 'Welcome to Blog site'

app.run(host='localhost', port=5000)

Note: The function name should be same as the endpoint name.

Run the application:

python filename.py
Blogs
Blogs

We can also have a URL with a variable endpoint. Such URLs are used for webpages whose functions take in argument from the users.

Consider the function:

from flask import Flask

app = Flask(__name__)

@app.route('/blogs/<int:id>')
def blogs(id):
    return f"Welcome to Blog number:{id}"

app.run(host='localhost', port=5000)

Note: Here the non-variable endpoint (blogs) will be the function name and the endpoint variable (id) will be an argument to the function.

Now, as you might have guessed, based on the variable endpoint, the webpage will show different output.

Blog id
Blog id

2. Using add_url_route() attribute

This function is normally used when we need to route a function externally without using decorators. The syntax :

app.add_url_route('<url_rule(endpoint_structure)>','<endpoint_name>',<view_function>')

Therefore consider the below file:

from flask import Flask

app = Flask(__name__)

def blogs():
    return f"Welcome to Blog Site"

app.add_url_rule('/blogs','blogs', blogs)

app.run(host='localhost', port=5000)

Here the output will be same as before.

Blogs
Blogs

Similarly, the syntax for variable endpoint is:

app.add_url_rule('<url_rule_with_variable>','<endpoint_name>',<view_function>)

There the variable endpoint file syntax will be:

from flask import Flask

app = Flask(__name__)

def blogs(id):
    return f"Welcome to Blog number:{id}"

app.add_url_rule('/blogs/<int:id>','blogs',blogs)

app.run(host='localhost', port=5000)

Run the application and note the output:

Blog 1
Blog 1

Here as well the output is same as before.

Conclusion

That’s it for this tutorial, guys! Do try the examples given above yourself for better understanding. 

See you in the next article! Till then, Happy coding!!