2
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

Rahul Dey
  • 71
  • 1
  • 9

1 Answers1

4

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)
  
aymenim
  • 136
  • 3
  • Thank you,it works. But could you please help me in understanding why using Response it doesn't return the same? https://fastapi.tiangolo.com/advanced/response-directly/ -as it says – Rahul Dey Feb 06 '21 at 13:04
  • 1
    @RahulDey, updated my answer since I forgot to mention the query param which was why you were getting the 200, Response directly responds with the data you provide therefore it needs to be a string. – aymenim Feb 06 '21 at 13:55