Return HTTP status code 201 in flask

前端 未结 9 1092
忘掉有多难
忘掉有多难 2020-12-23 19:58

We\'re using Flask for one of our API\'s and I was just wondering if anyone knew how to return a HTTP response 201?

For errors such as 404 we can call:



        
相关标签:
9条回答
  • 2020-12-23 20:32

    You can do

    result = {'a': 'b'}
    return jsonify(result), 201
    

    if you want to return a JSON data in the response along with the error code You can read about responses here and here for make_response API details

    0 讨论(0)
  • 2020-12-23 20:35

    You can use Response to return any http status code.

    > from flask import Response
    > return Response("{'a':'b'}", status=201, mimetype='application/json')
    
    0 讨论(0)
  • 2020-12-23 20:37

    Dependent on how the API is created, normally with a 201 (created) you would return the resource which was created. For example if it was creating a user account you would do something like:

    return {"data": {"username": "test","id":"fdsf345"}}, 201
    

    Note the postfixed number is the status code returned.

    Alternatively, you may want to send a message to the client such as:

    return {"msg": "Created Successfully"}, 201
    
    0 讨论(0)
  • 2020-12-23 20:40

    So, if you are using flask_restful Package for API's returning 201 would becomes like

    def bla(*args, **kwargs):
        ...
        return data, 201
    
    

    where data should be any hashable/ JsonSerialiable value, like dict, string.

    0 讨论(0)
  • 2020-12-23 20:41

    As lacks suggested send status code in return statement and if you are storing it in some variable like

    notfound = 404
    invalid = 403
    ok = 200
    

    and using

    return xyz, notfound
    

    than time make sure its type is int not str. as I faced this small issue also here is list of status code followed globally http://www.w3.org/Protocols/HTTP/HTRESP.html

    Hope it helps.

    0 讨论(0)
  • 2020-12-23 20:46

    you can also use flask_api for sending response

    from flask_api import status
    
    @app.route('/your-api/')
    def empty_view(self):
        content = {'your content here'}
        return content, status.HTTP_201_CREATED
    

    you can find reference here http://www.flaskapi.org/api-guide/status-codes/

    0 讨论(0)
提交回复
热议问题