Search code examples
pythonpython-3.xapiflaskflask-restful

How to return JSON objects (List of Dictionaries) in Flask API


Newbie here and stuck on returning some objects from JSON to my Flask API.

I have a list of dictionaries called data, you'll see in my code below. I need to check if the status_id is in the data. If it is, I have to display that user's name. How would I access a dictionary from a list? Or is my json not valid? I did use a linter to check and it passed the JSON test. I'm getting error: string indices must be integers. Which leads me to believe that since it's a list I'll need integers for the indexes.

Any help in the right direction would be great.

Here's my code:

@app.route("/status/<status_id>", methods=['GET'])
def get_status(status_id):
    data = [{
                "id": 5,
                "name": "Meghan"
            },
            {
                "id": 6,
                "name": "Julia"
            }
        ]

    data_dump = json.dumps(data, indent=4)

    if status_id in data_dump:
        #find that status id and name and return it
        return data_dump[status_id]['name']
    else:
        return "Not Found in Dictionary"

Solution

  • See below. A simplified version of the get_status function.

    Pay attention to the HTTP status code (200 Vs. 404)

    @app.route("/status/<status_id>", methods=['GET'])
    def get_status(status_id):
        data = [{
            "id": 5,
            "name": "Meghan"
        },
            {
                "id": 6,
                "name": "Julia"
            }
        ]
        name = None
        for entry in data:
            if entry['id'] == status_id:
                name = entry['name']
                break
        if name is not None:
            print('The name for status_id {} is {}'.format(status_id,name))
            return name, 200
            # or, if you want to return both use Flask jsonify and send a dict
            # see http://flask.pocoo.org/docs/1.0/api/#flask.json.jsonify
        else:
            print('Can not find a name for status id {}'.format(status_id))
            return "Not Found in Dictionary", 404