Building REST APIs with Python Flask - Complete Guide
Building REST APIs with Python Flask
Flask is a lightweight Python web framework perfect for building APIs quickly.
Setting Up Flask
First, install Flask using pip:
pip install flask
Creating a Simple API
Here’s a basic Flask application with a REST endpoint:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api/users', methods=['GET'])
def get_users():
users = [
{'id': 1, 'name': 'Alice', 'email': 'alice@example.com'},
{'id': 2, 'name': 'Bob', 'email': 'bob@example.com'}
]
return jsonify(users)
@app.route('/api/users', methods=['POST'])
def create_user():
data = request.get_json()
new_user = {
'id': len(users) + 1,
'name': data['name'],
'email': data['email']
}
return jsonify(new_user), 201
if __name__ == '__main__':
app.run(debug=True, port=5000)
Adding Authentication
For production APIs, add JWT authentication:
from flask_jwt_extended import JWTManager, create_access_token, jwt_required
app.config['JWT_SECRET_KEY'] = 'your-secret-key'
jwt = JWTManager(app)
@app.route('/api/login', methods=['POST'])
def login():
username = request.json.get('username')
password = request.json.get('password')
# Validate credentials (simplified)
if username == 'admin' and password == 'secret':
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
return jsonify({'error': 'Invalid credentials'}), 401
@app.route('/api/protected', methods=['GET'])
@jwt_required()
def protected():
return jsonify({'message': 'This is a protected route'})
Testing with cURL
Test your API endpoints using the curl command:
# GET request
curl http://localhost:5000/api/users
# POST request
curl -X POST http://localhost:5000/api/users \
-H "Content-Type: application/json" \
-d '{"name":"Charlie","email":"charlie@example.com"}'
Database Integration
Connect Flask to PostgreSQL using SQLAlchemy:
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:pass@localhost/dbname'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def to_dict(self):
return {
'id': self.id,
'name': self.name,
'email': self.email
}
# Create tables
with app.app_context():
db.create_all()
Conclusion
Flask makes it easy to build REST APIs in Python. Use these code examples as a starting point for your next project!