Lesson 2
Inserting Data with POST Requests
Inserting Data with POST Requests

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.

What are POST Requests?

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.

Setup Recap

Here's a quick recap of our existing setup:

Python
1from 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.

Step 1: Defining a POST Endpoint

We begin by defining a route for the endpoint and specifying that it only accepts POST requests.

Python
1# 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.

Step 2: Extract Data from Request Body

Next, we get the new user data from the request body in JSON format.

Python
1# 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()
  • The request.get_json() method extracts the data sent in the request body.
  • A request body is the part of the HTTP request where data is sent to the server. In POST requests, this data is typically in JSON format.
  • We use the request body instead of path or query parameters because it allows us to send structured, complex data more cleanly. Path and query parameters, commonly used in GET requests, are better suited for simpler data like IDs or search terms.
Step 3: Validate the New Data

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.

Python
1# 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
  • Before processing, we validate the incoming data by checking if the username field is present.
  • If the validation fails, we return a 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).
Step 4: Generate ID, Append and Return

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.

Python
1# 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
  • A new unique ID is generated by finding the maximum ID in the current database and adding 1.
  • The new user data is appended to the mock database.
  • Finally, we return the newly created user with a 201 status code, indicating "Created". This means the request has been fulfilled, and a new resource has been created as a result.
Accessing the Endpoint

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:

JSON
1{ 2 "username": "new_user" 3}

If the request is successful, the server will return a response with a 201 status code, similar to:

JSON
1{ 2 "id": 4, 3 "username": "new_user" 4}
Summary and Practice Exercises

In this lesson, you learned how to handle POST requests to create new data in a Flask application. We covered:

  • The purpose and use cases of POST requests
  • Setting up a POST endpoint
  • Validating incoming data
  • Generating unique IDs
  • Returning appropriate HTTP responses

These 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!

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