Flask / Flask Routing and Views

Creating Routes and Handling Requests

In this tutorial, we will explore how to create routes in Flask and handle HTTP requests. This is a fundamental aspect of building web applications, as it allows us to connect URL…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers URL routing, dynamic routes, and handling different types of requests in Flask.

1. Introduction

In this tutorial, we will be learning about creating routes and handling HTTP requests in Flask, a Python micro web framework. Flask allows us to map URLs to Python functions, which are also called "routes". This is a fundamental aspect of building any web application, as it allows us to determine what content is displayed to the user based on the URL they are visiting.

By the end of this tutorial, you will understand what routes are, how to create them, and how to handle HTTP requests.

Prerequisites: This tutorial assumes that you have a basic understanding of Python and a basic knowledge of HTML. Familiarity with Flask would be beneficial but isn't necessary.

2. Step-by-Step Guide

Concept of Routes and HTTP Requests

A route is a URL pattern that is used to fetch a particular webpage. When a URL matches a route, the associated Python function is executed, and its result is returned to the browser as a response.

HTTP requests are how we communicate with a server. The four most common types of requests are GET, POST, PUT, and DELETE.

Creating Routes in Flask

Creating a route in Flask is straightforward. We use the route() decorator to bind a function to a URL. Here is an example:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, World!"

In this example, '/' is the URL to which we are binding the function home(). When we navigate to the root URL of our application, we will see the text "Hello, World!".

Handling HTTP Requests

With Flask, we can easily handle different types of HTTP requests. By default, a route only answers to GET requests. But you can use the methods argument of the route() decorator to handle other types of requests. For example:

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()

In this example, the login() function will respond to both GET and POST requests. If the request method was POST, then the login form is posted. If the request method was GET, then the login form is displayed.

3. Code Examples

Example 1: Simple Route

from flask import Flask
app = Flask(__name__)

# This is a route
@app.route('/')
def home():
    # This function will be called when the '/' URL is accessed
    return "Hello, World!"

When you navigate to the root URL of your application, you will see "Hello, World!".

Example 2: Route with Variable

@app.route('/hello/<name>')
def hello(name):
    # The <name> inside the route is a variable
    return "Hello, %s!" % name

In this case, if you navigate to '/hello/John', you will see "Hello, John!".

Example 3: Route Handling GET and POST Requests

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    # Here we check the method of the request
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()

In this case, the login() function will respond to both GET and POST requests.

4. Summary

In this tutorial, we have learned about creating routes and handling HTTP requests in Flask. We learned how to bind Python functions to URLs and how to handle different types of HTTP requests.

Next steps in your learning could include learning about templates in Flask, form handling, and connecting to databases. Here are some additional resources:
- Flask Documentation
- The Flask Mega-Tutorial

5. Practice Exercises

  1. Create a Flask application with a route for '/about' that returns "About Page".
  2. Create a Flask application with a route for '/user/' that returns "User Profile: ".
  3. Create a Flask application with a POST route for '/login' that returns "User Logged In" if the request method is POST, and "Show Login Form" otherwise.

The solutions can be found in the Flask documentation. Keep practicing to solidify your understanding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Backlink Checker

Analyze and validate backlinks.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help