Rahul Dey
Rahul Dey

Reputation: 71

fastapi.Response() not returning customized response

api = fastapi.FastAPI()

@api.get('/api/sum')

def caculate(z):

    if z == 0 :
        return fastapi.Response(content = {'Error' : 'Z must be an integer'},
        status_code=400,
        media_type="application/json")
    return

uvicorn.run(api, host="127.0.0.50", port=8000) #server

I am trying to return the response as mentioned in the content and a 400 http response. But it is giving me a 200 response and also giving me 'null' instead of the content.

output

Upvotes: 2

Views: 5429

Answers (1)

aymenim
aymenim

Reputation: 146

You need to provide a type to the query param and use JSONResponse as the return If you want the object to be returned as json or serialize the data yourself json.dumps() if you want to use Response.

  def caculate(z: int=0):
      if z == 0 :
          return fastapi.responses.JSONResponse(content = {'Error' : 'Z must be an integer'},status_code=400)
  

Upvotes: 4

Related Questions