Flask REST API Development Guidelines
Best Practices for Flask with Pydantic & Swagger (FastAPI Migration Ready)
Project Structure
│ ├── models/ # Pydantic models
│ │ ├── __init__.py
│ │ ├── user.py
│ │ ├── dataource.py
│ │ ├── smartdiff.py
│ │ ├── workflow.py
│ │ └── common.py # Shared/base models
Naming Conventions
General Rules
- Files: Use
snake_case(e.g.,user_service.py,product_routes.py) - Classes: Use
PascalCase(e.g.,UserService,ProductModel) - Functions/Methods: Use
snake_case(e.g.,get_user_by_id,create_product) - Variables: Use
snake_case(e.g.,user_id,total_count) - Constants: Use
UPPER_SNAKE_CASE(e.g.,MAX_PAGE_SIZE,DEFAULT_TIMEOUT)
Pydantic Models
# Request models: <Entity><Action>Request
class UserCreateRequest(BaseModel):
pass
class UserUpdateRequest(BaseModel):
pass
# Response models: <Entity><Action>Response or <Entity>Schema
class UserResponse(BaseModel):
pass
class UserListResponse(BaseModel):
pass
# Base models: <Entity>Base
class UserBase(BaseModel):
pass
Route/Endpoint Naming
# Blueprint names: <entity>_bp or <entity>_routes
user_bp = Blueprint('users', __name__, url_prefix='/api/v1/users')
# Endpoint function names: <action>_<entity>
@user_bp.route('/', methods=['GET'])
def get_users():
pass
@user_bp.route('/<int:user_id>', methods=['GET'])
def get_user(user_id):
pass
@user_bp.route('/', methods=['POST'])
def create_user():
pass
Pydantic Models
Base Configuration
from pydantic import BaseModel, ConfigDict, Field
from typing import Optional
from datetime import datetime
class BaseSchema(BaseModel):
"""Base schema with common configuration"""
model_config = ConfigDict(
from_attributes=True, # For ORM compatibility
populate_by_name=True,
arbitrary_types_allowed=True
)
class TimestampMixin(BaseModel):
"""Mixin for timestamp fields"""
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: Optional[datetime] = None
Request Models
from pydantic import EmailStr, field_validator
class UserCreateRequest(BaseSchema):
"""Request model for creating a user"""
username: str = Field(..., min_length=3, max_length=50)
email: EmailStr
password: str = Field(..., min_length=8)
full_name: Optional[str] = Field(None, max_length=100)
@field_validator('username')
@classmethod
def validate_username(cls, v):
if not v.isalnum():
raise ValueError('Username must be alphanumeric')
return v.lower()
class UserUpdateRequest(BaseSchema):
"""Request model for updating a user"""
email: Optional[EmailStr] = None
full_name: Optional[str] = Field(None, max_length=100)
Response Models
class UserResponse(BaseSchema, TimestampMixin):
"""Response model for user data"""
id: int
username: str
email: EmailStr
full_name: Optional[str]
is_active: bool = True
# Exclude sensitive fields
model_config = ConfigDict(
from_attributes=True,
exclude={'password', 'password_hash'}
)
class UserListResponse(BaseSchema):
"""Response model for paginated user list"""
total: int
page: int
page_size: int
users: list[UserResponse]
Common Response Patterns
from typing import Generic, TypeVar
from pydantic import BaseModel
T = TypeVar('T')
class ApiResponse(BaseModel, Generic[T]):
"""Standard API response wrapper"""
success: bool
message: str
data: Optional[T] = None
class PaginationParams(BaseModel):
"""Standard pagination parameters"""
page: int = Field(1, ge=1)
page_size: int = Field(20, ge=1, le=100)
sort_by: Optional[str] = None
order: str = Field('asc', pattern='^(asc|desc)$')
API Endpoints
RESTful URL Structure
GET /api/v1/users # List all users
GET /api/v1/users/{id} # Get specific user
POST /api/v1/users # Create new user
PUT /api/v1/users/{id} # Update user (full)
PATCH /api/v1/users/{id} # Update user (partial)
DELETE /api/v1/users/{id} # Delete user
# Nested resources
GET /api/v1/users/{id}/posts # Get user's posts
POST /api/v1/users/{id}/posts # Create post for user
# Actions/Operations
POST /api/v1/users/{id}/activate # Activate user
POST /api/v1/users/{id}/reset-password # Reset password
Flask Route Implementation
from flask import Blueprint, request, jsonify
from pydantic import ValidationError
from app.models.user import UserCreateRequest, UserResponse, UserListResponse
from app.services.user_service import UserService
user_bp = Blueprint('users', __name__, url_prefix='/api/v1/users')
user_service = UserService()
@user_bp.route('/', methods=['GET'])
def get_users():
"""Get paginated list of users"""
try:
# Parse query params with Pydantic
params = PaginationParams(**request.args.to_dict())
result = user_service.get_users(
page=params.page,
page_size=params.page_size
)
response = UserListResponse(**result)
return jsonify(response.model_dump()), 200
except ValidationError as e:
return jsonify({'error': e.errors()}), 422
@user_bp.route('/<int:user_id>', methods=['GET'])
def get_user(user_id):
"""Get user by ID"""
user = user_service.get_user_by_id(user_id)
if not user:
return jsonify({'error': 'User not found'}), 404
response = UserResponse.model_validate(user)
return jsonify(response.model_dump()), 200
@user_bp.route('/', methods=['POST'])
def create_user():
"""Create new user"""
try:
# Validate request with Pydantic
user_data = UserCreateRequest(**request.get_json())
user = user_service.create_user(user_data)
response = UserResponse.model_validate(user)
return jsonify(response.model_dump()), 201
except ValidationError as e:
return jsonify({'error': e.errors()}), 422
Response Patterns
Standard Response Format
# Success Response
{
"success": true,
"message": "User created successfully",
"data": {
"id": 1,
"username": "johndoe",
"email": "john@example.com"
}
}
# Error Response
{
"success": false,
"message": "Validation failed",
"errors": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
# Paginated Response
{
"success": true,
"data": {
"total": 100,
"page": 1,
"page_size": 20,
"items": [...]
}
}
HTTP Status Codes
- 200 OK: Successful GET, PUT, PATCH
- 201 Created: Successful POST
- 204 No Content: Successful DELETE
- 400 Bad Request: Invalid request format
- 401 Unauthorized: Authentication required
- 403 Forbidden: Insufficient permissions
- 404 Not Found: Resource not found
- 422 Unprocessable Entity: Validation error
- 500 Internal Server Error: Server error
Error Handling
Custom Exceptions
# app/utils/exceptions.py
class ApiException(Exception):
"""Base API exception"""
def __init__(self, message: str, status_code: int = 400):
self.message = message
self.status_code = status_code
super().__init__(self.message)
class NotFoundError(ApiException):
def __init__(self, message: str = "Resource not found"):
super().__init__(message, 404)
class ValidationError(ApiException):
def __init__(self, message: str = "Validation failed"):
super().__init__(message, 422)
class UnauthorizedError(ApiException):
def __init__(self, message: str = "Unauthorized"):
super().__init__(message, 401)
Error Handler
# app/main.py
from flask import Flask, jsonify
from pydantic import ValidationError
from app.utils.exceptions import ApiException
def create_app():
app = Flask(__name__)
@app.errorhandler(ApiException)
def handle_api_exception(error):
return jsonify({
'success': False,
'message': error.message
}), error.status_code
@app.errorhandler(ValidationError)
def handle_validation_error(error):
return jsonify({
'success': False,
'message': 'Validation failed',
'errors': error.errors()
}), 422
@app.errorhandler(404)
def handle_not_found(error):
return jsonify({
'success': False,
'message': 'Resource not found'
}), 404
return app
3. API Versioning
# Option 1: URL versioning (Recommended)
/api/v1/users
/api/v2/users
# Option 2: Header versioning
@user_bp.before_request
def check_api_version():
version = request.headers.get('API-Version', 'v1')
if version not in ['v1', 'v2']:
abort(400, 'Invalid API version')
Steps:
- Entities:
- Users
- DataSources
- Sub Entity --> Objects
- Workflows
- Sub Entity --> Steps
- Alerts
- Configurations
- Resources
- Products
- Smartdiff
- Workload
- MetadataSync
- DQ
- AI Studio
- Search
Phase1.0
- 1- Pick a module
- Yogesh --> Users(P1)
- Yashwant -->DataSources(P1), Smartdiff(P2)
- Teja --> DQ, Alerts, S2P(Later)
- Subu & Amarnath --> TimeLine, Workflows(P1), Workload Analyzer
- Lokesh -->DataSources(P1)
- Kokila -->DataSources(P1), Search, Config
- Anil --> Workflows(P1), AI Studio
- Rana --> ALL UI changes, Workflows(P1), Users(P1),DataSources(P1)
- 2.0 Make changes in url using kebab-case & Verb-Noun framework for exampple (/v1/reset-password)
- fwk:
/api/v1/<resource>[/<sub-resource>[/<id>]] - Review PRs and Merge into common branch for UI and other
- Phase1.1
- 3.0 Add Pydyntic model for request and response
- 3.1 Make changes in *_api.py with correct http method
- 3.2 Adding guuid if not present for entity.
- 4-Add visibilty(internal/public) flag in swagger json
- 5-Make changes in client Side
- 6- Update testcases(unit & e2e)
- 7-Verify from UI and add testcases for it using cypress or playwrite
Module
- /auth/* → for login/register/token/password
- /users/* → for CRUD on user objects
- /user-profile & /user-preferences → for personal details/settings
- /roles & /permissions → for RBAC control
Phase2
- Add exception decorator for each api
- Update testcases(unit & e2e)
- Verify from UI and add testcases for it using cypress or playwrite