Handling HTTP Methods in Flask Views

Tutorial 3 of 5

Handling HTTP Methods in Flask Views

1. Introduction

Goal

This tutorial aims to introduce you to handling different HTTP methods in Flask. By the end of this tutorial, you will be able to create, retrieve, update, or delete data from your Flask application.

Learning Outcomes

You will learn how to:
- Understand the different HTTP methods and their use.
- Implement the HTTP methods in Flask.
- Handle different HTTP methods in your Flask views.

Prerequisites

A basic understanding of Python and Flask is required.

2. Step-by-Step Guide

HTTP stands for HyperText Transfer Protocol. It's the underlying protocol used by the World Wide Web to define how messages are formatted and transmitted. Main HTTP methods include GET, POST, PUT, DELETE, etc.

In Flask, you can handle these methods using route decorators in your views.

GET Method

GET is the default method in Flask and it is used to send a request to the server to retrieve data.

POST Method

The POST method is used to send data to the server to create a new resource.

PUT Method

The PUT method is used to update an existing resource on the server.

DELETE Method

The DELETE method is used to delete an existing resource on the server.

3. Code Examples

Let's look at examples of how to implement these methods in Flask views.

GET Method

@app.route('/users', methods=['GET'])
def get_users():
    # Get all users
    all_users = User.query.all()
    return jsonify([user.serialize() for user in all_users])

In this example, we define a route '/users' that accepts GET requests. It retrieves all users from the database and returns them as a JSON response.

POST Method

from flask import request

@app.route('/users', methods=['POST'])
def add_user():
    # Get user data from request
    user_data = request.get_json()
    new_user = User(name=user_data['name'], email=user_data['email'])
    db.session.add(new_user)
    db.session.commit()
    return jsonify(new_user.serialize()), 201

Here, we define a route '/users' that accepts POST requests. It gets the user data from the request, creates a new User object, saves it to the database, and returns the new user as a JSON response.

PUT Method

@app.route('/users/<int:id>', methods=['PUT'])
def update_user(id):
    # Get user data from request
    user = User.query.get(id)
    user_data = request.get_json()
    user.name = user_data['name']
    user.email = user_data['email']
    db.session.commit()
    return jsonify(user.serialize())

This is a route that accepts PUT requests to update a user. It finds the user by id, updates user's data, and returns the updated user as a JSON response.

DELETE Method

@app.route('/users/<int:id>', methods=['DELETE'])
def delete_user(id):
    # Find user by id and delete
    user = User.query.get(id)
    db.session.delete(user)
    db.session.commit()
    return '', 204

This route accepts DELETE requests to delete a user. It finds the user by id, deletes it from the database, and returns an empty response with a 204 status code, which means 'No Content'.

4. Summary

In this tutorial, we covered how to handle different HTTP methods in Flask. We learned how to create, retrieve, update, and delete resources in a Flask application using the GET, POST, PUT, and DELETE methods.

5. Practice Exercises

  1. Create a Flask application that handles GET and POST requests for a 'products' route.
  2. Extend your application to handle PUT and DELETE requests for a specific product in the 'products' route.
  3. Create a Flask application that handles all four HTTP methods for a 'blogs' route.

Remember to follow best practices and thoroughly test your code.

Happy Coding!