Understanding Routing and HTTP methods in Flask

Krishnavyshak
5 min readMar 8, 2023

--

PART2: A Beginner’s Guide to Routing and HTTP Methods in Flask

Flask is a popular web framework for Python that provides a simple and lightweight approach to building web applications. One of the key features of Flask is its routing system, which allows developers to map URL patterns to specific functions or views within their application.

In this article, we’ll take a closer look at Flask’s routing system and explore how it can be used to build powerful web applications.

What is Routing?

Routing is a fundamental concept in web development, and Flask’s routing system simplifies the process of directing users to the correct function or view within an application. Essentially, routing is like a roadmap for a web server, telling it where to go and what to do when a user makes a request.

In Flask, routing is made easy with the use of the @app.route decorator. This decorator is like a signpost that points to a specific Python function, which is then executed to provide the appropriate response to the user’s request.

For example, suppose we have a Flask application that includes a function to display a list of products. We could use the @app.route decorator to map the /products URL to this function, like so:

from flask import Flask

app = Flask(__name__)

@app.route('/products')
def list_products():
# code to retrieve and display list of products

Now, when a user requests the /products URL from our application, Flask will execute the list_products function and return the results.

URL Patterns

URL patterns are the building blocks of a web application’s routing system, and in Flask, they can be constructed using static and dynamic components. Static components are like signposts on a highway, pointing users to specific URLs that correspond to particular functions or views. Dynamic components, on the other hand, are like wildcard placeholders that match a variety of possible values, allowing for greater flexibility in handling user requests.

For instance, a URL pattern in Flask might include both static and dynamic components, like “/products/int:product_id”. The “/products/” component is a static component that corresponds to a specific function or view, while the “int:product_id” component is a dynamic component that can match any integer value. This enables Flask to retrieve and display the details of a specific product, based on the user’s request.

For example, we might define a URL pattern that includes both static and dynamic components like this:

@app.route('/products/<int:product_id>')
def show_product(product_id):
# code to retrieve and display details for product with given ID

In this case, the URL pattern includes the static /products/ component, followed by a dynamic <int:product_id> component. This dynamic component tells Flask to expect an integer value in the URL, which will be passed to the show_product function as a parameter.

Dynamic components can also include other data types, such as strings or floats, and can include additional formatting options to specify things like minimum and maximum values.

HTTP Methods

The routing system of Flask is not just limited to URL patterns but also encompasses support for HTTP methods. HTTP methods are used to specify the type of action being performed on a particular resource, like retrieving data or submitting a form. In simpler terms, it is like telling the server what to do with the requested data.

With Flask’s built-in support for several common HTTP methods, developers can easily create web applications that can handle a variety of user actions and inputs. The GET method, for example, is typically used to retrieve data, while the POST method is used to submit data, like a form. Similarly, the PUT method can be used to update a resource, and the DELETE method can be used to delete a resource.

By providing support for these commonly used HTTP methods, Flask offers developers the flexibility to design web applications that are tailored to their needs. Whether you need to retrieve data, submit a form, or update a resource, Flask’s routing system with built-in HTTP methods has got you covered.

These methods can be specified using additional decorators, like so:

@app.route('/products/<int:product_id>', methods=['GET', 'PUT'])
def update_product(product_id):
if request.method == 'GET':
# code to retrieve and display details for product with given ID
elif request.method == 'PUT':
# code to update the details for product with given ID
else:
# code to handle unsupported HTTP methods

In this example, we have defined a route for the /products/ URL pattern that supports both the GET and PUT HTTP methods. Depending on the method used in the request, Flask will execute the appropriate code block within the update_product function.

Routing Example

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
return 'This is the home page!'

@app.route('/about')
def about():
return 'This is the about page!'

@app.route('/contact')
def contact():
return 'This is the contact page!'

if __name__ == '__main__':
app.run()

In this example, we define three routes using the @app.route decorator. The first route, @app.route('/'), maps the root URL to the index() function, which returns a simple message for the home page. The second route, @app.route('/about'), maps the /about URL to the about() function, which returns a message for the about page. The third route, @app.route('/contact'), maps the /contact URL to the contact() function, which returns a message for the contact page.

When you run this script and visit http://localhost:5000/ in your web browser, you should see the message for the home page. If you visit http://localhost:5000/about, you should see the message for the about page, and if you visit http://localhost:5000/contact, you should see the message for the contact page.

HTTP Methods Example

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return 'This is a GET request!'
elif request.method == 'POST':
return 'This is a POST request!'
if __name__ == '__main__':
app.run()

In this example, we define a single route using the @app.route decorator, with support from both GET and POST HTTP methods. The index() function checks the HTTP method of the request using the request.method attribute, and returns a message depending on whether the request was a GET or POST request.

When you run this script and visit http://localhost:5000/ in your web browser, you should see the message for a GET request. If you use a tool like curl to send a POST request to the same URL, you should see the message for a POST request.

We can now run our Flask application by going into the terminal and running this command:

flask run

Conclusion

Flask’s routing system provides a powerful and flexible way to map URLs to specific functions or views within a web application. By using static and dynamic URL patterns, as well as support for HTTP methods, developers can create a wide range of web applications with Flask.

In addition to its routing system, Flask also includes support for templates, request handling, and database integration, making it a comprehensive web framework for Python developers. Whether you are building a simple website or a complex web application, Flask is a great choice for creating Python-based web projects.

--

--

Krishnavyshak
Krishnavyshak

No responses yet