3

I'm very new in using FastAPI and postman. When I am sending a POST request with a body (input data), I'm getting Success code 200 and also intended Response.

Now, I want to tweak my input data to make my code fail intentionally. This is also happening. But the status code is coming to be 500 and Internal Server Error is being displayed in response.

I want to manually give a status code in each case of failure and also some related output in Response. How to achieve this goal?

mufassir
  • 406
  • 5
  • 16

2 Answers2

2

Detailed Solution can be found out on https://fastapi.tiangolo.com/tutorial/handling-errors/.

A quick solution is to just add following line in the function where you are returning output using try and except statements:

try:
    output
except Exception:
    raise HTTPException(status_code=406, detail="New Error Found")
mufassir
  • 406
  • 5
  • 16
2

If you want to JSON response format, this might be helpful

from fastapi.responses import JSONResponse
from fastapi import status

def my_function():
    return JSONResponse(
                status_code=500,
                content={
                         "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                         "message": "Internal Server Error"}
            )
Mamun
  • 456
  • 7
  • 9
  • I needed to give manual status codes. Is it possible here? – mufassir Oct 25 '21 at 07:36
  • Yeah, possible. Change the status code as you want. See this list https://github.com/encode/starlette/blob/master/starlette/status.py . If not found any relevant, Just put manual code. – Mamun Oct 25 '21 at 08:18
  • Okay.. Could you show an instance with status code 406 and detail as "Solver TimeOut"? – mufassir Oct 25 '21 at 11:03
  • 1
    Just change the status code. JSONResponse( status_code=406, content={ "code": 406 "message": "Solver TimeOut"} ) – Mamun Oct 26 '21 at 05:51