Hello I am trying to make a django website using the spotify api, so I am trying to get some simple example code working using the spotipy python library, but keep getting a http post 500 whenever my spotipy code is called.
Right now if you click a button on the website it makes a post request to one of my endpoints, which calls a python function and is supposed to return text. This is the code in the python function:
import spotipy
def spotifyleastplayed_py(request):
print("spotifyleastplayed_py()")
if request.method == 'POST':
print("0")
sp = spotipy.Spotify()
print("1")
results = sp.search(q='weezer', limit=20)
print("2")
print(results)
data = "temp spotifyleastplayed_py() Return Data"
return HttpResponse(data) #HttpResponse(json.dumps("{test:bobo}"))
When the function is called, my console outputs the following error message:
[06/Oct/2019 21:49:03] "GET /spotifyleastplayed HTTP/1.1" 200 1992
spotifyleastplayed_py()
0
1
[06/Oct/2019 21:49:07] "POST /spotifyleastplayed_py/ HTTP/1.1" 500 6326
Do I need to add the spotipy url to django somewhere so the library can make calls successfully? It seems like its failing to make the http request to spotipy.
First of all, I would advise you to learn more about debugging your python code, as this is a critical skill to have as a developer, and it might help you get further into the problem next time. One thing you could deduce from your example for example is that your program does not execute anything beyond the following line
results = sp.search(q='weezer', limit=20)
But the only information you are getting is a 500 return code, which doesn't tell you exactly what is going wrong, only that something is not right.
One first step you could take for example is trying to find out what exactly is causing your code to terminate. If you wrap the statement in a try except block, you'll be able to see exactly what kind of error is occurring, like this:
try:
results = sp.search(q='weezer', limit=20)
except Exception as e:
print(e)
This catches the error generated by the statement, and prints it out which will give the following:
http status: 401, code:-1 -
https://api.spotify.com/v1/search?q=weezer&limit=20&offset=0&type=track:
No token provided
That's already a lot more telling than simply a 500 error, right?
I would not recommend this method for every issue in your code, but it's a start.
To learn more about how to debug your code, you can read articles like this.
Anyways:
When I run your code, a spotipy.client.SpotifyException is raised, because the Spotify API returns a 401 error code.
401 (Unauthorized) means you have no authorization to access the requested resource, and for the Spotify API specifically, it means that you'll need to supply a valid token.
You'll need to request a token from the user, and pass that token when initializing spotify like this:
...
sp = spotipy.Spotify(auth=token)
results = sp.search(q='weezer', limit=20)
...
How exactly you get this token from the user depends on the rest of your implementation.
I would recommend reading up on Spotify's authentication flow
There are also plenty of other examples on how people implemented the authorization flow in spotipy, for example in this StackOverflow thread.
Related
I am learning about YELP APIs currently, and want to execute Business Search, but i am stuck with error 400 (HTTP 400 - Bad request). Following online course, my code (runned in virtual environment) should return error 401 (HTTP 401) (and then we provide created yelp app id and key etc.), but i am getting error 400 and can't find a way to solve this, so i get the error 401 and can continue...
Here is my code, it is super-simple and i checked for grammer mistakes and can't find one. I am looking for answer for few hours and really starting lose myself.... Could someone please help me?
import requests
response = requests.get("https://api.yelp.com/v3/businesses/search") # to send GET (to read) request to an endpoint.
print(response)
Outcome when running code:
<Response [400]>
Please let me know what more information you need to help me out. I am a complete beginner here and begging for help.
According to the Yelp documentation, you are required to include query parameters of either (1) location, or (2) latitude and longitude. It looks like your request is missing those parameters.
https://www.yelp.com/developers/documentation/v3/business_search
See below for example:
import requests
response = requests.get("https://api.yelp.com/v3/businesses/search?latitude=37.786882&longitude=-122.399972") # to send GET (to read) request to an endpoint.
print(response)
I am trying to use the google web risk API ( beta) with my python code . Please see the sample code:-
URI='http://www.amazongroupco.org' # bad url
key='key=<mykey>'
threat='&threatTypes=MALWARE'
queryurl='https://webrisk.googleapis.com/v1beta1/uris:search?'
requeststring=queryurl+key+threat
header={"Content-Type":"application/json"}
payload = {'uri':URI }
try:
req = requests.get(requeststring, headers=header, params=payload)
print(req.url)
if (req.status_code == 200):
print(req)
else:
print(" ERROR:",req)
except Exception as e:
print(" Google API returned error:",e, req.url)
The above code always returns successful request status code "Response [200] OK" with an empty jason response {}. The fact that it is an malicious site , I was expecting it to return something in the jason response. I tried it with other malicious sites as well but I get the same response - empty jason object with a status 200 OK.
Am I missing something ?.
I understand that some sites may not have malware but are social engineering sites which is another kind of threattype. Therefore i am wondering if there is an general purpose all-in-all threatTypes attribute I can use which will return a jason object no matter what the threat is as long as it is a Threat.
Just a side note that anyone trying this should have an GCP account to generate a key.
Any guidance here will be much appreciated.
I have also checked the Web Risk API and it works and I have also reproduced your issue and I get the same result. The URL you are checking it is not considered by Google as MALWARE threat. Honestly I have tried various types of threads for that specific URL and it seems that it is not in the Google lists.
Here you can find a list of all the thread types you can use. There is a type for the situation you have described : THREAT_TYPE_UNSPECIFIED , but it returns a error json - invalid argument, always and this is intended behaviour.
I should also note that as it is stated in the official documentation you should use the REST API with the URI encoded :
The URL must be valid (see RFC 2396) but it doesn't need to be canonicalized.
If you use the REST API, you must encode GET parameters, like the URI.
I'm currently having a hard time getting some of my Django tests to work.
What I'm trying to do is test if a given URL (the REST API I want to consume) is up and running (returning status code 200) and later on if it's responding the expected values.
However, all I get returned is a status code 404 (Page not found), even though the URL is definitely the right one. (Tried the exact string in my browser)
This is the code:
from django.test import TestCase
class RestTest(TestCase):
def test_api_test_endpoint(self):
response = self.client.get("http://ip.to.my.api:8181/test/")
self.assertEqual(response.status_code, 200, "Status code not equals 200")
It always returns a 404 instead of a 200...
Anyone knows what I do wrong here?
self.client is not a real HTTP client; it's the Django test client, which simulates requests to your own app for the purposes of testing. It doesn't make HTTP requests, and it only accepts a path, not a full URL.
If you really needed to check that an external URL was up, you would need a proper HTTP client like requests. However this doesn't seem to be an appropriate thing to do in a test case, since it depends on an external API; if that API went down, suddenly your tests would fail, which seems odd. This could be something that you do in a monitoring job, but not in a test.
Soundclouds API is returning 403 on some tracks for me. I have tried playing with the raw http endpoints and also the soundcloud api wrapper for python, both have the issue.
https://api.soundcloud.com/tracks/251164884.json?client_id=CLIENT_ID
The above one returns a 403 error while below one works, using same CLIENT_ID obviously
https://api.soundcloud.com/tracks/197355235.json?client_id=CLIENT_ID
Using the library wrapper I get. requests.exceptions.HTTPError: 403 Client Error: Forbidden
import soundcloud
client = soundcloud.Client(client_id=CLIENT_ID)
track = client.get('/resolve', url='https://soundcloud.com/mtarecords/my-nu-leng-flava-d-soul-shake')
https://soundcloud.com/calyxteebee/nothing-left
Another track that also doesn't resolve. Not all tracks have this issue, most work how they always have.
If you go to the Share -> Embed on Soundcloud the track_id will be in there, so I know I am using the correct track_id.
Viewing the http endpoints in browser I get the error.
Failed to load resource: the server responded with a status of 401 (Unauthorized) - https://api.soundcloud.com/favicon.ico
Anyone else run into this issue before?
Using your two examples I get valid results for both
Example 1:
https://api.soundcloud.com/resolve?url=https://soundcloud.com/calyxteebee/nothing-left&client_id=CLIENT_ID
returns
https://api.soundcloud.com/tracks/251164884?client_id=CLIENT_ID
Example 2:
https://api.soundcloud.com/resolve?url=https://soundcloud.com/mtarecords/my-nu-leng-flava-d-soul-shake&client_id=CLIENT_ID
returns
https://api.soundcloud.com/tracks/249638630?client_id=CLIENT_ID
using this url, working perfectly sir. Try this. :D
https://api.soundcloud.com/tracks/TRACK_ID/stream?client_id=CLIENT_ID
I have been investigating this issue for some time now, and I discovered something which at least solves my situation, dunno if it will solve yours.
The Revelation:
If you do a head request with curl (-I option) then it seems to always return with a 200/300 range response.
Why it works: I am streaming Soundcloud tracks with URLs like https://api.soundcloud.com/tracks/TRACK_ID/stream?client_id=CLIENT_ID in an iOS app using FreeStreamer. The stream was failing on exactly those tracks for which curl -v returned 403 for the tracks URL (it returns 401 for the stream URL). So to solve my situation, I perform a head request which gives 302 Found, extract the mp3 URL, and I use that to stream instead of the original URL.
I consider this a bug of the library (since it should be able to handle any 302) and I created an issue for it.
I am probably overseeing something obvious but I can't seem to figure it. I am trying a simple verification to start with using the following url.
http://myanimelist.net/api/account/verify_credentials.xml
http://myanimelist.net/modules.php?go=api#verifycred
(Here's the full documentation regarding this URL).
This is the code used for testing it out.
class Foobar():
def __init__(self):
pass
def bar(self):
client = requests.get('http://myanimelist.net/api/account/verify_credentials.xml',
auth=(username, password))
if client.status_code == 200:
print "Succesfull authentication. %i"%client.status_code
else:
print "Authentication failed %i"%client.status_code
print client.text
Foo = Foobar()
Foo.bar()
I got a correct response once and assumed this was the right way of going. However from this part on I only receive responses like this.
Every request send regarding the user credentials being correct or not.
I've tried various encoding and neither have affected the response in any way.
EDIT: I seem to have solved the issue. After wiping my cookies and clearing my cache it returned a valid response by status code 401.
The issue causing it was cooking placed by the site itself. I am unsure which cookies specifically caused this problem but once found I will add it.
EDIT: They have a bot checking thrid party connections which bans you upon trying to connect rending their API useless.