-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
117 lines (94 loc) · 3.33 KB
/
main.py
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
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError, FastAPIError
import uvicorn
from sqlalchemy.exc import InvalidRequestError
from starlette.exceptions import HTTPException as StarletteHttpException
from api.v1.utils.database import Base, engine
from api.v1.responses.success_responses import success_response
from api.v1.responses.error_responses import ValidationErrorResponse, ErrorResponse
from api.v1.routes import version_one
load_dotenv()
# Creating database
Base.metadata.create_all(bind=engine)
# App settings for project
app = FastAPI(
title="BookVault",
summary="Library management api",
version="0.0.1",
contact={
"name": "Izzyjosh",
"email": "[email protected]",
},
license_info={
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html",
},
debug=os.environ.get("DEBUG") != "False",
redoc_url=None,
docs_url="/docs",
)
app.include_router(version_one)
# Setting up cors and middleware
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Setup error responses
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
errors = []
for error in exc.errors():
errors.append({"field": error.get("loc")[-1], "message": error.get("msg")})
response = ValidationErrorResponse(errors=errors)
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=response.model_dump()
)
@app.exception_handler(StarletteHttpException)
async def http_exception_handler(request: Request, exc: StarletteHttpException):
"""
:param request: HTTP request object
:param exc: HTTP exception
:returns JSONResponse
"""
response = ErrorResponse(status_code=exc.status_code, message=exc.detail)
return JSONResponse(status_code=exc.status_code, content=response.model_dump())
@app.exception_handler(InvalidRequestError)
async def http_exception_handler(request: Request, exc: InvalidRequestError):
"""
:param request: HTTP request object
:param exc: HTTP exception
:returns JSONResponse
"""
response = ErrorResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, message=exc._message()
)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content=response.model_dump()
)
@app.exception_handler(FastAPIError)
async def http_exception_handler(request: Request, exc: FastAPIError):
"""
:param request: HTTP request object
:param exc: HTTP exception
:returns JSONResponse
"""
response = ErrorResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, message=exc.detail
)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content=response.model_dump()
)
@app.get("/")
async def home():
return success_response(status_code=200, message="Welcome to BookVault API")
# start server
if __name__ == "__main__":
uvicorn.run(app, port=int(os.environ.get("SERVER_PORT", 5001)), reload=False)