File size: 6,489 Bytes
be86a81 49c7ffd be86a81 49c7ffd be86a81 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | """
FastAPI Application Entry Point
This is the main application file for the Todo backend.
Initializes the FastAPI app with routes, CORS, exception handlers, and database lifecycle.
"""
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, status, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import ValidationError
from src.config import get_settings
from src.api.routes import todos, auth
from src.models.database import init_db, close_db
# Database lifespan manager
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Manage application lifespan events.
Handles database connection on startup and graceful shutdown.
Database connection is deferred to first actual use.
"""
# Startup: Skip database initialization to allow container to start
# Database will connect on first request
print("[INFO] Starting application (database connection deferred)")
print("[INFO] Database will connect on first API request")
yield
# Shutdown: Close database connection
await close_db()
print("[OK] Database connection closed")
# Create FastAPI application instance
app = FastAPI(
title="Todo API",
description="Backend API for Todo application with Neon PostgreSQL and JWT authentication",
version="2.0.0",
docs_url="/docs",
redoc_url="/redoc",
lifespan=lifespan, # Add database lifecycle management
)
# Get settings
settings = get_settings()
# Configure CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins_list, # List of allowed origins
allow_credentials=True, # Allow cookies/auth headers
allow_methods=["*"], # Allow all HTTP methods
allow_headers=["*"], # Allow all headers
)
# Include routers
app.include_router(todos.router)
app.include_router(auth.router)
@app.get("/", tags=["root"])
async def root():
"""
Root endpoint with basic API information.
Returns:
dict: API status and version information
"""
return {
"status": "ok",
"version": "2.0.0",
"message": "Todo API is running with Neon PostgreSQL",
"docs": "/docs"
}
@app.get("/health", tags=["health"])
async def health_check():
"""
Health check endpoint to verify API and database are running.
Returns:
dict: Status information including database connectivity
"""
return {
"status": "healthy",
"service": "todo-api",
"version": "2.0.0",
"database": "connected"
}
# ============================================================================
# Exception Handlers
# ============================================================================
@app.exception_handler(status.HTTP_401_UNAUTHORIZED)
async def unauthorized_handler(request: Request, exc: HTTPException) -> JSONResponse:
"""
Handle 401 Unauthorized errors.
Args:
request: The incoming request
exc: The HTTPException that was raised
Returns:
JSONResponse: Standardized error response with 401 status
"""
return JSONResponse(
status_code=status.HTTP_401_UNAUTHORIZED,
content={
"code": "UNAUTHORIZED",
"message": exc.detail or "Authentication required",
"details": []
}
)
@app.exception_handler(status.HTTP_403_FORBIDDEN)
async def forbidden_handler(request: Request, exc: HTTPException) -> JSONResponse:
"""
Handle 403 Forbidden errors.
Args:
request: The incoming request
exc: The HTTPException that was raised
Returns:
JSONResponse: Standardized error response with 403 status
"""
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={
"code": "FORBIDDEN",
"message": exc.detail or "Access denied",
"details": []
}
)
@app.exception_handler(status.HTTP_404_NOT_FOUND)
async def not_found_handler(request: Request, exc: HTTPException) -> JSONResponse:
"""
Handle 404 Not Found errors.
Args:
request: The incoming request
exc: The HTTPException that was raised
Returns:
JSONResponse: Standardized error response with 404 status
"""
return JSONResponse(
status_code=status.HTTP_404_NOT_FOUND,
content={
"code": "NOT_FOUND",
"message": exc.detail or "Resource not found",
"details": []
}
)
@app.exception_handler(ValidationError)
async def validation_error_handler(request: Request, exc: ValidationError) -> JSONResponse:
"""
Handle Pydantic validation errors (422 Unprocessable Entity).
Args:
request: The incoming request
exc: The ValidationError that was raised
Returns:
JSONResponse: Standardized error response with 422 status
"""
# Extract validation errors
details = []
for error in exc.errors():
details.append({
"field": ".".join(str(loc) for loc in error["loc"]),
"message": error["msg"]
})
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": details
}
)
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception) -> JSONResponse:
"""
Global exception handler for unhandled errors (500 Internal Server Error).
Args:
request: The incoming request
exc: The exception that was raised
Returns:
JSONResponse: Standardized error response with 500 status
"""
# Log the error (in production, use proper logging)
# For security, don't expose internal error details to client
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={
"code": "INTERNAL_SERVER_ERROR",
"message": "An unexpected error occurred. Please try again later.",
"details": []
}
)
if __name__ == "__main__":
import uvicorn
# Get settings for configuration
settings = get_settings()
# Run the application with uvicorn
uvicorn.run(
"main:app",
host=settings.api_host,
port=settings.api_port,
reload=settings.debug_mode,
)
|