1

I am using flask-restful api. When I change debug=True to debug=False I don't receive data as a json format. This is the example code:

from flask import Flask, jsonify, Response
from flask_restful import Resource, Api
import json

app = Flask(__name__)

# Create the API
api = Api(app)

@app.route('/')
def index():
    return "HELLO WORLD"


class tests(Resource):

    def get(self):
        #return json.dumps({"A":1, "B":2}, sort_keys=False, indent=4)
        return jsonify({"A":1, "B":2}) 

api.add_resource(tests, '/<string:identifier>')

if __name__ == '__main__':
    app.run(debug=False)

with json.dumps(dictionary) it returns:

"{\n \"A\": 1,\n \"B\": 2\n}"

but I expect:

{
  "A": 1,
  "B": 2
 }
Dinko Pehar
  • 5,454
  • 4
  • 23
  • 57
J2015
  • 320
  • 4
  • 24

1 Answers1

0

The defined resource is the cause of your issue since it requires that you pass "self" to the functions inside. Defining the class as an object instead of a resource will circumvent this while still allowing you to pass arguments to the function, such as id, as seen in get_tests_id().

from flask import Flask, json
from flask_restful import Api

app = Flask(__name__)

# Create the API
api = Api(app)


@app.route('/')
def index():
    return "HELLO WORLD"


class Tests(object):

    # function to get all tests
    @app.route('/tests', methods=["GET"])
    def get_tests():
        data = {"A": 1, "B": 2}
        return json.dumps(data, sort_keys=False, indent=4), 200

    # function to get tests for the specified id("A" or "B" in this case) 
    @app.route('/tests/<id>', methods=["GET"])
    def get_tests_id(id):
        data = {"A": 1, "B": 2}
        return json.dumps({id: data.get(id)}, sort_keys=False, indent=4), 200


if __name__ == '__main__':
    app.run(debug=False)

Assuming you are running the API on port 5000 and testing it from the host, the following URLs can be used to access your data from a web browser:

'localhost:5000/tests' - URL to get all tests

'localhost:5000/tests/A' - URL to get tests with id="A"

'localhost:5000/tests/B' - URL to get tests with id="B"

Cheese
  • 118
  • 10