Welcome to another milestone in your Flask journey. Throughout this course, we will explore various HTTP methods using a mock database to illustrate practical applications. In this lesson, we will concentrate on using the GET method to retrieve data from a mock database.
By the end of this lesson, you will be able to create Flask endpoints to retrieve data using GET requests, building on the concepts you've already learned. We will also cover how to handle errors and return appropriate status codes to ensure robust and reliable API endpoints.
Let's go over how to set up a basic Flask application and introduce the mock database we'll be using throughout this course to teach HTTP methods.
Python1from flask import Flask 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]
In this setup, we initialize a Flask application and create a mock database represented as a list of dictionaries. This user database will be the core of our exercises throughout the course, where we will practice retrieving, inserting, editing, and deleting data.
Now, let's create an endpoint to retrieve all users from our mock database. We will use the GET method to define this route. Here's the code to define such a route:
Python1from flask import jsonify 2 3@app.route('/all_users', methods=['GET']) 4def get_users(): 5 # Return the entire user database as JSON 6 return jsonify(database)
Explanation:
/all_users
URL.get_users
function is called when a GET request is made to this URL.jsonify(database)
function converts the user database (a list of dictionaries) into a JSON response and returns it.When you run this code and access /all_users
, you'll get an HTTP 200 status code (which means success) along with a JSON response containing all users from the mock database:
JSON1[ 2 {"id": 1, "username": "cosmo"}, 3 {"id": 2, "username": "jake"}, 4 {"id": 3, "username": "emma"} 5]
Next, we will create an endpoint to retrieve a single user by their ID using a path parameter. Here's how we do it:
Python1@app.route('/users/<int:user_id>', methods=['GET']) 2def get_user(user_id): 3 # Loop through the database to find the user with the given ID 4 for user in database: 5 if user['id'] == user_id: 6 # Return the found user as JSON 7 return jsonify(user) 8 # Return an error message if the user is not found 9 return jsonify(error="User not found"), 404
Explanation:
/users
route includes a path parameter /<int:user_id>
to capture the user's ID from the URL.int:
part ensures that the parameter is treated as an integer. If an incompatible data type is provided, Flask will return a 404 error.get_user
function takes user_id
as an argument and searches the database for a user with that ID.For example, if you access /users/2
, you will get an HTTP 200 status code along with the following JSON response:
JSON1{ 2 "id": 2, 3 "username": "jake" 4}
It's important to handle cases where a user is not found in the database. In the previous section, we included error handling within the get_user
function. Here's the relevant code:
Python1# Return an error message if the user is not found 2return jsonify(error="User not found"), 404
This part of the code is executed if the user with the specified ID is not found in the database.
jsonify(error="User not found")
creates a JSON response with an error message.404
part sets the HTTP status code to 404, which means "Not Found".In Flask, you can return a response and set its status code by separating them with a comma. This ensures clients know the resource was not found and receive a clear error message.
When a client attempts to access a user ID that does not exist, such as /users/99
, the server will respond with an HTTP 404 status code, indicating that the requested resource was not found. The JSON response will contain a descriptive error message:
JSON1{ 2 "error": "User not found" 3}
This response helps clients understand that the specified user ID does not exist in the database and guides them to correct their request accordingly.
In this lesson, we unlocked the power of GET requests in Flask, enabling us to effortlessly retrieve data from a mock database. You learned how to:
It's now time to put your newfound knowledge to the test! Dive into the practice exercises where you'll will reinforce your understanding and prepare you for more advanced techniques in future lessons.
Get ready to flex your coding muscles and have some fun exploring the power of Flask!