api: add better response documentation
This commit is contained in:
parent
bc7e74f28d
commit
745dfaf19f
4 changed files with 97 additions and 16 deletions
26
api/src/dooris_api/exceptions.py
Normal file
26
api/src/dooris_api/exceptions.py
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
from typing import Mapping, Optional
|
||||
from fastapi import HTTPException, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.utils import is_body_allowed_for_status_code
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
|
||||
from dooris_api import models
|
||||
|
||||
|
||||
class HttpProblemException(HTTPException):
|
||||
problem: models.HttpProblemDetail
|
||||
headers: Optional[Mapping[str, str]]
|
||||
|
||||
def __init__(self, problem: models.HttpProblemDetail, headers: Optional[Mapping[str, str]] = None):
|
||||
self.problem = problem
|
||||
super().__init__(status_code=problem.status, headers=headers)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return str(self.problem)
|
||||
|
||||
|
||||
async def problem_exception_handler(request: Request, exc: HttpProblemException) -> Response:
|
||||
headers = exc.headers
|
||||
if not is_body_allowed_for_status_code(exc.problem.status):
|
||||
return Response(status_code=exc.status_code, headers=headers)
|
||||
return JSONResponse(jsonable_encoder(exc.problem), status_code=exc.status_code, headers=exc.headers)
|
||||
Loading…
Add table
Add a link
Reference in a new issue