Lara M.
Lara M.

Reputation: 855

Flask read and navigate JSON

I need to parse an API with film ids and titles, getting specific elements with Flask, but it always gives me errors:

app = flask.Flask(__name__)
app.config["DEBUG"] = True


@app.route('/filmId/<filmid>', methods=['GET'])

def filmId(filmid): 
    retrieve_url = "http:www.exemple.url"
    response = requests.get(retrieve_url)
    retrieve_data = response.json()
    for d in retrieve_data:
        if filmid in d["videoId"]:
                return filmid
        else:
                return "An error occurred with id "+filmid
app.run()

This works just if i compile the url with the first id in the API, but giving the second or the third it shows the error message. What am I doing wrong?

On other hand, I don't understand how to parse a json with Flask at all: it seems that the usual way (data["key"]) gives error everytimes.

Upvotes: 0

Views: 78

Answers (1)

arshovon
arshovon

Reputation: 13651

response.json() returns a dictionary. See the details key and values of the dictionary. Check the values of retrieve_data variable.

Parse JSON data with Flask

As I do not have access to the API endpoint, I am showing an example of retrieving JSON data from an API and then manipulate it to show a particular value to user.

I want to show the country name to the user for a given country code. If there is no country name found, it will show an error message to user.

  • I will use a REST API to get the country details information for a given country code. The API endpoint contains the country code at the last path. Example endpoint: https://restcountries.eu/rest/v2/alpha/bd
  • I will search for the key that contains the country name from retrieved data.
  • If there is a country name found in retrieved data, I will show it to user. Otherwise, I will show an error message.

Code:

import requests
from flask import Flask, render_template, jsonify


app = Flask(__name__)

@app.route('/countries/<country_code>', methods=['GET'])
def get_country_information(country_code): 
    retrieve_url = "https://restcountries.eu/rest/v2/alpha/{}".format(country_code)
    response = requests.get(retrieve_url)
    data = response.json()
    found_country = False
    for key in data:
        if key == "name":
            found_country = True
            return data["name"]
    if not found_country:
        return "Country name is not found for country code {}".format(country_code)

Output:

Valid country code:

valid country code

Invalid country code:

invalid country code

Upvotes: 1

Related Questions