Flask / Flask Basics

Handling HTTP Requests in Flask

In this tutorial, you'll learn about handling HTTP requests in Flask. You'll look at how to handle the different types of HTTP requests and how to retrieve data from them.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Introduces Flask, its features, and basic concepts including routing, templates, and request handling.

1. Introduction

In this tutorial, we will dive into handling HTTP requests in Flask, a micro web framework written in Python. We will explore how to deal with different types of HTTP requests like GET, POST, PUT and DELETE and how to retrieve data from these requests.

By the end of this tutorial, you will:
- Understand how to handle HTTP requests in Flask.
- Know how to retrieve data from these requests.
- Be able to implement these concepts in your Flask applications.

Prerequisites:
- Basic understanding of Python programming.
- Familiarity with Flask. If you're not familiar with Flask, check out the official Flask tutorial first.

2. Step-by-Step Guide

HTTP (HyperText Transfer Protocol) is a protocol for sending data over the internet. It defines how messages are formatted and transmitted, and what actions web servers and browsers should take in response to various commands.

In Flask, you can handle HTTP requests using route decorators. A route is associated with a Python function, and the function returns a response to the HTTP request.

Here's a simple example of a route in Flask:

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

This route responds to HTTP requests at the URL '/' (the root URL) with the text 'Hello, World!'.

HTTP Methods

There are four main types of HTTP requests: GET, POST, PUT, and DELETE.

  • GET: Retrieves data. This is the default method for many routes.
  • POST: Sends data to be processed by the server.
  • PUT: Updates existing data.
  • DELETE: Deletes existing data.

In Flask, you can specify the HTTP methods a route should respond to like this:

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # Process the POST data
    else:
        # Handle the GET request

Retrieving Data from Requests

When handling a POST or PUT request, you often need to retrieve data sent in the request. You can do this with request.form for form data and request.json for JSON data:

@app.route('/', methods=['POST'])
def index():
    form_data = request.form
    json_data = request.json

3. Code Examples

Example 1: Simple GET and POST request

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # Retrieve the form data
        form_data = request.form
        return 'Form data received: {}'.format(form_data)
    else:
        # Handle the GET request
        return 'This is a GET request'

if __name__ == "__main__":
    app.run(debug=True)

In this example, if the client sends a POST request, the server will return the form data. If the client sends a GET request, the server will return the string 'This is a GET request'.

Example 2: Using JSON data in a POST request

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['POST'])
def index():
    # Retrieve the JSON data
    json_data = request.get_json()
    return 'JSON data received: {}'.format(json_data)

if __name__ == "__main__":
    app.run(debug=True)

In this example, the server expects a POST request with JSON data. It retrieves the JSON data using request.get_json() and returns it in the response.

4. Summary

We've covered how to handle HTTP requests in Flask, including GET and POST requests, and how to retrieve form and JSON data from these requests.

For further learning, you could explore handling PUT and DELETE requests, and how to handle file uploads in Flask.

5. Practice Exercises

  1. Create a Flask route that responds to both GET and DELETE requests. In response to a DELETE request, it should return the string 'DELETE request received'.

  2. Create a Flask route that responds to PUT requests with JSON data. It should return the JSON data in the response.

Solutions:

  1. Solution to the first exercise:
@app.route('/', methods=['GET', 'DELETE'])
def index():
    if request.method == 'DELETE':
        return 'DELETE request received'
    else:
        return 'This is a GET request'
  1. Solution to the second exercise:
@app.route('/', methods=['PUT'])
def index():
    json_data = request.get_json()
    return 'JSON data received: {}'.format(json_data)

Remember, the best way to learn is by doing. Try to build some simple web applications using Flask and experiment with different types of HTTP requests.

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

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

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