In this tutorial, our goal is to guide you through the process of building a RESTful API using Flask-RESTful. Flask-RESTful is an extension for Flask that simplifies the process of building APIs and reduces the amount of boilerplate code you need to write.
By the end of this tutorial, you will learn:
- How to set up a Flask project
- How to install and use Flask-RESTful
- How to define resources and routes
- How to handle requests and responses
Prerequisites: Basic knowledge of Python and understanding of web development concepts.
Start by setting up a new Flask project. Install Flask and Flask-RESTful using pip:
pip install flask flask-restful
Create a new file app.py
and import Flask and Api from flask_restful.
from flask import Flask
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
The Api
object will be our entry point for adding resources.
A resource can be defined as a class that inherits from Resource. Each HTTP method is mapped to a method in this class.
from flask_restful import Resource
class HelloWorld(Resource):
def get(self):
return {'message': 'Hello, World!'}
Now, link the resource with a URL so that it can be accessed.
api.add_resource(HelloWorld, '/')
Finally, add the code to run the application.
if __name__ == '__main__':
app.run(debug=True)
In the code below, we define a resource HelloWorld with a get
method that returns a simple message.
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
# Return a simple message
return {'message': 'Hello, World!'}
# Add the HelloWorld resource and associate it with the '/' URL
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True)
When you run this code and navigate to http://localhost:5000/
, you should see the message "Hello, World!".
You can also handle URL parameters as shown below. The get
method takes an argument todo_id
and uses it to return a specific todo item.
class TodoResource(Resource):
def get(self, todo_id):
return {todo_id: todos[todo_id]}
api.add_resource(TodoResource, '/todos/<int:todo_id>')
In this case, if you navigate to http://localhost:5000/todos/1
, you would get the todo item with ID 1.
In this tutorial, we have covered:
- Setting up a Flask project and installing Flask-RESTful
- Creating a Flask application and an API
- Defining and adding resources to the API
- Handling requests and responses
Continue learning by exploring more about how to handle different HTTP methods like POST, PUT, DELETE, and how to use request parsing for more complex data handling.
TodoList
that returns a list of all todos. Map it to the URL '/todos'.post
method to TodoList
that allows adding a new todo item.delete
method to TodoResource
that allows deleting a specific todo item.For further practice, consider learning about how to connect your API to a database, or how to secure your API using authentication and authorization.