Handling HTTP Requests in Flask

Tutorial 4 of 5

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.