Building RESTful APIs in Flask
Introduction
Flask is a popular micro web framework in Python that is lightweight and easy to use for building web applications and APIs. When building RESTful APIs in Flask, you can either use Flask's built-in features or extend it with the Flask-RESTful extension, which simplifies the creation of API endpoints.
This article will guide you through building RESTful APIs with Flask, compare Flask-RESTful with Flask itself, and show how to create and manage API endpoints.
Step 1: Setting Up Flask
First, you need to install Flask if you haven't already:
pip install flask
Create a basic Flask application:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Welcome to the Flask API!'
if __name__ == '__main__':
app.run(debug=True)
Step 2: Flask-RESTful vs Flask
Flask itself can be used to build APIs, but when you need to create more complex APIs with several endpoints, Flask-RESTful can help you structure the application better. Here's a comparison between Flask and Flask-RESTful:
Flask
Flask allows you to build APIs by defining routes with Flask's @app.route() decorator. You handle HTTP methods (GET, POST, PUT, DELETE, etc.) by defining the corresponding methods in the view function.
Example of a simple API using Flask:
from flask import Flask, jsonify
app = Flask(__name__)
# Sample data
tasks = [
{'id': 1, 'title': 'Buy groceries', 'done': False},
{'id': 2, 'title': 'Clean house', 'done': False}
]
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
if __name__ == '__main__':
app.run(debug=True)
This example creates a simple API that returns a list of tasks in JSON format.
Flask-RESTful
Flask-RESTful is an extension for Flask that provides simple tools for building REST APIs. It organizes resources and requests better and offers additional features like automatic JSON formatting and validation.
Example of a simple API using Flask-RESTful:
from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
# Sample data
tasks = [
{'id': 1, 'title': 'Buy groceries', 'done': False},
{'id': 2, 'title': 'Clean house', 'done': False}
]
class TaskList(Resource):
def get(self):
return {'tasks': tasks}
api.add_resource(TaskList, '/tasks')
if __name__ == '__main__':
app.run(debug=True)
Flask-RESTful simplifies creating API endpoints by defining resources as classes. The TaskList class defines the GET method, and the endpoint is added using api.add_resource().
Step 3: Creating and Managing API Endpoints
API endpoints are the entry points for communication between the client and the server. In this section, we will create several endpoints in Flask and Flask-RESTful and manage data via HTTP methods.
Flask Example with Multiple Endpoints
In this example, we will create a CRUD (Create, Read, Update, Delete) API for managing tasks:
from flask import Flask, jsonify, request
app = Flask(__name__)
tasks = [
{'id': 1, 'title': 'Buy groceries', 'done': False},
{'id': 2, 'title': 'Clean house', 'done': False}
]
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/tasks', methods=['POST'])
def create_task():
new_task = request.get_json()
tasks.append(new_task)
return jsonify(new_task), 201
@app.route('/tasks/', methods=['PUT'])
def update_task(task_id):
task = next((t for t in tasks if t['id'] == task_id), None)
if task is None:
return jsonify({'message': 'Task not found'}), 404
task_data = request.get_json()
task.update(task_data)
return jsonify(task)
@app.route('/tasks/', methods=['DELETE'])
def delete_task(task_id):
task = next((t for t in tasks if t['id'] == task_id), None)
if task is None:
return jsonify({'message': 'Task not found'}), 404
tasks.remove(task)
return jsonify({'message': 'Task deleted'}), 200
if __name__ == '__main__':
app.run(debug=True)
This example creates a simple CRUD API with four endpoints:
GET /tasks: Retrieves the list of tasks.POST /tasks: Creates a new task.PUT /tasks/<task_id>: Updates an existing task.DELETE /tasks/<task_id>: Deletes a task.
Flask-RESTful Example with Multiple Endpoints
In Flask-RESTful, you can create similar endpoints with fewer lines of code:
from flask import Flask, request
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
tasks = [
{'id': 1, 'title': 'Buy groceries', 'done': False},
{'id': 2, 'title': 'Clean house', 'done': False}
]
class TaskList(Resource):
def get(self):
return {'tasks': tasks}
def post(self):
new_task = request.get_json()
tasks.append(new_task)
return new_task, 201
class Task(Resource):
def get(self, task_id):
task = next((t for t in tasks if t['id'] == task_id), None)
if task is None:
return {'message': 'Task not found'}, 404
return task
def put(self, task_id):
task = next((t for t in tasks if t['id'] == task_id), None)
if task is None:
return {'message': 'Task not found'}, 404
task_data = request.get_json()
task.update(task_data)
return task
def delete(self, task_id):
task = next((t for t in tasks if t['id'] == task_id), None)
if task is None:
return {'message': 'Task not found'}, 404
tasks.remove(task)
return {'message': 'Task deleted'}, 200
api.add_resource(TaskList, '/tasks')
api.add_resource(Task, '/tasks/')
if __name__ == '__main__':
app.run(debug=True)
Flask-RESTful uses the Resource class to define the CRUD methods for each resource. The TaskList and Task classes define the GET, POST, PUT, and DELETE methods for managing tasks.
Step 4: Conclusion
In this article, we compared Flask and Flask-RESTful for building RESTful APIs, created several API endpoints for managing tasks, and showed how Flask-RESTful simplifies the process. Flask-RESTful is especially useful for larger applications with many API endpoints as it helps structure the code better, provides useful tools for serialization, and simplifies routing.
By following these steps, you can create your own RESTful APIs in Flask with minimal effort. Whether you use Flask alone or Flask-RESTful, both are great options for building APIs depending on your project needs.