from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError, HTTPException from starlette.status import HTTP_400_BAD_REQUEST from App.routers.stocks.routes import router as stocks_router from App.routers.utt.routes import router as utt_router from App.routers.bonds.routes import router as bonds_router from App.routers.tasks.routes import router as tasks_router from App.routers.users.routes import router as users_router from App.routers.portfolio.routes import router as portfolio_router from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware from App.schemas import ResponseModel, AppException from db import init_db, close_db, clear_db app = FastAPI(title="Uwekezaji API", description="Stock Market Data API") @app.exception_handler(AppException) async def custom_http_exception_handler(request: Request, exc: AppException): return JSONResponse( status_code=exc.status_code, content=ResponseModel(success=False, message=exc.detail, data=exc.data).dict(), ) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=HTTP_400_BAD_REQUEST, content=ResponseModel( success=False, message="Validation error", data={"errors": exc.errors()} ).dict(), ) # # Configure CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=False, allow_methods=["*"], allow_headers=["*"], ) # Include routers app.include_router(stocks_router) app.include_router(utt_router) app.include_router(bonds_router) app.include_router(tasks_router) app.include_router(users_router) app.include_router(portfolio_router) app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*") # Database initialization and cleanup @app.on_event("startup") async def startup_event(): # Clear and reinitialize database on startup await init_db() @app.on_event("shutdown") async def shutdown_event(): # await clear_db() await close_db() # Root endpoint @app.get("/") async def root(): return {"message": "Welcome to Uwekezaji API"}