A RESTful API is an API that follows the principles of REST. It uses standard HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources. In the context of a ToDo app, the resources are the ToDo items. For example:
Flask is a micro - framework for Python. It provides a simple way to create web applications and APIs. It uses a routing mechanism to map URLs to Python functions, making it easy to define API endpoints.
JSON (JavaScript Object Notation) is a lightweight data - interchange format. RESTful APIs often use JSON to send and receive data between the client and the server. In our ToDo app, we’ll use JSON to represent ToDo items.
First, create a virtual environment and install Flask.
# Create a virtual environment
python3 -m venv todo-env
# Activate the virtual environment
source todo-env/bin/activate
# Install Flask
pip install flask
We’ll represent ToDo items as Python dictionaries. Each ToDo item will have an id
, a title
, a description
, and a completed
status.
# Store ToDo items in a list
todos = []
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/')
def index():
return "Welcome to the ToDo API!"
if __name__ == '__main__':
app.run(debug=True)
@app.route('/todos', methods=['POST'])
def create_todo():
data = request.get_json()
if not data or 'title' not in data:
return jsonify({"error": "Title is required"}), 400
new_todo = {
'id': len(todos) + 1,
'title': data['title'],
'description': data.get('description', ''),
'completed': False
}
todos.append(new_todo)
return jsonify(new_todo), 201
@app.route('/todos', methods=['GET'])
def get_todos():
return jsonify(todos)
@app.route('/todos/<int:todo_id>', methods=['GET'])
def get_todo(todo_id):
todo = next((t for t in todos if t['id'] == todo_id), None)
if todo is None:
return jsonify({"error": "ToDo not found"}), 404
return jsonify(todo)
@app.route('/todos/<int:todo_id>', methods=['PUT'])
def update_todo(todo_id):
todo = next((t for t in todos if t['id'] == todo_id), None)
if todo is None:
return jsonify({"error": "ToDo not found"}), 404
data = request.get_json()
todo['title'] = data.get('title', todo['title'])
todo['description'] = data.get('description', todo['description'])
todo['completed'] = data.get('completed', todo['completed'])
return jsonify(todo)
@app.route('/todos/<int:todo_id>', methods=['DELETE'])
def delete_todo(todo_id):
global todos
todos = [t for t in todos if t['id'] != todo_id]
return jsonify({"message": "ToDo deleted successfully"})
jsonschema
to validate JSON data.Building a RESTful ToDo app with Flask is a great way to learn about RESTful APIs and web development in Python. By understanding the core concepts, typical usage scenarios, and avoiding common pitfalls, you can create a robust and efficient ToDo app. Remember to follow best practices to ensure the security and maintainability of your application.