I am writing a small Function to catch a 404 when I request information from an API.
Code
def film_api():
number = random.randint(1, 10000)
film = requests.get('https://api.themoviedb.org/3/movie/{}?api_key=################'.format(number))
while film.status_code == '404':
film = requests.get('https://api.themoviedb.org/3/movie/{}?api_key=################'.format(number))
else:
return film.json()
404 Output
{
'status_code': 34,
'status_message': 'The resource you requested could not be found.'
}
correct output
{
'spoken_languages': [{
'name': 'English',
'iso_639_1': 'en'
}],
'genres': [{
'name': 'Comedy',
'id': 35
}, {
'name': 'Drama',
'id': 18
}],
'popularity': 0.493744,
'original_title': 'American Splendor',
'overview': 'An original mix of fiction and reality illuminates the life of comic book hero everyman Harvey Pekar.',
'runtime': 101,
'status': 'Released',
'homepage': 'http://www.newline.com/properties/americansplendor.html',
'video': False,
'revenue': 6003587,
'release_date': '2003-08-15',
'adult': False,
'vote_average': 6.4,
'imdb_id': 'tt0305206',
'poster_path': '/pcZ08ts1HaxWpUMMMQL2z3pomf1.jpg',
'production_companies': [],
'belongs_to_collection': None,
'title': 'American Splendor',
'backdrop_path': '/AswDSBB3rbh2auan9tKjETg09H8.jpg',
'original_language': 'en',
'budget': 0,
'vote_count': 43,
'production_countries': [{
'iso_3166_1': 'US',
'name': 'United States of America'
}],
'tagline': 'Ordinary life is pretty complicated',
'id': 2771
}
I have been bouncing back and forth between docs to find my answer and moved from an except to a while loop. I am using Python, Flask and Requests to build a simple web function so it does not need to be overly complex.
Is there something I am missing specifically?
requests status_code returns integer not string.
So you can fix like if film.status_code == 404:
def film_api():
number = random.randint(1, 10000)
film = requests.get('https://api.themoviedb.org/3/movie/{}?api_key=################'.format(number))
if film.status_code == 404:
film = requests.get('https://api.themoviedb.org/3/movie/{}?api_key=################'.format(number))
else:
return film.json()
Related
So I have two different dictionaries, the one is kind of like a "filter", and the other one is a list of dictionaries.
Currently what I'm doing is:
if all(item in tutor.items() for item in filters.items()):
The problem with this is, that I have a list of programs, that the tutor is capable of teaching in. It could be Maple, and or Geogebra. There are a lot of different options. The problem is, that a tutor may teach in multiple programs. So if I in the filters specify the program, Maple. I don't want it to show me the tutors that ONLY teach in Maple, but all the tutors where the program is/is not a part of the programs list.
So I somehow need to rewrite if all(item in tutor.items() for item in filters.items()):
To something like if contains(item in tutor.items() for item in filters.items()):
But that of course doesn't work.
tutor dictionary would look something like this:
{ 'age': 34,
'age_interval': '27+',
'car': 'No',
'course': '',
'educational_institution': 'Not set by tutor',
'email': 'ronaldreagon.rr#gmail.com',
'first_name': 'Ronald',
'fluent_danish': 'Not set by tutor',
'fluent_other': [''],
'gender': 'Not set by tutor',
'grade': '',
'gym_type': 'STX',
'has_second': False,
'hour_interval': None,
'hours': 0,
'id': 112306,
'inactive_reason': 'Jeg t▒r sgu ikke give ham forl▒b, s▒ g▒r ham inaktiv '
'-Elmar',
'last_name': 'Reagon Ravi Kumar',
'lat': 55.78319639999999,
'lat_alternative': 0,
'lng': 12.5151532,
'lng_alternative': 0,
'mobile_phone': '+45 50213154',
'more_courses': 'Yes',
'programs': 'Not set by tutor',
'status': 'Inactive',
'still_gym': 'Not set by tutor',
'subjects': 'None, ',
'tutor_address': 'Elektrovej 330 K5 2800 kongens lyngby',
'tutor_amount_of_students': 0,
'tutor_gym': 'Not set by tutor',
'tutor_qualification': 'Not set by tutor',
'tutor_uni': 'G▒r ikke p▒ en videreg▒ende uddannelse'}
{ 'age': 19,
'age_interval': '18 til 20',
'car': 'No',
'course': '',
'educational_institution': 'Not set by tutor',
'email': 'Katrinenm02#gmail.com',
'first_name': 'Katrine',
'fluent_danish': 'Not set by tutor',
'fluent_other': [''],
'gender': 'Not set by tutor',
'grade': '',
'gym_type': 'STX',
'has_second': False,
'hour_interval': None,
'hours': 0,
'id': 112356,
'inactive_reason': 'Inaktiv fordi hun er Kathrine',
'last_name': 'Mikha',
'lat': 55.653212,
'lat_alternative': 0,
'lng': 12.296957,
'lng_alternative': 0,
'mobile_phone': '53200337',
'more_courses': 'Yes',
'programs': 'Not set by tutor',
'status': 'Inactive',
'still_gym': 'Not set by tutor',
'subjects': 'None, ',
'tutor_address': 'Taastrup Have 8 st. TH',
'tutor_amount_of_students': 0,
'tutor_gym': 'Not set by tutor',
'tutor_qualification': 'Not set by tutor',
'tutor_uni': 'G▒r ikke p▒ en videreg▒ende uddannelse'}
{ 'age': 19,
And the filters, would just specify the same keys, and a value. For instance
{
"gym_type" "STX"
}
This is done through a GET request, to our API
#api.route("/test", methods=["GET"])
def validate_api_request():
try:
filters = request.json
return get_matching_tutors(filters)
except:
return error_response(400, "Bad request: error in body")
def get_matching_tutors(filters):
matching_tutors = []
for tutor in tutor_list:
if all(item in tutor.items() for item in filters.items()):
matching_tutors.append(tutor)
return jsonify(matching_tutors)
Let's say I specify this in the API call.
{
"programs": [
"Excel"
]
}
What I would get back, is a list of all the tutors that meet the requirement of being able to teach in Excel. But a lot of the tutors may be able to teach in Excel, and another program. But I will only get the tutors that ONLY teach in Excel. So the expected result should be something like this:
{
"age": 24,
"age_interval": "24 til 26",
"car": "Yes",
"course": "4. prioritet (Foretrækker fysisk)",
"educational_institution": "Københavns Universitet",
"email": "hdl543#alumni.ku.dk",
"first_name": "Ahmed",
"fluent_danish": "Yes",
"fluent_other": [
"Engelsk"
],
"gender": "Mand",
"grade": "7 til 8",
"gym_type": "STX",
"has_second": true,
"hour_interval": null,
"hours": 0,
"id": 134781,
"inactive_reason": "Blank",
"last_name": "Osman Mohammed",
"lat": 55.70321,
"lat_alternative": 55.68784609999999,
"lng": 12.530245,
"lng_alternative": 12.5696519,
"mobile_phone": "42313324",
"more_courses": "Yes",
"programs": [
"TI-Nspire",
"Geogebra",
"Wordmat",
"Excel",
"STATA"
],
"status": "Active",
"still_gym": "Jeg er færdig med gymnasiet",
"subjects": "Matematik B, Matematik C, Matematik Folkeskole, ",
"tutor_address": "Frederikssundsvej 54B, 2. th.",
"tutor_amount_of_students": 0,
"tutor_gym": "Frederiksberg Gymnasium",
"tutor_qualification": "Not set by tutor",
"tutor_uni": "Økonomi"
},
As you can see, I only specified Excel but I got a tutor that can teach in Excel, and other programs. So I'm thinking that I need to see if it "contains" the specified program in the API call
For the long term, you'll probably want to use a SQL database with a table for the tutors and a table with the different programs with a many-to-many relationship between them.
For now, we can create some helper functions. It's not strictly necessary, but it will make the code easier to read and maintain.
def matches_filter(filter_value, tutor_value):
if isinstance(tutor_value, list):
# We want to treat this as a set of values to match
# instead of checking for equality
# Note: if you have to do this often, consider using sets instead of lists to store these values.
return set(filter_value).issubset(set(tutor_value))
return filter_value == tutor_value
def matches_all_filters(filter_dict, tutor):
return all(filter_key in tutor and matches_filter(filter_value, tutor[filter_key])
for filter_key, filter_value in filter_dict.items())
def get_matching_tutors(filters):
matching_tutors = [tutor for tutor in tutor_list
if matches_all_filters(filters, tutor]
return jsonify(matching_tutors)
I'm sorry for my bad english
Hello, I am using a brokerage firm for payment instrument. The API connection is successful and I get the result. But I can't use the returned result information.
payment_card = {
'cardHolderName': kartisim,
'cardNumber': kartno,
'expireMonth': kartskt_ay,
'expireYear': '2030',
'cvc': karcvc,
'registerCard': '0'
}
buyer = {
'id': adres.id,
'name': adres.adres_uye.username,
'surname': 'Doe',
'gsmNumber': '+905350000000',
'email': adres.adres_uye.email,
'identityNumber': '74300864791',
'lastLoginDate': '2015-10-05 12:43:35',
'registrationDate': '2013-04-21 15:12:09',
'registrationAddress': adres.adres_detay,
'ip': '85.34.78.112',
'city': 'Istanbul',
'country': 'Turkey',
'zipCode': '34732'
}
address = {
'contactName': 'Jane Doe',
'city': 'Istanbul',
'country': 'Turkey',
'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
'zipCode': '34732'
}
basket_items = []
for bas in uye:
basa = {
'id': str(bas.id),
'name': str(bas.sepet_urun.urun_baslik),
'category1': str(bas.sepet_urun.urun_anakategori.anakategori_baslik),
'category2': str(bas.sepet_urun.urun_altkategori.altkategori_baslik),
'itemType': 'VIRTUAL',
'price': str(bas.sepet_fiyat)
}
basket_items.append(basa)
print(basket_items)
request_payload = {
'locale': 'tr',
'conversationId': '123456789',
'price': str(sepetf),
'paidPrice': str(sepetf),
'currency': 'TRY',
'installment': '1',
'basketId': str(sepetid),
'paymentChannel': 'WEB',
'paymentGroup': 'PRODUCT',
'paymentCard': payment_card,
'buyer': buyer,
'shippingAddress': address,
'billingAddress': address,
'basketItems': basket_items
}
payment = iyzipay.Payment().create(request_payload, options)
print(payment.read().decode('utf-8'))
return HttpResponse(payment["status"])
I cannot use the returned result information. The returned result is as follows
The error I get is as follows:
'HTTPResponse' object is not subscriptable
Looks like the issue is here.
return HttpResponse(payment["status"])
payment returns an HTTPResponse response object and you cannot directly index the status. Instead you should use .status attribute.
If your intention is to return JSON back as response you could use JsonResponse class from django.http module.
return JsonResponse(json.loads(payment.read().decode('utf-8')))
This is my first time dealing with json data. So I'm not that familiar with the structure of json.
I got some data through "we the people" e-petition sites with following code:
url = "https://api.whitehouse.gov/v1/petitions.json?limit=3&offset=0&createdBefore=1573862400"
jdata_2 = requests.get(url).json()
Yet, I realize this is something different from... the ordinary json structure since I got some error while I tried to convert it into excel file with pandas
df = pandas.read_json(jdata_2)
Obviously, I must miss something which I must have done before using pandas.read_json() code.
I have searched for the answer but most of questions are "How can I convert json data into excel data", which needs json data. For my case, I scraped it from the url, so I thought I could make that strings into json data, and then try to convert it into excel data as well. So I tried to use json.dump() as well, but it didn't work as well.
I know it must be the naive question. But I'm not sure where I can start with this naive question. If anyone can instruct me how to deal with it, I would really appreciate it. Or link me some references that I can study as well.
Thank you for your help in advance.
This is the json data with the requests, and I pprint it with indent=4.
Input:
url = "https://api.whitehouse.gov/v1/petitions.json?limit=3&offset=0&createdBefore=1573862400"
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(jdata_2)
Output :
{ 'metadata': { 'requestInfo': { 'apiVersion': 1,
'query': { 'body': None,
'createdAfter': None,
'createdAt': None,
'createdBefore': '1573862400',
'isPublic': 1,
'isSignable': None,
'limit': '3',
'mock': 0,
'offset': '0',
'petitionsDefaultLimit': '1000',
'publicThreshold': 149,
'responseId': None,
'signatureCount': None,
'signatureCountCeiling': None,
'signatureCountFloor': 0,
'signatureThreshold': None,
'signatureThresholdCeiling': None,
'signatureThresholdFloor': None,
'sortBy': 'DATE_REACHED_PUBLIC',
'sortOrder': 'ASC',
'status': None,
'title': None,
'url': None,
'websiteUrl': 'https://petitions.whitehouse.gov'},
'resource': 'petitions'},
'responseInfo': { 'developerMessage': 'OK',
'errorCode': '',
'moreInfo': '',
'status': 200,
'userMessage': ''},
'resultset': {'count': 1852, 'limit': 3, 'offset': 0}},
'results': [ { 'body': 'Please save kurdish people in syria \r\n'
'pleaee save north syria',
'created': 1570630389,
'deadline': 1573225989,
'id': '2798897',
'isPublic': True,
'isSignable': False,
'issues': [ { 'id': 326,
'name': 'Homeland Security & '
'Defense'}],
'petition_type': [ { 'id': 291,
'name': 'Call on Congress to '
'act on an issue'}],
'reachedPublic': 0,
'response': [],
'signatureCount': 149,
'signatureThreshold': 100000,
'signaturesNeeded': 99851,
'status': 'closed',
'title': 'Please save rojava north syria\r\n'
'please save kurdish people\r\n'
'please stop erdogan\r\n'
'plaease please',
'type': 'petition',
'url': 'https://petitions.whitehouse.gov/petition/please-save-rojava-north-syria-please-save-kurdish-people-please-stop-erdogan-plaease-please'},
{ 'body': 'Kane Friess was a 2 year old boy who was '
"murdered by his mom's boyfriend, Gyasi "
'Campbell. Even with expert statements from '
'forensic anthropologists, stating his injuries '
'wete the result of homicide. Mr. Campbell was '
'found guilty of involuntary manslaughter. This '
"is an outrage to Kane's Family and our "
'community.',
'created': 1566053365,
'deadline': 1568645365,
'id': '2782248',
'isPublic': True,
'isSignable': False,
'issues': [ { 'id': 321,
'name': 'Criminal Justice Reform'}],
'petition_type': [ { 'id': 281,
'name': 'Change an existing '
'Administration '
'policy'}],
'reachedPublic': 0,
'response': [],
'signatureCount': 149,
'signatureThreshold': 100000,
'signaturesNeeded': 99851,
'status': 'closed',
'title': "Kane's Law. Upon which the murder of a child, "
'regardless of circumstances, be seen as 1st '
'degree murder. A Federal Law.',
'type': 'petition',
'url': 'https://petitions.whitehouse.gov/petition/kanes-law-upon-which-murder-child-regardless-circumstances-be-seen-1st-degree-murder-federal-law'},
{ 'body': "Schumer and Pelosi's hatred and refusing to "
'work with President Donald J. Trump is holding '
'America hostage. We the people know securing '
'our southern border is a priority which will '
'not happen with these two in office. Lets '
'build the wall NOW!',
'created': 1547050064,
'deadline': 1549642064,
'id': '2722358',
'isPublic': True,
'isSignable': False,
'issues': [ {'id': 306, 'name': 'Budget & Taxes'},
{ 'id': 326,
'name': 'Homeland Security & '
'Defense'},
{'id': 29, 'name': 'Immigration'}],
'petition_type': [ { 'id': 291,
'name': 'Call on Congress to '
'act on an issue'}],
'reachedPublic': 0,
'response': [],
'signatureCount': 149,
'signatureThreshold': 100000,
'signaturesNeeded': 99851,
'status': 'closed',
'title': 'Remove Chuck Schumer and Nancy Pelosi from '
'office',
'type': 'petition',
'url': 'https://petitions.whitehouse.gov/petition/remove-chuck-schumer-and-nancy-pelosi-office'}]}
And this is the Error message I got
Input :
df = pandas.read_json(jdata_2)
Output :
ValueError: Invalid file path or buffer object type: <class 'dict'>
You can try the below code as well, it is working fine
URL = "https://api.whitehouse.gov/v1/petitions.json?limit=3&offset=0&createdBefore=1573862400"
// fetching the json response from the URL
req = requests.get(URL)
text_data= req.text
json_dict= json.loads(text_data)
//converting json dictionary to python dataframe for results object
df = pd.DataFrame.from_dict(json_dict["results"])
Finally, saving the dataframe to excel format i.e xlsx
df.to_excel("output.xlsx")
This is my first question :)
I loop over a nested dictionary to print specific values. I am using the following code.
for i in lizzo_top_tracks['tracks']:
print('Track Name: ' + i['name'])
It works for string variables, but does not work for other variables. For example, when I use the following code for the date variable:
for i in lizzo_top_tracks['tracks']:
print('Album Release Date: ' + i['release_date'])
I receive a message like this KeyError: 'release_date'
What should I do?
Here is a sample of my nested dictionary:
{'tracks': [{'album': {'album_type': 'album',
'artists': [{'external_urls': {'spotify': 'https://open.spotify.com/artist/56oDRnqbIiwx4mymNEv7dS'},
'href': 'https://api.spotify.com/v1/artists/56oDRnqbIiwx4mymNEv7dS',
'id': '56oDRnqbIiwx4mymNEv7dS',
'name': 'Lizzo',
'type': 'artist',
'uri': 'spotify:artist:56oDRnqbIiwx4mymNEv7dS'}],
'external_urls': {'spotify': 'https://open.spotify.com/album/74gSdSHe71q7urGWMMn3qB'},
'href': 'https://api.spotify.com/v1/albums/74gSdSHe71q7urGWMMn3qB',
'id': '74gSdSHe71q7urGWMMn3qB',
'images': [{'height': 640,
'width': 640}],
'name': 'Cuz I Love You (Deluxe)',
'release_date': '2019-05-03',
'release_date_precision': 'day',
'total_tracks': 14,
'type': 'album',
'uri': 'spotify:album:74gSdSHe71q7urGWMMn3qB'}]}
The code you posted isn't syntactically correct; running it through a Python interpreter gives a syntax error on the last line. It looks like you lost a curly brace somewhere toward the end. :)
I went through it and fixed up the white space to make the structure easier to see; the way you had it formatted made it hard to see which keys were at which level of nesting, but with consistent indentation it becomes much clearer:
lizzo_top_tracks = {
'tracks': [{
'album': {
'album_type': 'album',
'artists': [{
'external_urls': {
'spotify': 'https://open.spotify.com/artist/56oDRnqbIiwx4mymNEv7dS'
},
'href': 'https://api.spotify.com/v1/artists/56oDRnqbIiwx4mymNEv7dS',
'id': '56oDRnqbIiwx4mymNEv7dS',
'name': 'Lizzo',
'type': 'artist',
'uri': 'spotify:artist:56oDRnqbIiwx4mymNEv7dS'
}],
'external_urls': {
'spotify': 'https://open.spotify.com/album/74gSdSHe71q7urGWMMn3qB'
},
'href': 'https://api.spotify.com/v1/albums/74gSdSHe71q7urGWMMn3qB',
'id': '74gSdSHe71q7urGWMMn3qB',
'images': [{'height': 640, 'width': 640}],
'name': 'Cuz I Love You (Deluxe)',
'release_date': '2019-05-03',
'release_date_precision': 'day',
'total_tracks': 14,
'type': 'album',
'uri': 'spotify:album:74gSdSHe71q7urGWMMn3qB'
}
}]
}
So the first (and only) value you get for i in lizzo_top_tracks['tracks'] is going to be this dictionary:
i = {
'album': {
'album_type': 'album',
'artists': [{
'external_urls': {
'spotify': 'https://open.spotify.com/artist/56oDRnqbIiwx4mymNEv7dS'
},
'href': 'https://api.spotify.com/v1/artists/56oDRnqbIiwx4mymNEv7dS',
'id': '56oDRnqbIiwx4mymNEv7dS',
'name': 'Lizzo',
'type': 'artist',
'uri': 'spotify:artist:56oDRnqbIiwx4mymNEv7dS'
}],
'external_urls': {
'spotify': 'https://open.spotify.com/album/74gSdSHe71q7urGWMMn3qB'
},
'href': 'https://api.spotify.com/v1/albums/74gSdSHe71q7urGWMMn3qB',
'id': '74gSdSHe71q7urGWMMn3qB',
'images': [{'height': 640, 'width': 640}],
'name': 'Cuz I Love You (Deluxe)',
'release_date': '2019-05-03',
'release_date_precision': 'day',
'total_tracks': 14,
'type': 'album',
'uri': 'spotify:album:74gSdSHe71q7urGWMMn3qB'
}
}
The only key in this dictionary is 'album', the value of which is another dictionary that contains all the other information. If you want to print, say, the album release date and a list of the artists' names, you'd do:
for track in lizzo_top_tracks['tracks']:
print('Album Release Date: ' + track['album']['release_date'])
print('Artists: ' + str([artist['name'] for artist in track['album']['artists']]))
If these are dictionaries that you're building yourself, you might want to remove some of the nesting layers where there's only a single key, since they just make it harder to navigate the structure without giving you any additional information. For example:
lizzo_top_albums = [{
'album_type': 'album',
'artists': [{
'external_urls': {
'spotify': 'https://open.spotify.com/artist/56oDRnqbIiwx4mymNEv7dS'
},
'href': 'https://api.spotify.com/v1/artists/56oDRnqbIiwx4mymNEv7dS',
'id': '56oDRnqbIiwx4mymNEv7dS',
'name': 'Lizzo',
'type': 'artist',
'uri': 'spotify:artist:56oDRnqbIiwx4mymNEv7dS'
}],
'external_urls': {
'spotify': 'https://open.spotify.com/album/74gSdSHe71q7urGWMMn3qB'
},
'href': 'https://api.spotify.com/v1/albums/74gSdSHe71q7urGWMMn3qB',
'id': '74gSdSHe71q7urGWMMn3qB',
'images': [{'height': 640, 'width': 640}],
'name': 'Cuz I Love You (Deluxe)',
'release_date': '2019-05-03',
'release_date_precision': 'day',
'total_tracks': 14,
'type': 'album',
'uri': 'spotify:album:74gSdSHe71q7urGWMMn3qB'
}]
This structure allows you to write the query the way you were originally trying to do it:
for album in lizzo_top_albums:
print('Album Release Date: ' + album['release_date'])
print('Artists: ' + str([artist['name'] for artist in album['artists']]))
Much simpler, right? :)
I am able to get a dictionary from my request function. Here's what I get:
{
'collaborative': False,
'external_urls': {
'spotify': 'http://open.spotify.com/user/dashrif/playlist/3LEoetnegEv2Q8jdmB8TER'
},
'href': 'https://api.spotify.com/v1/users/dashrif/playlists/3LEoetnegEv2Q8jdmB8TER',
'id': '3LEoetnegEv2Q8jdmB8TER',
'images': [{
'height': 640,
'url': 'https://mosaic.scdn.co/640/0cd0508f78c5e5f6e2b01b3009753083c7977270527f35929eff151f80bcabec17b2fb9383da342b32d7d3432ff965abb01f706ec2efc38282a11b45d088e352f19eebb53874fcdc4366ff4249da45fe',
'width': 640
},
{
'height': 300,
'url': 'https://mosaic.scdn.co/300/0cd0508f78c5e5f6e2b01b3009753083c7977270527f35929eff151f80bcabec17b2fb9383da342b32d7d3432ff965abb01f706ec2efc38282a11b45d088e352f19eebb53874fcdc4366ff4249da45fe',
'width': 300
},
{
'height': 60,
'url': 'https://mosaic.scdn.co/60/0cd0508f78c5e5f6e2b01b3009753083c7977270527f35929eff151f80bcabec17b2fb9383da342b32d7d3432ff965abb01f706ec2efc38282a11b45d088e352f19eebb53874fcdc4366ff4249da45fe',
'width': 60
}],
'name': 'Life Playlist Vol. I: The Fuck You Getting Hype For? You Still Broke',
'owner': {
'external_urls': {
'spotify': 'http://open.spotify.com/user/dashrif'
},
'href': 'https://api.spotify.com/v1/users/dashrif',
'id': 'dashrif',
'type': 'user',
'uri': 'spotify:user:dashrif'
},
'public': True,
'snapshot_id': 'PCG8b/CxCfaCjX0mmFMZ3T9NUsJC1sz5MVAXfQf3aefQhcAi4Zdm2k+3rySb/HLw',
'tracks': {
'href': 'https://api.spotify.com/v1/users/dashrif/playlists/3LEoetnegEv2Q8jdmB8TER/tracks',
'total': 63
},
'type': 'playlist',
'uri': 'spotify:user:dashrif:playlist:3LEoetnegEv2Q8jdmB8TER'
}
At least I hope this is a dictionary. Honestly at this point I've gotten so many errors I'm not too sure. Here's the code in question:
playlist_api_endpoint = "{}/playlists".format(profile_data["href"])
playlists_response = requests.get(playlist_api_endpoint,
headers=authorization_header)
playlist_data = json.loads(playlists_response.text)
display_arr = [profile_data] + playlist_data["items"]
return render_template("index.html",sorted_array=display_arr)
Basically I want to be able to filter out the last uri object and any other uri objects when adding new playlists. I've tried .items(), filtered dictionary, and a couple of other things I can't remember. If anyone has an idea of where I'm going wrong or how to to achieve my goal, I'd love some help. Thanks!