Build scalable REST APIs with Flask, including blueprints, JWT auth, and database integration.
# Flask RESTful API Development
Build production-ready REST APIs with Flask using Google Antigravity IDE. This comprehensive guide covers routing, authentication, validation, and deployment best practices.
## Why Flask?
Flask provides a lightweight, flexible framework for API development. Google Antigravity IDE's Gemini 3 engine suggests optimal patterns and security configurations.
## Application Factory Pattern
```python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from config import Config
db = SQLAlchemy()
migrate = Migrate()
jwt = JWTManager()
def create_app(config_class=Config):
"""Application factory pattern."""
app = Flask(__name__)
app.config.from_object(config_class)
# Initialize extensions
db.init_app(app)
migrate.init_app(app, db)
jwt.init_app(app)
CORS(app, resources={r"/api/*": {"origins": app.config["CORS_ORIGINS"]}})
# Register blueprints
from app.api import bp as api_bp
app.register_blueprint(api_bp, url_prefix="/api/v1")
# Register error handlers
register_error_handlers(app)
return app
def register_error_handlers(app):
"""Register custom error handlers."""
@app.errorhandler(400)
def bad_request(error):
return {"error": "Bad request", "message": str(error)}, 400
@app.errorhandler(404)
def not_found(error):
return {"error": "Not found", "message": str(error)}, 404
@app.errorhandler(500)
def internal_error(error):
db.session.rollback()
return {"error": "Internal server error"}, 500
```
## RESTful Resource Implementation
```python
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from marshmallow import Schema, fields, validate, ValidationError
from app.models import User
from app import db
bp = Blueprint("api", __name__)
# Validation schemas
class UserSchema(Schema):
id = fields.Int(dump_only=True)
email = fields.Email(required=True)
name = fields.Str(required=True, validate=validate.Length(min=2, max=100))
password = fields.Str(required=True, load_only=True, validate=validate.Length(min=8))
created_at = fields.DateTime(dump_only=True)
class UserUpdateSchema(Schema):
name = fields.Str(validate=validate.Length(min=2, max=100))
email = fields.Email()
user_schema = UserSchema()
users_schema = UserSchema(many=True)
user_update_schema = UserUpdateSchema()
# GET /api/v1/users
@bp.route("/users", methods=["GET"])
@jwt_required()
def get_users():
"""Get all users with pagination."""
page = request.args.get("page", 1, type=int)
per_page = min(request.args.get("per_page", 20, type=int), 100)
pagination = User.query.order_by(User.created_at.desc()).paginate(
page=page, per_page=per_page, error_out=False
)
return jsonify({
"data": users_schema.dump(pagination.items),
"pagination": {
"page": page,
"per_page": per_page,
"total": pagination.total,
"pages": pagination.pages,
"has_next": pagination.has_next,
"has_prev": pagination.has_prev,
}
})
# POST /api/v1/users
@bp.route("/users", methods=["POST"])
def create_user():
"""Create a new user."""
try:
data = user_schema.load(request.json)
except ValidationError as err:
return {"error": "Validation failed", "details": err.messages}, 400
if User.query.filter_by(email=data["email"]).first():
return {"error": "Email already registered"}, 409
user = User(
email=data["email"],
name=data["name"]
)
user.set_password(data["password"])
db.session.add(user)
db.session.commit()
return user_schema.dump(user), 201
# GET /api/v1/users/<id>
@bp.route("/users/<int:id>", methods=["GET"])
@jwt_required()
def get_user(id):
"""Get user by ID."""
user = User.query.get_or_404(id)
return user_schema.dump(user)
# PUT /api/v1/users/<id>
@bp.route("/users/<int:id>", methods=["PUT"])
@jwt_required()
def update_user(id):
"""Update user."""
user = User.query.get_or_404(id)
current_user_id = get_jwt_identity()
if user.id != current_user_id:
return {"error": "Unauthorized"}, 403
try:
data = user_update_schema.load(request.json)
except ValidationError as err:
return {"error": "Validation failed", "details": err.messages}, 400
for key, value in data.items():
setattr(user, key, value)
db.session.commit()
return user_schema.dump(user)
# DELETE /api/v1/users/<id>
@bp.route("/users/<int:id>", methods=["DELETE"])
@jwt_required()
def delete_user(id):
"""Delete user."""
user = User.query.get_or_404(id)
db.session.delete(user)
db.session.commit()
return "", 204
```
## Authentication
```python
from flask_jwt_extended import create_access_token, create_refresh_token
from datetime import timedelta
@bp.route("/auth/login", methods=["POST"])
def login():
"""Authenticate user and return tokens."""
email = request.json.get("email")
password = request.json.get("password")
if not email or not password:
return {"error": "Email and password required"}, 400
user = User.query.filter_by(email=email).first()
if not user or not user.check_password(password):
return {"error": "Invalid credentials"}, 401
access_token = create_access_token(
identity=user.id,
expires_delta=timedelta(hours=1)
)
refresh_token = create_refresh_token(identity=user.id)
return {
"access_token": access_token,
"refresh_token": refresh_token,
"user": user_schema.dump(user)
}
@bp.route("/auth/refresh", methods=["POST"])
@jwt_required(refresh=True)
def refresh():
"""Refresh access token."""
identity = get_jwt_identity()
access_token = create_access_token(identity=identity)
return {"access_token": access_token}
```
## Rate Limiting
```python
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
limiter = Limiter(
key_func=get_remote_address,
default_limits=["100 per minute", "1000 per hour"]
)
@bp.route("/auth/login", methods=["POST"])
@limiter.limit("5 per minute")
def login():
# Login logic
pass
```
## Best Practices
- Use application factory pattern
- Implement request validation with Marshmallow
- Apply JWT for stateless authentication
- Add rate limiting for protection
- Use pagination for list endpoints
- Handle errors consistently
Google Antigravity IDE provides Flask API templates and automatically suggests security improvements for your Python web applications.This Python prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their python implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Python projects, consider mentioning your framework version, coding style, and any specific libraries you're using.