How to fix my function to obtain track ID by searching with Spotify API? - python-requests

I would like to obtain the track ID from Spotify by searching with the track name. I have set up my Spotify developer account and am using spotipy. I found people with similar issues (Correct python syntax to search by artist in Spotify's Search API?) but cannot find any major differences between my code and the answers they received.
Here is my function. I am not getting any error messages, but it keeps returning "None." What should I change?
def get_id(track_name:str, token:str) -> str:
headers = {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Bearer {tokenjson}'.format(tokenjson=auth_token)
}
params = {
'q':track_name,
'type':'track'
}
try:
response = requests.get('https://api.spotify.com/v1/search',
headers = headers,
params = params
)
json = response.json()
first_result = json['tracks']['items'][0]
track_id = first_result['id']
return track_id
except:
return None

Related

Python requests_Query_String_Multiple_Values

I am trying to request REST API as below
querystring = {"severity":'medium'}
headers = {"Accept": "application/json"}
response = requests.request("GET", url, headers=headers, params=querystring)
Question:I want to get some data with multiple severity values in query string. As of now I can pass only a single value.After trying querystring = {"severity":['medium','high']} , got only the medium severity events.
Help please.

How to allow Flutter to get a value that it stored in a firebase server or any server?

Right now I am using an http 0.11.3+16 and I am able to add a true value to an item on the site using the following function:
if (newAcceptStatus) {
response = await http.put('https://example.com/example1/${selectedOrder.id}/example2/${_authenticatedUser.id}.json?auth=${_authenticatedUser.token}',
body: json.encode(true));
this function is only called when the admin is logged in and the admin is the only one that can change the status of the Boolean, so the value is stored under the admins id and token. so I tried the following to help show if the item was changed by the admin to the user but i keep getting that the value is null when i decode the response with the following function:
Future<Null> checkAccept() async{
http.Response response;
response = await http.get('https://example.com/example1/${selectedOrder.id}/example2/(admin id goes here).json?auth=${_authenticatedUser.token}');
accepted = json.decode(response.body);
}
not sure what i am doing wrong. any help would be appreciated!
I was calling the wrong list of items which were very similar, thus giving me an empty list

POST data empty ( or not exist ) when I receive post back from TPV provider

I'm trying to implement a service Redsys payments on my .net website.
The payment is successful (data are sent by post) but when the POST data back to my website ( to confirm the payment ) and i try to retrieve them with:
Request.form string value = [ "name"]
the value is always empty
I tried to count how many are in Request.Form.Keys.Count and always gives me zero values.
In the vendor documentation it indicated that the variables may be collected with Request.form [ "name"] and I called them to ask why I do not get the data and they dont know why...so I'm desperate,
What may be due?
I have reviewed the header I get from the server ( width Request.Headers ) and have the following parameters. HttpMethod:: GET Requestype: GET and contentlength: 0 . My bank tell me that they response POST not GET... so it´s a mistery. May be the error is becouse that sendings are made from a https to a htttp ?
You are receiving a POST without parameters.
The parameters are in the content of the call.
You should read the content and get the values of each parameter:
[System.Web.Http.HttpPost]
public async Task<IHttpActionResult> PostNotification()
{
string body = "";
await
Request.Content.ReadAsStreamAsync().ContinueWith(x =>
{
var result = "";
using (var sr = new StreamReader(x.Result))
{
result = sr.ReadToEnd();
}
body += result;
});
In body you can read the parameters (the order of them can change).

.$id retrieves but .name etc doesn't - AngularFire

I am attempting to retrieve data from firabase by getting the $id from routeparams and then syncing as object and retrieving individual pieces of the data with data.(childnamehere). This is successful when retrieving the meta i.e. data.$id but not when retrieving my own data i.e. data.name.. I have reviewed the documentation but can't figure out why I can't console.log (in this case) courseUnique.name ? Any help would be appreciated.
else if (action === "view") {
var courseId = $routeParams.id;
var sync = $firebase(coursesRef.child(courseId));
var courseUnique = sync.$asObject();
var id = courseUnique.$id;
var name = courseUnique.name;
console.log(courseId, courseUnique, id, name);
console output for above is:
-JhgqkeFyfvS9nh5bKyK FirebaseObject {$$conf: Object, $id: "-JhgqkeFyfvS9nh5bKyK", $priority: null, $save: function, $remove: function…} undefined
Sorry for the terse answer, but this one has been covered a ton of times already. I'll provide some links to previous answer in a bit, but for now this code will work:
var courseUnique = sync.$asObject();
courseUnique.$loaded().then(function(courseUnique) {
console.log(courseUnique.name);
})
See:
the AngularFire documentation for the $loaded event
this blog post explaining the $loaded event
this answer explaining why you need this $loaded construct
most of these questions are probably about the same topic

Cant get digest auth to work with node.js

I'm trying to get a simple (!) digest authentication working with node js using an an API from gathercontent.com.
Everything seems to be working except I still get a "Wrong credentials" response that looks like this:
{ success: false, error: 'Wrong Credentials!' }
The code looks like this:
var https = require('https'),
qs = require('querystring');
apikey = "[my api key goes in here]",
pwd = "[my password goes in here]",
crypto = require('crypto');
module.exports.apiCall = function () {
var options = {
host:'abcdefg.gathercontent.com',
port:443,
path:'/api/0.1/get_pages_by_project/get_me',
method:'POST',
headers:{
"Accept":"application/json",
"Content-Type":"application/x-www-form-urlencoded"
}
};
var req = https.request(options, function (res) {
res.on('data', function (d) {
var creds = JSON.parse(d);
var parsedDigest = parseDigest(res.headers['www-authenticate']);
console.log(parsedDigest);
var authopts = {
host:'furthercreative.gathercontent.com',
port:443,
path:'/api/0.1/get_pages_by_project/get_me',
method:'POST',
headers:{
"Accept":"application/json",
"Content-Type":"application/x-www-form-urlencoded",
"Authorization" : getAuthHeader(parsedDigest, apikey, parsedDigest['Digest realm'], pwd)
}
};
console.log(authopts);
console.log('\n\n\n');
var req2 = https.request(authopts, function (res2) {
console.log("statusCode: ", res2.statusCode);
console.log("headers: ", res2.headers);
res2.on('data', function (d2) {
var result = JSON.parse(d2);
});
});
req2.end();
});
});
req.write('id=1234');
req.end();
req.on('error', function (e) {
console.error(e);
});
};
function parseDigest(s){
var parts = s.split(',');
var obj = {};
var nvp = '';
for(var i = 0; i < parts.length; i++){
nvp = parts[i].split('=');
obj[nvp[0]] = nvp[1].replace(/"/gi, '');
}
return obj;
}
function getAuthHeader(digest, apikey, realm, pwd){
var md5 = crypto.createHash('md5');
var s = '';
var nc = '00000001';
var cn = '0a4f113b';
var HA1in = apikey+':'+realm+':'+pwd;
md5 = crypto.createHash('md5');
md5.update(HA1in);
var HA1out = md5.digest('hex');
var HA2in = 'POST:/api/0.1/get_pages_by_project/get_me';
md5 = crypto.createHash('md5');
md5.update(HA2in);
var HA2out = md5.digest('hex');
md5 = crypto.createHash('md5');
var respIn = HA1out + ':' + digest.nonce + ':'+nc+':'+cn+':'+digest.qop+':'+ HA2out;
md5.update(respIn);
var resp = md5.digest('hex');
s = [ 'Digest username="',apikey,'", ',
'realm="',digest['Digest realm'],'", ',
'nonce="',digest.nonce,'", ',
'uri="/api/0.1/get_pages_by_project/get_me", ',
'cnonce="',cn,'", ',
'nc="',nc,'", ',
'qop="',digest.qop,'", ',
'response="',resp,'", ',
'opaque="',digest.opaque,'"'].join('')
return s;
}
I'd try and Curl to it but I'm not sure how!
Any help appreciated!
I see a couple of issues potentially related to your problem. It's hard to tell which ones are the actual culprits, not knowing anything about gathercontent's implementation. If you pasted an example of their 'WWW-Authenticate' header, it would be much easier to provide specific help.
So I'm speculating what the actual cause is, but here are some actual problems that you should address anyway, to conform to the spec (i.e. protect it from breaking in the future because the server starts doing things slightly differently):
in the Authorization headers you are creating, remove the double quotes around nc, and maybe also qop
I don't know what qop value gathercontent is using. If it's auth-int, then you'd also have to append the hashed HTTP body to HA2, see #3.2.2.3 of the spec - furthermore, they might be specifying a comma-separated list of qop values for you to choose from - or the server might not send a value for qop at all, i.e. they use the most basic from of HTTP digest auth, in which your implementation would be violating the spec, as then you aren't allowed to e.g. send a cnonce, nc etc.
you try to get the realm via parsedDigest['Digest realm'], i.e. you are assuming that the realm is the first attribute after the initial Digest keyword. That might or might not be the case, but you should not rely upon it (modify your parseDigest function to strip of the string "Digest " before splitting the rest)
the way you use parsedDigest, you make the assumption that Digest is always capitalized that way, and that realm, nonce, etc. are always in lowercase. According to the spec, these are all case-insensitive
A couple of unrelated issues:
Does the server really force you to use Digest authentication? This is HTTPS, so you might as well do Basic authentication, it's way easier, and with HTTPS, just as safe. (Answering myself here, after checking out gathercontent: Basic auth is apparently not possible)
As mentioned in my comment to your question, cnonce should be random for every request, especially, you shouldn't copy and paste it from Wikipedia, which makes you more vulnerable (but not an issue here, as all data goes over SSL anyway in your case)
Regarding how to curl it - try this:
curl --data 'id=1234' --digest --user "apikey:pwd" https://abcdefg.gathercontent.com:443/api/0.1/get_pages_by_project/get_me
It's Peter from GatherContent.
The first, pretty obvious thing would be to use just get_me instead of get_pages_by_project/get_me. You are mixing two different things in the latter. get_me doesn't require any parameters sent via POST, so you can drop them.
Also, please make sure that your password is always lowercase x.
Does it change anything?
Edit:
For anyone interested, here's our API docs:
http://gathercontent.helpjuice.com/questions/26611-How-do-I-use-the-API
The express-auth module supports multiple authentication schemes, including HTTP Digest. See: https://github.com/ciaranj/express-auth
Another excellent option is passport at: https://github.com/jaredhanson/passport
The http-digest examples in the two modules tend to focus on establishing an authentication for you node.js application vs. forwarding the authentication request to a third-party. However, you should be able to make it work with a little noodling.
If pressed, i would use passport. The examples offered are a lot more clear and documented.
Hope that helps...
I would recomand you to use mikeal's request module it make it a lot easier and cleaner.
Request does not have support for HTTP Auth yet, saddly but you would just have to set the Authorization header.
Try urllib it will work with simple and disgest auth.
See Exemple :
https://stackoverflow.com/a/57221051/8490598

Resources