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?

3
  • 1
    Try: return Response("{1:'a', 2:'b'}", status=201, mimetype='application/json') .Btw, 1001 is not a valid HTTP status code Commented Jan 2, 2020 at 8:47
  • heres a reference for HTTP status codes en.wikipedia.org/wiki/List_of_HTTP_status_codes. Commented Jan 2, 2020 at 8: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. Commented Jan 2, 2020 at 11:01

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

7 Comments

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 : flaskapi.org/api-guide/status-codes
you can add the what changes you have done in the answer itself, no need to make a comment :)
i did, just wanted to make sure no one gets confused :)
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.