Add response utility functions and HTTP exception handler to improve API responses
This commit is contained in:
parent
74253f0d4a
commit
affe5187fc
22
app/responses.py
Normal file
22
app/responses.py
Normal file
@ -0,0 +1,22 @@
|
||||
from fastapi import status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
def created_response(location: str, message: str = "The item was created successfully"):
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
content={"message": message},
|
||||
headers={"Location": location},
|
||||
)
|
||||
|
||||
|
||||
def paginated_response(data: list, count: int, page: int, limit: int):
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_200_OK,
|
||||
content=[item for item in data],
|
||||
headers={
|
||||
"Pagination-Count": str(count),
|
||||
"Pagination-Page": str(page),
|
||||
"Pagination-Limit": str(limit),
|
||||
},
|
||||
)
|
||||
12
main.py
12
main.py
@ -1,4 +1,5 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.routers import (
|
||||
@ -7,6 +8,7 @@ from app.routers import (
|
||||
plans_router,
|
||||
subscriptions_router,
|
||||
tenants_router,
|
||||
users_router,
|
||||
)
|
||||
|
||||
app = FastAPI(title="Profitra API", version="1.0.0")
|
||||
@ -19,6 +21,13 @@ app.add_middleware(
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
if isinstance(exc.detail, dict):
|
||||
return JSONResponse(status_code=exc.status_code, content=exc.detail)
|
||||
return JSONResponse(status_code=exc.status_code, content={"message": exc.detail})
|
||||
|
||||
|
||||
API_PREFIX = "/v1"
|
||||
|
||||
app.include_router(auth_router, prefix=API_PREFIX)
|
||||
@ -26,6 +35,7 @@ app.include_router(business_types_router, prefix=API_PREFIX)
|
||||
app.include_router(plans_router, prefix=API_PREFIX)
|
||||
app.include_router(tenants_router, prefix=API_PREFIX)
|
||||
app.include_router(subscriptions_router, prefix=API_PREFIX)
|
||||
app.include_router(users_router, prefix=API_PREFIX)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
|
||||
Loading…
Reference in New Issue
Block a user