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
CodePudding user response:
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
CodePudding user response:
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)
CodePudding user response:
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
CodePudding user response:
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.
201
or 400
are the status codes and you can do this for the other status codes.