Repository navigation
Expand file tree
/
Copy pathmain_api.py
More file actions
65 lines (48 loc) · 1.59 KB
/
Copy pathmain_api.py
File metadata and controls
65 lines (48 loc) · 1.59 KB
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
from contextlib import asynccontextmanager
import uvicorn
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from controllers import health_router
from core import UVICORN_LOGGING_CONFIG, logger, settings
from core.dependency_injection import create_container
from middlewares import ExceptionMiddleware, RequestMiddleware, validation_exception_handler
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Starting the application with Uvicorn, environment: %s", settings.ENVIRONMENT)
yield
await app.container.db().close_db()
app = FastAPI(
title=settings.PROJECT_NAME,
version=settings.PROJECT_VERSION,
description="My API",
docs_url="/docs",
redoc_url="/redoc",
lifespan=lifespan,
)
# Enable CORS (Modify origins as needed)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Change to specific origins in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(ExceptionMiddleware)
app.add_middleware(RequestMiddleware)
# Register exception handlers
app.add_exception_handler(RequestValidationError, validation_exception_handler)
# Include API routers
app.include_router(health_router)
# Dependency injection
app.container = create_container()
# Root endpoint
@app.get("/")
async def root():
return {"message": "Running My API", "version": settings.PROJECT_VERSION}
if __name__ == "__main__":
uvicorn.run(
"main_api:app",
reload=True,
log_config=UVICORN_LOGGING_CONFIG,
)