Building RESTful APIs with Flask is a straightforward and rewarding process. Flask is a micro web framework for Python that allows you to create web applications quickly and efficiently. RESTful APIs enable different software applications to communicate with each other over the web. In this guide, we will explore three diverse and practical examples of creating RESTful APIs with Flask, suitable for developers of all levels.
Imagine you want to build a simple API for a todo list application. This API will allow users to create, read, update, and delete tasks in their todo list.
from flask import Flask, jsonify, request
app = Flask(__name__)
## Sample data
todos = [{"id": 1, "task": "Learn Flask", "done": False}]
@app.route('/todos', methods=['GET'])
def get_todos():
return jsonify(todos)
@app.route('/todos', methods=['POST'])
def add_todo():
new_todo = request.get_json()
todos.append(new_todo)
return jsonify(new_todo), 201
@app.route('/todos/<int:todo_id>', methods=['PUT'])
def update_todo(todo_id):
todo = next((todo for todo in todos if todo['id'] == todo_id), None)
if todo:
todo.update(request.get_json())
return jsonify(todo)
return jsonify({'error': 'Todo not found'}), 404
@app.route('/todos/<int:todo_id>', methods=['DELETE'])
def delete_todo(todo_id):
global todos
todos = [todo for todo in todos if todo['id'] != todo_id]
return '', 204
if __name__ == '__main__':
app.run(debug=True)
In many applications, you need to handle user authentication. This example demonstrates how to create a simple user authentication API using Flask that allows users to register and log in.
from flask import Flask, request, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
users = {}
@app.route('/register', methods=['POST'])
def register():
username = request.json['username']
password = request.json['password']
if username in users:
return jsonify({'message': 'User already exists!'}), 400
users[username] = generate_password_hash(password)
return jsonify({'message': 'User registered successfully!'}), 201
@app.route('/login', methods=['POST'])
def login():
username = request.json['username']
password = request.json['password']
if username not in users or not check_password_hash(users[username], password):
return jsonify({'message': 'Invalid credentials!'}), 401
return jsonify({'message': 'Login successful!'}), 200
if __name__ == '__main__':
app.run(debug=True)
werkzeug.security
for password hashing, ensuring that the passwords are stored securely.Suppose you’re building an API for a book inventory where users can browse books and filter them based on categories. This example showcases how to create such an API with Flask.
from flask import Flask, jsonify, request
app = Flask(__name__)
## Sample data
books = [
{"id": 1, "title": "Flask for Beginners", "category": "Programming"},
{"id": 2, "title": "Python 101", "category": "Programming"},
{"id": 3, "title": "Cooking Basics", "category": "Cooking"}
]
@app.route('/books', methods=['GET'])
def get_books():
category = request.args.get('category')
if category:
filtered_books = [book for book in books if book['category'].lower() == category.lower()]
return jsonify(filtered_books)
return jsonify(books)
if __name__ == '__main__':
app.run(debug=True)
/books?category=Programming
will return only programming books.By following these examples of creating RESTful APIs with Flask, you can start building your own web applications with ease. Remember to experiment and modify the code to fit your specific use cases!