Retrieving Data with GET Requests
Retrieving Data with GET Requests
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.
Setting Up Flask and Mock Database
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.
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.
Defining a Route to Get All Users
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:
Explanation:
- Firstly, we define a route that responds to GET requests at the
/all_usersURL. - The
get_usersfunction is called when a GET request is made to this URL. - The
jsonify(database)function converts the user database (a list of dictionaries) into a JSON response and returns it.
Accessing GET /all_users
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:
