In our previous lesson, we explored how to handle GET requests in Flask to retrieve data from our mock database. Now, we will take a step further and learn how to insert new data using POST requests. Understanding POST requests is essential for building web applications that allow users to submit data, such as registration forms, comments, or any other type of user-generated content.
A POST request is one of the HTTP methods used to send data to the server to create a new resource. Unlike GET requests that retrieve data, POST requests are used to submit data to be processed to a specified resource. In this lesson, we will explore how to handle them in Flask and add data to our mock database.
Here's a quick recap of our existing setup:
Python1from flask import Flask, request, jsonify 2 3# Initialize the Flask app 4app = Flask(__name__) 5 6# Mock database with user data 7database = [ 8 {"id": 1, "username": "cosmo"}, 9 {"id": 2, "username": "jake"}, 10 {"id": 3, "username": "emma"} 11]
Now, let's create a POST endpoint to add new data. This endpoint will accept user data in JSON format and add it to our mock database.
We begin by defining a route for the endpoint and specifying that it only accepts POST
requests.
Python1# Define a route to create a new user 2@app.route('/users', methods=['POST']) 3def create_user():
By specifying methods=['POST']
, we ensure this route only responds to POST
requests, differentiating it from any GET
requests to the same /users
URL.
Next, we get the new user data from the request body in JSON format.
Python1# Define a route to create a new user 2@app.route('/users', methods=['POST']) 3def create_user(): 4 # Get the new user data from the request body 5 new_user = request.get_json()
request.get_json()
method extracts the data sent in the request body.POST
requests, this data is typically in JSON format.We need to ensure that the incoming data is valid. In this case, we check that the username
is present in the request. If not, an error response is returned.
Python1# Define a route to create a new user 2@app.route('/users', methods=['POST']) 3def create_user(): 4 # Get the new user data from the request body 5 new_user = request.get_json() 6 7 # Validate the new user data 8 if "username" not in new_user: 9 # Return a 400 Bad Request error if data is invalid 10 return jsonify(error="Invalid data"), 400
username
field is present.400
status code, which indicates a "Bad Request." This means the server cannot process the request due to client error (e.g., missing required fields).We generate a new unique ID for the user by finding the maximum existing ID and adding 1. Finally, we add the new user to the mock database and return a success response.
Python1# Define a route to create a new user 2@app.route('/users', methods=['POST']) 3def create_user(): 4 # Get the new user data from the request body 5 new_user = request.get_json() 6 7 # Validate the new user data 8 if "username" not in new_user: 9 # Return a 400 Bad Request error if data is invalid 10 return jsonify(error="Invalid data"), 400 11 12 # Generate a new ID by finding the maximum existing ID and adding 1 13 new_id = max(user['id'] for user in database) + 1 14 new_user["id"] = new_id 15 16 # Add the new user to the mock database 17 database.append(new_user) 18 19 # Return the newly added user as JSON with a status code 201 (Created) 20 return jsonify(new_user), 201
201
status code, indicating "Created". This means the request has been fulfilled, and a new resource has been created as a result.To access this endpoint, the client should send a POST
request to /users
passing the user data in the request body as JSON.
An example of the request body would be the following:
JSON1{ 2 "username": "new_user" 3}
If the request is successful, the server will return a response with a 201
status code, similar to:
JSON1{ 2 "id": 4, 3 "username": "new_user" 4}
In this lesson, you learned how to handle POST requests
to create new data in a Flask
application. We covered:
POST requests
POST
endpointThese concepts are essential for building dynamic web applications that can handle user input and create new resources. In the upcoming practice exercises, you will get hands-on experience with creating POST requests
and reinforcing what you've learned in this lesson. Great job so far, and let's move forward!