3

Everything runs fine, API(flask) returns the data nicely. However, when I try to customise the response code, I can't do it.
Following are the two ways, I tried:

from flask import make_response
dictionary = {1:'a', 2:'b'}
resp = make_response(dictionary,1001)
return resp

#In developer tools, I could see the data, but status-code is 200

.

from flask import Response
dictionary = {1:'a', 2:'b'}
resp = Response(dictionary, status = 1001)
return resp

#Here again, I see the data, but the status code is 200

How do I set the status code to be something else?

Mr.President
  • 163
  • 1
  • 9
  • 1
    Try: ```return Response("{1:'a', 2:'b'}", status=201, mimetype='application/json')``` .Btw, `1001` is not a valid HTTP status code – T.M Luan Jan 02 '20 at 08:47
  • heres a reference for HTTP status codes https://en.wikipedia.org/wiki/List_of_HTTP_status_codes. – marxmacher Jan 02 '20 at 08:50
  • @T.MLuan Thaks for replying, Sir. If I want to set custom status code,how could I do that? Like if I want to trigger different actions based on return type. – Mr.President Jan 02 '20 at 11:01

1 Answers1

6

This should answer your question : https://flask.palletsprojects.com/en/1.1.x/quickstart/#about-responses

Example from docs:

@app.errorhandler(404)
def not_found(error):
    resp = make_response(render_template('error.html'), 404)
    resp.headers['X-Something'] = 'A value'
    return resp
marxmacher
  • 591
  • 3
  • 20
  • i changed the answer to be more accurate. Initial answer had a reference to flask api which is different from your regular flask. Leaving the link to flask api here if someone needed it : https://www.flaskapi.org/api-guide/status-codes/ – marxmacher Jan 02 '20 at 08:44
  • you can add the what changes you have done in the answer itself, no need to make a comment :) – sahasrara62 Jan 02 '20 at 08:51
  • i did, just wanted to make sure no one gets confused :) – marxmacher Jan 02 '20 at 08:56
  • Thanks for replying, Sirs. I could return `204` for no content, but successful request. If I want to return my own status code, is it possible to do that? Just curious about this. – Mr.President Jan 02 '20 at 11:04
  • https://stackoverflow.com/questions/7996569/can-we-create-custom-http-status-codes – marxmacher Jan 02 '20 at 11:05
  • in short yes. they just have to follow same logic. – marxmacher Jan 02 '20 at 11:06
  • Thanks a lot, everyone.Thank you marxmacher, you helped me a lot. Finally, I am able to set the status codes. I used `abort` from `flask-restful`. – Mr.President Jan 02 '20 at 12:29