Welcome to the final lesson of the course! On our journey so far, we've learned how to retrieve data using GET requests and insert new data with POST requests. Today, we'll focus on updating existing records using PUT requests.
By the end of this lesson, you'll be able to set up a PUT
endpoint to update user data in our mock database, validate the incoming data, find the record you wish to update, make the necessary changes, and return the appropriate response.
A PUT request is used to update an existing resource on the server. Unlike POST
requests, which are often used to create new resources, PUT
requests are used to modify or replace the current representation of the target resource with the uploaded content. For example, if you want to change a user's username in a database, you would use a PUT
request to do this.
Before we dive into PUT
requests, let's quickly recap our existing setup for context. We've already set up a Flask app and a mock database of users. Here is the code for the initialization:
Python1from flask import Flask, request, 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]
We already set up GET
and POST
endpoints in previous lessons to retrieve and insert data into our mock database. Now, let's see how we can update existing data.
First, we need to define a PUT
route in our Flask application. Let's create an endpoint that listens for PUT
requests at /users/<int:user_id>
:
Python1@app.route('/users/<int:user_id>', methods=['PUT']) 2def update_user(user_id): 3 # Get the updated user data from the request body 4 updated_user = request.get_json()
- The
@app.route
decorator defines the endpoint path and the HTTP methods it accepts. In this case, it acceptsPUT
requests. <int:user_id>
in the path means this endpoint expects an integer ID to specify the user to update. Including the user ID in the URL clearly indicates which user is being updated and follows a common convention in web APIs.- We extract only the properties that need updating from the request body using the
request.get_json()
method, which allows us to focus on the changes to be made while keeping the URL structure clean and readable.
Next, we need to validate the incoming data to ensure it contains the necessary fields. Specifically, we want to check if the username
field is present:
Python1@app.route('/users/<int:user_id>', methods=['PUT']) 2def update_user(user_id): 3 # Get the updated user data from the request body 4 updated_user = request.get_json() 5 6 # Validate the updated user data 7 if "username" not in updated_user: 8 # Return a 400 Bad Request error if the data is invalid 9 return jsonify(error="Invalid data"), 400
- The
if
statement checks ifusername
is present inupdated_user
. - If not, it returns a
400 Bad Request
error along with an error message in JSON format.
Now that we have validated the input, we can proceed to update the user's data in the mock database. Here's how we can do it:
Python1@app.route('/users/<int:user_id>', methods=['PUT']) 2def update_user(user_id): 3 # Get the updated user data from the request body 4 updated_user = request.get_json() 5 6 # Validate the updated user data 7 if "username" not in updated_user: 8 # Return a 400 Bad Request error if data is invalid 9 return jsonify(error="Invalid data"), 400 10 11 # Find and update the user in the mock database 12 for user in database: 13 if user['id'] == user_id: 14 # Update the user's username 15 user['username'] = updated_user['username'] 16 # Return the updated user as JSON 17 return jsonify(user)
- We loop through the
database
list to find the user with the matchinguser_id
. - If we find a match, we update the
username
field of that user. - Finally, we return the updated user data as JSON.
To ensure that our API is user-friendly and follows standard practices, we need to return appropriate responses, including meaningful HTTP status codes:
Python1@app.route('/users/<int:user_id>', methods=['PUT']) 2def update_user(user_id): 3 # Get the updated user data from the request body 4 updated_user = request.get_json() 5 6 # Validate the updated user data 7 if "username" not in updated_user: 8 # Return a 400 Bad Request error if data is invalid 9 return jsonify(error="Invalid data"), 400 10 11 # Find and update the user in the mock database 12 for user in database: 13 if user['id'] == user_id: 14 # Update the user's username 15 user['username'] = updated_user['username'] 16 # Return the updated user as JSON 17 return jsonify(user) 18 19 # Return an error message if the user is not found 20 return jsonify(error="User not found"), 404
- If the user is successfully updated, we return the updated user data with a default
200 OK
status. - If the user with the specified
user_id
is not found, we return a404 Not Found
error.
To access this endpoint, the client should send a PUT
request to /users/<user_id>
, passing the updated user data in the request body as JSON. The <user_id>
in the URL should be replaced with the ID of the user you intend to update. This works similarly to the POST
request we discussed in the previous lesson.
An example of the request body would be:
JSON1{ 2 "username": "updated_user" 3}
If the request is successful, the server will return a response with a 200
status code, similar to:
JSON1{ 2 "id": 1, 3 "username": "updated_user" 4}
If the user with the specified ID is not found, the server will return a 404
status code with an error message.
In this lesson, you learned how to handle PUT requests
to update existing data in a Flask application. We covered:
- The purpose and use cases of
PUT requests
. - Setting up a
PUT
endpoint. - Validating incoming data.
- Updating the data in the mock database.
- Returning appropriate HTTP responses.
You now have the foundational knowledge to update existing resources in your Flask applications. By reaching this point, you've completed the course! Great job sticking through to the end. Now it's time to practice what you've learned through hands-on exercises. Happy coding!