0

I am trying to develop an api with Flask. I want my api to return json file. However, the value I return is a tuple because it contains the json file and the status code. Do I need to show the Status Code in a different way? Thank you for your help.

def create(name, age):
    return {"name": name,"age": age},{"Status Code": 200}



@app.route("/createaccount/", methods=["POST"])
def CreateAcc():

    account_info = json.loads(request.data)    
    data_set = create(name="Jack", age=23)
    json_dump = json.dumps(data_set)

return json_dump
Selman
  • 274
  • 2
  • 4
  • 17

4 Answers4

1

You can do this:

@app.route("/createaccount/", methods=["POST"])
def CreateAcc():
    if request.method == 'POST':
        try:
            account_info = json.loads(request.data)    
            data_set = create(name="Jack", age=23)
            json_dump = json.dumps(data_set)

            return jsonify({"status": "success",
                        "message": "Successfully created account",
                        "data": json_dump}), 200
        except Exception as error: 
            return jsonify({"status": "error",
                           "message": "bad request"}), 400

so you can return success and failed error status code.

200 or 400 are the status codes and you can do this for the other status codes.

Olasimbo
  • 965
  • 6
  • 14
  • In my original project, there are about 100 validations. According to the error, different status codes are coming. If I only returned the status code when the operation was successful, I could use this. Any idea what I can do about it? – Selman May 17 '22 at 12:05
  • 1
    Check https://flask.palletsprojects.com/en/2.1.x/api/#flask.abort – Benoît Zu May 17 '22 at 12:10
  • 1
    @Selman I edited my response to handle the cases where you want to have both success and failed error status code. – Olasimbo May 17 '22 at 12:15
1

You can return the status code directly in the http response. If you need to put the result code in the http reponse body, you can do as follow:

from flask import Flask
import json

app = Flask(__name__)


def create(name, age):
    return {"name": name,"age": age},{"Status Code": 200}


@app.route('/createaccount/', methods=['POST'])
def get_request():
    return json.dumps(create(name="Jack", age=23)), 201


if __name__ == "__main__":
    app.run(port=5000, debug=True)
Matteo Pasini
  • 1,787
  • 3
  • 13
  • 26
1

The return statement automatically jsonifies a dictionary in the first return value, hence you can do below

def create(name, age):
    return {"name": name, "age": age} 

@app.route("/createaccount/", methods=["POST"])
def CreateAcc():
    data = create(name="Jack", age=23)
    return data, 200
Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
1

There is the jsonify function for that in Flask.

Serialize data to JSON and wrap it in a Response with the application/json mimetype.

Example from documentation:

from flask import jsonify

@app.route("/users/me")
def get_current_user():
    return jsonify(
        username=g.user.username,
        email=g.user.email,
        id=g.user.id,
    )

Source: https://flask.palletsprojects.com/en/2.1.x/api/#flask.json.jsonify

And if you want to specify the status code, example:

@app.route("/users/me")
def get_current_user():
    return jsonify(
        username=g.user.username,
        email=g.user.email,
        id=g.user.id,
    ), 200
Benoît Zu
  • 1,217
  • 12
  • 22
  • Hello, Thank you for your answer. There is something that confuses me. I'm doing a lot of validation and their response codes are not the same. --404,400,401-- I made these validations inside the create function and returned the appropriate status codes. For example, if no name is entered, a warning message and status code: 400 bad request are returned. It returns 200 if everything is correct. I want to call the create function within the CreateAcc function and get the status code from the value returned from the create function and respond to it. – Selman May 17 '22 at 12:16
  • I thought I did this, but the result returned was a tuple and my plan was broken.I think in the solution method you showed me, only one status code can be returned. I may have misunderstood, sorry, I'm new to api business. I would be glad if you could explain. – Selman May 17 '22 at 12:16
  • 1
    If you only want to stop and send a specific status code, use `abort` function, it will raise an `HTTPException`. So no need to use return, you can use `abort(404)` directly inside your create function. – Benoît Zu May 17 '22 at 12:22