Program excercise : Write a function that, using the Star Wars API (swapi.co), takes a character name, and returns a list with the names of the films that character was in.
import requests, json
def get_film_details_by_url(film_url):
resp = requests.get(film_url)
return_dict = None
if resp.status_code == 200:
return_dict = json.loads(resp.text)
return return_dict
def get_film_details_by_char_name(char_name):
swapi_base_url = "https://swapi.co/api/"
get_people_url = swapi_base_url+"people"
film_url_array = []
film_name_array = []
to_continue = True
while to_continue:
resp = requests.get(get_people_url)
if resp.status_code == 200:
resp_dict = json.loads(resp.text)
for ppl in resp_dict["results"]:
if ppl["name"].lower() == char_name.lower():
film_url_array = ppl["films"]
if not resp_dict["next"] or len(film_url_array)>0:
break
else:
get_people_url = resp_dict["next"]
for film_url in film_url_array:
film_details = get_film_details_by_url(film_url)
if film_details:
film_name_array = film_name_array+[film_details["title"]]
return film_name_array
def get_film_details_by_url(film_url):
resp = requests.get(film_url)
return_dict = None
if resp.status_code == 200:
return_dict = json.loads(resp.text)
return return_dict
def get_film_details_by_char_name(char_name):
swapi_base_url = "https://swapi.co/api/"
get_people_url = swapi_base_url+"people"
film_url_array = []
film_name_array = []
to_continue = True
while to_continue:
resp = requests.get(get_people_url)
if resp.status_code == 200:
resp_dict = json.loads(resp.text)
for ppl in resp_dict["results"]:
if ppl["name"].lower() == char_name.lower():
film_url_array = ppl["films"]
if not resp_dict["next"] or len(film_url_array)>0:
break
else:
get_people_url = resp_dict["next"]
for film_url in film_url_array:
film_details = get_film_details_by_url(film_url)
if film_details:
film_name_array = film_name_array+[film_details["title"]]
return film_name_array
Comments
Post a Comment