Reputation: 855
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
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.
https://restcountries.eu/rest/v2/alpha/bd
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:
Invalid country code:
Upvotes: 1