KeyError: 'name' in Spotify Web API - python

I'm using spotify's web API to get song information for a discord bot im making. I'm hosting the bot on heroku. im using the tracks option to get the track name and artist name from a songs ID. When the bot is on heroku, it throws the following error:
https://pastebin.com/smqqqDfY
however, when i host the same code on my laptop, it gives no such error. I even separated the spotify code to see if the JSON file has a key named 'name' and it works!
the code is:
#pulls the name and artist name from the API and link
def spotifypull(uri):
r = requests.get(spotify_base.format(id=uri), headers=headers)
r = r.json()
return (r['name']+" "+r['artists'][0]['name'])
#checks if the link is a spotify link(this is from the "request" function)
if query.find("spotify") !=-1:
uri = query[31:53]
name = spotifypull(uri)
this same code gives the proper output if separated locally
import requests
query = "https://open.spotify.com/track/6WkrFOo6SGAjhGMrjIwAD4?si=VDwYLniGQLGmqzUK3RdBow"
uri = query[31:53]
SPOTIFY_ID = "<id>"
SPOTIFY_SECRET = "<secret>"
AUTH_URL = 'https://accounts.spotify.com/api/token'
ytbase = "https://www.youtube.com/watch?v="
auth_response = requests.post(AUTH_URL, {
'grant_type': 'client_credentials',
'client_id': SPOTIFY_ID,
'client_secret': SPOTIFY_SECRET,
})
auth_response_data = auth_response.json()
access_token = auth_response_data['access_token']
headers = {
'Authorization': 'Bearer {token}'.format(token=access_token)
}
spotify_base = 'https://api.spotify.com/v1/tracks/{id}'
r = requests.get(spotify_base.format(id=uri), headers=headers)
r = r.json()
name = r['name']+" "+r['artists'][0]['name']
print(name)
output of above:
Wasn't Enough CrySpy
Any help would be massively appreciated! the full code is here if needed.
edit:
when ran locally,
r.text is https://pastebin.com/sjrW3exW
r.get_status is 200

Okay i got the issue, the spotify token was expiring after an hour. Thanks to #ygrorg for the idea.
Edit: Since some max brain mods want me to provide more clarity, Spotify tokens are valid for only an hour, I solved it by calling for a new token everytime a song is played. Alternatively, its only possible that you put the token regeneration commands in an infinite loop and put a delay of 30-45 min at the end of the loop, so you have a fresh token every time.

Related

Azure DevOps Personal Access Token

I have my PAT and some example code to pull the projects within my organization. However when I try to use a GET command to read a work item I am given response 203. Most of my Googling has lead to three solutions, neither of which has been successful for me. One mentions editing my PAT using base64 and a :. The second says to use an oauth2 python library. The third solution is the code below.
PE_DEVOPS_NAME = "DevOpsArea"
# Fill in with your personal access token and org URL
personal_access_token = ':XXXX'
organization_url = 'https://dev.azure.com/organization/'
post_url = organization_url + PE_DEVOPS_NAME + "/_apis/wit/workitems/$task?api-version=6.0"
get_url = organization_url + PE_DEVOPS_NAME + "/_apis/wit/workitems/60814?api-version=6.0"
# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = Connection(base_url=organization_url, creds=credentials)
# Get a client (the "core" client provides access to projects, teams, etc)
core_client = connection.clients.get_core_client()
# Get the first page of projects
get_projects_response = core_client.get_projects()
for project in get_projects_response.value:
if project.name == PE_DEVOPS_NAME:
print(project.name)
response = requests.get(get_url)
print(get_url)
print(response.json)
Am I missing something in the above code that would make my PAT not work?
I kept looking and found the following code:
username = ''
personal_access_token = 'XXXX'
login_info = username + ":" + personal_access_token
b64 = base64.b64encode(login_info.encode()).decode()
headers = {"Authorization" : "Basic %s" % b64}
organization_url = 'https://dev.azure.com/organization/'
post_url = organization_url + PE_DEVOPS_NAME + "/_apis/wit/workitems/$task?api-version=6.0"
get_url = organization_url + PE_DEVOPS_NAME + "/_apis/wit/workitems/60814?api-version=6.0"
response = requests.get(get_url, headers=headers)
print(response.json())
This code works for my GET command. I will test with a POST. Can anyone explain why this works but the azure python library does not?
For the first sample in your code, definitely it will not work, there are two errors in your code.
When you use response = requests.get(get_url), it does not use any credential to call the REST API.
Even you use the Azure DevOps Python API python library, it should be personal_access_token = 'XXXX' instead of personal_access_token = ':XXXX', you should not include : character.
For 203 status code, if you use print(response.text) instead of print(response.json) in the last line, easily you can find it just returns a sign-in page.
To get the work item with the Azure DevOps Python API python library, you could add the code below to your sample, it gets the work item whose id is 68, if you want to get the 60814 one, just use range(60814, 60815).
wit_client = connection.clients.get_work_item_tracking_client()
desired_ids = range(68, 69)
print(desired_ids)
work_items = wit_client.get_work_items(ids=desired_ids)
for wit in work_items:
print(wit)
Reference - https://github.com/microsoft/azure-devops-python-samples/blob/552544e9cde70269e37784aff2e62dd97420b862/src/samples/work_item_tracking.py

