Customise Status codes in place of 500: Internal Server Error in FastAPI using Postman
Asked Answered
R

2

5

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?

Roper answered 21/10, 2021 at 10:51 Comment(1)
Have you seen fastapi.tiangolo.com/tutorial/handling-errors?Smooth
R
5

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")
Roper answered 25/10, 2021 at 5:48 Comment(0)
A
5

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"}
            )
Amphichroic answered 25/10, 2021 at 6:36 Comment(4)
I needed to give manual status codes. Is it possible here?Roper
Yeah, possible. Change the status code as you want. See this list github.com/encode/starlette/blob/master/starlette/status.py . If not found any relevant, Just put manual code.Amphichroic
Okay.. Could you show an instance with status code 406 and detail as "Solver TimeOut"?Roper
Just change the status code. JSONResponse( status_code=406, content={ "code": 406 "message": "Solver TimeOut"} )Amphichroic

© 2022 - 2024 — McMap. All rights reserved.