Lesson 5
Combining Methods into Single Endpoints
Combining Methods into Single Endpoints

Welcome to the final lesson of our course! In previous lessons, we built separate endpoints for each HTTP method to manage our users, which helped us maintain clarity and focus on each task.

In this lesson, we'll focus on combining multiple HTTP methods into a single endpoint. We will also highlight what we did previously, the changes made, and why combining methods can sometimes be more practical. Let's dive in!

Recap of Basic Setup

We've already configured a Flask application and created a mock database of users. Here's the initial setup code for context:

Python
1from flask import Flask, jsonify 2 3# Initialize a Flask app instance 4app = Flask(__name__) 5 6# Mock database as a list of dictionaries 7database = [ 8 {"id": 1, "username": "cosmo"}, 9 {"id": 2, "username": "jake"}, 10 {"id": 3, "username": "emma"} 11]

And of course, we also had individual methods for different operations.

How to Accept Multiple HTTP Methods

Combining multiple HTTP methods into a single endpoint can help simplify your API routes and make the codebase more maintainable. You can achieve this by specifying a list of methods in the methods parameter of the @app.route decorator. Here is a simple, generic example demonstrating an endpoint that accepts GET, POST, PUT, and DELETE methods:

Python
1@app.route('/example', methods=['GET', 'POST', 'PUT', 'DELETE']) 2def handle_example(): 3 if request.method == 'GET': 4 # Handle GET request 5 elif request.method == 'POST': 6 # Handle POST request 7 elif request.method == 'PUT': 8 # Handle PUT request 9 elif request.method == 'DELETE': 10 # Handle DELETE request
  • Combining Methods: The @app.route('/example', methods=['GET', 'POST', 'PUT', 'DELETE']) decorator specifies that the /example endpoint can handle GET, POST, PUT, and DELETE requests.
  • Method Handling: Inside the function, the method of the request is checked using request.method, and appropriate code can be placed under each condition (if, elif).
Can We Combine All Our Methods into One Endpoint?

Combining all methods into a single endpoint is not practical for several reasons, such as complexity and difficulty in managing different operations. Instead, we will group our endpoints into two main ones:

  1. Endpoint Without ID: This combines GET to retrieve all users and POST to create a new user.
  2. Endpoint With ID: This combines GET, PUT, and DELETE for operations on individual users specified by their ID.

This approach keeps our code organized and maintainable while still simplifying the API design.

Combining GET and POST Methods

We previously created /all_users for GET requests and /users for POST requests. Now, let's combine GET and POST methods into a single /users endpoint.

Here's the code to achieve this:

Python
1@app.route('/users', methods=['GET', 'POST']) 2def handle_users(): 3 # Check if the request method is GET to retrieve all users 4 if request.method == 'GET': 5 return jsonify(database) 6 7 # Check if the request method is POST to create a new user 8 elif request.method == 'POST': 9 new_user = request.get_json() 10 if "username" not in new_user: 11 return jsonify(error="Invalid data"), 400 12 new_id = max(user['id'] for user in database) + 1 13 new_user["id"] = new_id 14 database.append(new_user) 15 return jsonify(new_user), 201
  • Change Made: We combined retrieving all users and creating a new user into a single endpoint.
  • Old vs. New: Instead of having /all_users and /users separately, both now reside at /users.
Combining GET, PUT, and DELETE Methods for Individual Users

We previously had separate endpoints for GET, PUT, and DELETE operations for individual users. Let's streamline this by combining these methods into a single /users/<int:user_id> endpoint.

Here's the code to achieve this:

Python
1@app.route('/users/<int:user_id>', methods=['GET', 'PUT', 'DELETE']) 2def handle_user(user_id): 3 # Check if the request method is GET to retrieve a user by ID 4 if request.method == 'GET': 5 for user in database: 6 if user['id'] == user_id: 7 return jsonify(user) 8 return jsonify(error="User not found"), 404 9 10 # Check if the request method is PUT to update a user by ID 11 elif request.method == 'PUT': 12 updated_user = request.get_json() 13 if "username" not in updated_user: 14 return jsonify(error="Invalid data"), 400 15 for user in database: 16 if user['id'] == user_id: 17 user['username'] = updated_user['username'] 18 return jsonify(user) 19 return jsonify(error="User not found"), 404 20 21 # Check if the request method is DELETE to delete a user by ID 22 elif request.method == 'DELETE': 23 for user in database: 24 if user['id'] == user_id: 25 database.remove(user) 26 return jsonify(message="User deleted") 27 return jsonify(error="User not found"), 404
  • Change Made: Combined getting a single user, updating a user, and deleting a user into a single endpoint.
  • Old vs. New: Instead of having separate GET, PUT, and DELETE endpoints for individual users, all these operations now reside at /users/<int:user_id>.
Summary and Next Steps

In this lesson, you have learned:

  • How to combine multiple HTTP methods (GET, POST, PUT, DELETE) into single endpoints.
  • The benefits of combining methods for efficient API design.
  • Implementing combined methods for user management in a Flask application.

As you complete this lesson, you should feel confident in creating more sophisticated and efficient endpoints in your Flask applications. This marks the end of our comprehensive course on mastering Flask HTTP methods. Keep practicing and apply your skills to real-world projects. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.