Google DialogFlow: Usage of Session Entity

I am very newbie with the Google DialogFlow, As I am exploring with the Api.ai. I got to know about the userEntity(V1) or SessionEntity(V2).
I have created the session entity using fulfilment with the below code:
import requests
REQUIRED_SCOPES = 'https://www.googleapis.com/auth/dialogflow'
access_token = generate_access_token()
url = 'https://dialogflow.googleapis.com/v2/'+ session_id +'/entityTypes'
headers = {'Authorization': 'Bearer '+ access_token,'Content-Type': 'application/json'}
entity_data = json.dumps({"entityOverrideMode": "ENTITY_OVERRIDE_MODE_OVERRIDE", "entities": [{"synonyms":["sugarcane", "sugar"],"value": "sweet"}], "value": str(session_id)+'fruit'})
response = requests.post(url,headers=headers,data=entity_data)
It creates the sessionEntity with success and also able to list the entity from the session.
It's working while I tried from the same page of console with TryMe-Intents.
But while I tried using simulator or mobile to pass some phrases for my Intent I am not getting the newly created entity to map with the matching phrases.
For Example, I want Sugarcane, at this point, I suppose to get sugarcane as mapped with the entity with the current session for followup intents.
But it was not happening, don't know if I am missing anything. Let me know if anything is wrong or missing.
Suggestions are always welcome.
Reference Links which I have referred to achieve:
https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/v2/projects.agent.sessions.entityTypes/create
https://cloud.google.com/dialogflow-enterprise/docs/entities-session

How to add a new item using Python Etsy HTTP API methods?

