G2Labs Grzegorz Grzęda
Building RESTful APIs in Python using Flask
July 10, 2024
Building RESTful APIs in Python using Flask
Flask is a popular micro web framework written in Python, designed to build web applications with a simple and efficient approach. In this blog post, we will explore how to build RESTful APIs using Flask.
Setting up Flask
Before we begin, make sure you have Flask installed. You can install Flask using pip
:
|
|
Creating a Flask App
To get started, let’s create a basic Flask application. Create a new Python file, app.py
, and add the following code:
In this example, we import the Flask module and create a Flask application named app
. The @app.route('/')
decorator specifies the URL route for the index page. The hello()
function is called when someone navigates to the root URL ("/") and returns the string “Hello, World!”. Finally, we run the Flask application using app.run()
.
You can now start the Flask application by running python app.py
in your terminal. Navigate to http://localhost:5000
on your web browser, and you should see the message “Hello, World!”.
Creating an API Endpoint
Now that we have a basic Flask app up and running, let’s create an API endpoint to retrieve a list of users. Modify the app.py
file as follows:
In the modified code above, we created a list of users as a placeholder for a database. The get_users()
function now handles the route “/api/users” and returns a dictionary containing the list of users.
Restart your Flask application and navigate to http://localhost:5000/api/users
. You should see a JSON response containing the list of users:
Congratulations! You have just created your first RESTful API endpoint using Flask.
Implementing CRUD Operations
RESTful APIs typically support CRUD (Create, Read, Update, Delete) operations. Let’s implement these operations for our user API. Modify the app.py
file to include the following functions:
|
|
In the updated code above, we added four new functions to handle different HTTP methods (GET
, POST
, PUT
, DELETE
). The get_user()
function retrieves a specific user by their ID. The create_user()
function adds a new user to the list. The update_user()
function updates an existing user. The delete_user()
function removes a user from the list.
Make sure to import the request
module from Flask to handle data sent with HTTP requests.
Now you can perform CRUD operations on the user API, interacting with the data through the different endpoints. For example, to create a new user, make a POST request to http://localhost:5000/api/users
with the user data as the request body.
Conclusion
Flask provides a simple and flexible framework for building RESTful APIs in Python. In this blog post, we covered how to set up Flask, create API endpoints, and implement CRUD operations. Flask’s lightweight nature, combined with its excellent documentation, makes it an ideal choice for building APIs.
You can find the full source code for this example here.
Happy coding!