I am trying to use Etsy API to add a new listing on my store. In the documents section it says (below section how to do it). First fyi I have never used HTTP Method before so I am not sure how to setup the code so that it adds a new item.
(Link to the Etsy API page https://www.etsy.com/developers/documentation/reference/listing).
Method Name createListing
Synopsis Creates a new Listing.
HTTP Method POST
URI /listings
Parameters
Name Required Default Type
quantity Y int
title Y string
description Y text
price Y float
materials N array(string)
shipping_template_id N int
shop_section_id N int
image_ids N array(int)
is_customizable N boolean
non_taxable N boolean
image N image
state N active enum(active, draft)
processing_min N int
processing_max N int
category_id N int
taxonomy_id N int
tags N array(string)
who_made Y enum(i_did, collective, someone_else)
is_supply Y boolean
when_made Y enum(made_to_order, 2010_2017, 2000_2009, 1998_1999, before_1998, 1990_1997, 1980s, 1970s, 1960s, 1950s, 1940s, 1930s, 1920s, 1910s, 1900s, 1800s, 1700s, before_1700)
recipient N enum(men, women, unisex_adults, teen_boys, teen_girls, teens, boys, girls, children, baby_boys, baby_girls, babies, birds, cats, dogs, pets, not_specified)
occasion N enum(anniversary, baptism, bar_or_bat_mitzvah, birthday, canada_day, chinese_new_year, cinco_de_mayo, confirmation, christmas, day_of_the_dead, easter, eid, engagement, fathers_day, get_well, graduation, halloween, hanukkah, housewarming, kwanzaa, prom, july_4th, mothers_day, new_baby, new_years, quinceanera, retirement, st_patricks_day, sweet_16, sympathy, thanksgiving, valentines, wedding)
style N array(string)
Requires OAuth Y
Permission Scope listings_w
Notes
A shipping_template_id is required when creating a listing.
All listings created on www.etsy.com must be actual items for sale. Please see our guidelines for testingwith live listings.
Creating a listing creates a single inventory products with the supplied price and quantity. Use updateInventory to add more products.
The code I have right know looks like this
import urllib
import requests
url = 'https://openapi.etsy.com/v2/listings/active?api_key={YOUR KEY HERE)' # I put my API key here
r = requests.get(url)
payload = {'quantity': '1', 'title': 'testdfsdfdfs0','description': 'dfsdfsdfsdfdsf','price': '2.55','who_made': 'i_did','is_supply': '0','when_made': '2010_2017'}
rrr = requests.post(url,payload)
print rrr # I get an error 404
How can I add an item for sale on Etsy through Python HTTP method?
Update
from requests_oauthlib import OAuth1Session
import requests
from requests_oauthlib import OAuth1
import json
tempory_token_url = []
oauth_response_bucket = []
client_key = '.......'
client_secret = '......'
oauth = OAuth1Session(client_key, client_secret=client_secret)
request_token_url = 'https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20listings_r'
fetch_response = oauth.fetch_request_token(request_token_url)
resource_owner_key = fetch_response.get('oauth_token') # Have it
resource_owner_secret = fetch_response.get('oauth_token_secret')
oauth_url_temp = tempory_token_url[0]['login_urI']
base_authorization_url = oauth_url_temp
authorization_url = oauth.authorization_url(base_authorization_url)
redirect_response = raw_input('Paste the full redirect URL here: ')
oauth_response = oauth.parse_authorization_response(redirect_response)
verifier = oauth_response.get('oauth_verifier')
access_token_url = redeirect_response
oauth = OAuth1Session(client_key=client_secret=client_secret,resource_owner_key=resource_owner_key,resource_owner_secret=resource_owner_secret,verifier=verifier)
oauth_tokens = oauth.fetch_access_token(access_token_url)
resource_owner_key = oauth_tokens.get('oauth_token')
resource_owner_secret = oauth_tokens.get('oauth_token_secret')
Any ideas how to make this work? There is very little info regarding Etsy API and most of the stuff is in PHP which I have no clue how to work.
Image Uploading API
Everything looks the same like above this time I just changed the payload but I am getting a 403 Error. I am not sure what is causing it. My best guess would be something with oauth1.0 i think on their website it says you need oauth 1.1.
Here is how I set it up but I am getting 403 error:
url = 'https://openapi.etsy.com/v2/listings'
payload = {'listing_id':'342434342', 'image': ("test1.jpg", open('C:\\Users\\abc\\test1.jpg'),'image/jpeg'),'type':'image/jpeg'}
result = etsy.put(url, params=payload)
print result
Comment: ... at this point I am lost I have no idea where to put the pin# that etsy gave me
etsy oauth#reference
The token credentials you receive for a account do not expire,
and can be used over and over again to make authenticated API requests.
You should keep the token secret in a secure location and never send it as a plaintext parameter
(it's only used for signing your requests, and never needs to be sent in an API request on its own.)
You will not need to step through the OAuth authorization again,
unless you decides to revoke access, or unless you add features that require additional permission scopes.
Note: Didn't find a equivalent Replacement for PHP OAUTH_AUTH_TYPE_URI.
OAuth1Session Defaults to signature_type=u'AUTH_HEADER', so this could be wrong.
If this fails, you could try:
from oauthlib.oauth1 import SIGNATURE_TYPE_QUERY, SIGNATURE_TYPE_BODY
OAuth1Session(..., signature_type=SIGNATURE_TYPE_QUERY)
Create etsy OAuth1Session to reuse for Requests:
etsy = OAuth1Session(client_key,
client_secret=client_secret,
resource_owner_key=resource_owner_key,
resource_owner_secret=resource_owner_secret)
etsy Making an Authorized Request to the API:
response = etsy.get("https://openapi.etsy.com/v2/users/__SELF__")
user_data = json.loads(response.body_as_unicode())
etsy Checking Permission Scopes After Authentication:
response = etsy.get("https://openapi.etsy.com/v2/oauth/scopes")
meta = json.loads(response.body_as_unicode())
etsy Creates a new Listing
url = 'https://openapi.etsy.com/v2/listings'
payload = {'quantity': '1', 'title':...}
result = etsy.post(url, params=payload)
Comment: for api key do I need to import oauth2
According to Reference, Yes.
For write access and for accessing private user data, an OAuth access
token is required. Your application key is required to start the OAuth
authentication process.
Requires OAuth Y
Also your url should end with
URI /listings
url = 'https://openapi.etsy.com/v2/listings'
Your url should only up to the Question mark, for example:
url = 'https://openapi.etsy.com/v2/listings/active'
payload = {'api_key':YOUR KEY HERE, 'quantity': '1', ...
rrr = requests.post(url, params=payload)
Requests Quickstart: Passing Parameters In URLs
You often want to send some sort of data in the URL's query string.
If you were constructing the URL by hand,
this data would be given as key/value pairs in the URL after a question mark, e.g. \http://bin.org/get?key=val.
Requests allows you to provide these arguments as a dictionary of strings, using the params keyword argument.
Question: I am trying to upload a picture ... getting a 403 error
Your url Endpoint and payload isn't correct.
url = 'https://openapi.etsy.com/v2/listings'
payload = {'listing_id':'342434342', 'image': ("test1.jpg", open('C:\\Users\\abc\\test1.jpg'),'image/jpeg'),'type':'image/jpeg'}
Steps to do a etsy Request(uploadListingImage):
Read the Reference for your Method Name
Method Name uploadListingImage
HTTP Method POST
URI /listings/:listing_id/images
Parameters Name Required Default Type
listing_id Y int
listing_image_id N int
image N imagefile
...
Requires OAuth Y
Respect Supported Sizes Working with Images
Note: For me, it's unclear what the image Parameter is for.
And as it's NOT required makes no sense.
I assume its a Placeholder for the Parameter at Point 4 below: {'image':...
Build the URI
uri = 'https://openapi.etsy.com/v2/listings/342434342/images'
Create the Params Dict according to the above Reference
I recommend to use a listing_image_id, as this seems the only way to delete a Image afterwards.
params = {'listing_id':'342434342', 'listing_image_id': 1}
Create Multipart-Encoded File Dict
Image uploads can be performed using a POST request with the Content-Type: multipart/form-dataheader, following RFC1867
# PHP example from Reference:
# $params = array('#image' => '#'.$source_file.';type='.$mimetype);
files = {'image': ("test1.jpg", open('C:\\Users\\abc\\test1.jpg', 'rb'), 'image/jpeg')}
Do the Request, according the Reference, you have to use OAuth and POST
result = etsy.post(uri, params=params, files=files)
Please Comment if this is working for you or why not.

Python spotipy Oauth : Bad request

This is my code
UserScope = 'user-library-read'
util.prompt_for_user_token(username='vulrev1',scope=UserScope,client_id="533adb3f925b488za9d3772640ec6403",client_secret='66054b185c7541fcabce67afe522449b',redirect_uri="http://127.0.0.1/callback")
lz_uri = 'spotify:artist:36QJpDe2go2KgaRleHCDTp'
spotify = spotipy.Spotify()
results = spotify.artist_top_tracks(lz_uri)
for track in results['tracks'][:10]:
print ('track : ' + track['name'])
I'm getting this
spotipy.oauth2.SpotifyOauthError: Bad Request
I'm not quite sure what's going on here, is there something I need to do with the host files ? because http://127.0.0.1 refuses to connect
token = util.prompt_for_user_token(username='vulrev1',scope=UserScope,client_id="533adb3f925b488za9d3772640ec6403",client_secret='66054b185c7541fcabce67afe522449b',redirect_uri="http://127.0.0.1/callback")
spotify = spotipy.Spotify(auth=token)
You have to send your token as a auth. And also i think you must change your user ID to the specific numbers where u can find at the link of your profile.

X-PAYPAL-APPLICATION-ID error

I'm writing an application that utilizes Paypal's permissions API. I'm currently working on the sandbox. I get the verification code correctly but when I try to GetAccessToken, I get the error:
{"responseEnvelope":{"timestamp":"2013-09-03T08:32:16.580-07:00","ack":"Failure","correlationId":"3527b7033f20f","build":"2210301"},"error":[{"errorId":"560022","domain":"PLATFORM","subdomain":"Application","severity":"Error","category":"Application","message":"The X-PAYPAL-APPLICATION-ID header contains an invalid value","parameter":["X-PAYPAL-APPLICATION-ID"]}]}
I'm using the sandbox APP_ID and all the Verification code is also gotten dynamically. Here is my code fragment.
token = "AAAAAAAYaraTSVjvkUBT"
verification = "mgnnWDVfFmgAES0q371Hug"
headers2 = {
"X-PAYPAL-SECURITY-USERID": settings.USERNAME,
"X-PAYPAL-SECURITY-PASSWORD": settings.PASSWORD,
"X-PAYPAL-SECURITY-SIGNATURE": settings.SIGNATURE,
"X-PAYPAL-REQUEST-DATA-FORMAT": "JSON",
"X-PAYPAL-RESPONSE-DATA-FORMAT": "JSON",
"X-PAYPAL-APPLICATION-ID": "APP-80W284485P519543T",
}
url = "https://svcs.paypal.com/Permissions/GetAccessToken/?token=%s&verifier=%s" %(token, verification)
dat2 = {"requestEnvelope": {"errorLanguage":"en_US"}}
req2 = urllib2.Request(url, simplejson.dumps(dat2), headers2)
res2 = urllib2.urlopen(req2).read()
What I'm I doing wrong??
You cannot use the sandbox application id on the live environment. See https://developer.paypal.com/webapps/developer/docs/classic/lifecycle/goingLive/#register to learn how to obtain a live application id.
The endpoint should be https://svcs.sandbox.paypal.com as Siddick said above. The paypal API documentation is so inconsistent, the endpoint i had used previously had been used in a sandbox situation in the documentation.

Categories