Search for artist id by name - javascript

I am delving into spotify and javascript is not my main programming language so I managed to get some snippets together from a code that uses ajax (which I would rather not use) but still it returns nothing so I am wondering if some more experienced people out there could help me get started with a template to call the api.
My goal for this test is to search an artist name and get the first result (I expect many names will return multiple artists)
Most of what is in the documentation is curl and I didn't find the demos very helpful.
What I have so far is something like this:
function getArtistName (artistName) {
var artistID;
var searchArtists = function (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: query,
type: 'artist',
'accessToken': 'BQBvW70gHJ20Flc8cHErqg8s72bfTePbssblED-gpEuHFr_Yezesbthok8qaKBmjzo2WjWo9J7ZcTpSwvV8MZ_cW_E7UkrG_HF2R6gFQcqfdupgYGmoYsdRdt1q3tq2NU3pPgauuzmFLkUpdAuNp3shdVXJz2SzvnA',
'query': artistName,
limit: '1.'
},
success: function (response) {
//resultsPlaceholder.innerHTML = template(response);
}
});
};
console.log(searchArtists);
return artistID;
}
Some points of confusion:
The key seems to expire. I have a client ID on my profile but I am not sure where I can generate this token other than the "try it out" demo on the site.
What does this actually return, an ID or a JSON?

Here is a demo app that searches tracks using Node.js, or server-side Javascript: https://spotify-quicksearch.glitch.me/
If you click the "Remix this on Glitch" link on the page, you can see and edit the source.
The call to the API is made in server.js. First, we set the client ID and client secret, which are from the dashboard, as you've noted. In this example, we use those to get an access token using the Client Credentials Flow. You can read about all the authentication flows here: https://beta.developer.spotify.com/documentation/general/guides/authorization-guide/
This particular example uses an API wrapper called spotify-web-api-node, which just makes it easier to interact with the API through Javascript functions. To search for artists instead, just change searchTracks to searchArtists.
To answer your second question - all calls to the Spotify API return JSON. You can see the format of the full JSON response here: https://beta.developer.spotify.com/documentation/web-api/reference/search/search/. Roughly, it looks like this:
artists: {
items: [
{
id: <id>,
name: <name>,
...
}
...
]
}
To get the ID from the JSON, you need to parse the JSON object. You can see how I do this in the example in line 21 of client.js. You can modify that code to get just the ID of the first artist like this:
data.artists.items[0].id
Update: made an example that should be even more relevant:
https://spotify-search-artist.glitch.me/

Related

How to use 'find' in Google Sheets API (Cocos Creator)

I am using Cocos Creator to build a web app that will communicate with google sheets.
I didn't manage to find a suitable client library (as highlighted in below link)
https://discuss.cocos2d-x.org/t/integrating-google-sheets-api/47920
And decided to go with the REST api using http requests.
However, I am unable to find documents that show exactly how to perform the requests i need.
UPDATE:
Updated the title as I realized my previous approach of condition check is meant for filter views, which i misunderstood it's use case.
However, i saw this video showing that you can use the 'find' function that will return the cell grid, which is exactly what i'm looking for.
https://youtu.be/yPQ2Gk33b1U?t=348
I would like to know how to construct the request string to perform this call on the REST api using http request.
Previously:
As the title says, I need a condition check to for searching my sheet and return the cell that has the exact match for a given string.
This link documents that such conditions exist but does not show how to execute it with http request
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other
I've found this post that is performing something very similar to what I wish to request, using FilterCriteria and Condition.
Looking for examples how to use the Google Sheets API FilterCriteria object
However, he is using the C# client library but is there any that I can use for Cocos Creator? As such, I have to perform this with REST using Http Request, and I have no leads on how to construct the request string.
var http = require('http');
var obj = {
'key' : 'MY_API_KEY'
}
var filters = {
'dataFilters': [
{
'Condition' : {
'type' : 'TEXT_EQ',
'values' : [{ 'userEnteredValue' : 'string_to_match' }]
},
}
]
}
var filtersStr = JSON.stringify(filters);
http.Get('MY_GOOGLE_SHEET_ID:getByDataFilter' + filtersStr, obj, function(responseJson)
{
console.log(responseJson);
});
Above code is something i attempted, but you bet it is not working.

How can I retrieve data from firebase database by its value in Web App?

I am making a complaint portal and I want to assign id to the people who register.
My data structure in firebase like below:
fir-web-learn-51ffc
complaint
-Kwe6QXol8DV-uMDxIe7:"Hiii"
-KweCaYQrgG75BiJW3dA:"Hooooo"
and I have used this code for insertion:
function submitClick()
{
var complaint=document.getElementById('complaint').value;
var database=firebase.database().ref().child("complaint");
database.push().set(complaint);
}
for the above code, How can I retrieve the Name(Kwe6QXol8DV-uMDxIe7) by its value(Hiii). I have tried the code given on Google Firebase Documentation and Youtube but didn't work.
You'll use a Firebase query for that with orderByValue. So something like this:
var ref=firebase.database().ref().child("complaint");
ref.orderByValue().equalTo("Hiii").once("value", function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key);
});
});
Aside from the query itself, the main thing to note is the snapshot.forEach() in the callback. This loop is needed since a query can potentially match multiple results.

How to filter a displayed JSON file

I'm trying to make a web application using Outlook API's that allows me to search for a specific Outlook contact by his name.
I've got a little knowledge of javaScript but i never used any API or manipulated JSON files beforehand, so i looked through tutorials to help me, and
I ran into this one : https://dev.outlook.com/restapi/tutorial/javascript which i followed and succeeded to implement without much trouble.
Briefly, the tutorial allows me to build an app that can display the last 10 emails from the user, or the contact list of this user, which gives something like that :
Contacts displayed
Now what i'm trying to do is to filter this display and be able to search something like " give the contacts which name contains the syllable "AG" ".
I tried to understand the code as much as i can and i'm almost sure that i have to modify the function displaying all the contacts.
So what i did is that i pasted it, renamed it but now i'm struggling with the query parameters.
function getUserContacts(emailAddress, callback) {
getAccessToken(function(accessToken) {
if (accessToken) {
// Call the Outlook API
var callOptions = {
// Get contacts
url: apiEndpoint + '/Me/contacts',
token: accessToken,
method: 'GET',
email: emailAddress,
query: {
// Limit to the first 100 contacts
'$top': 100,
// Only return fields we will use
'$select': 'GivenName,Surname,EmailAddresses',
// Sort by given name alphabetically
'$orderby': 'GivenName ASC'
}
};
makeApiCall(callOptions, function(result, error) {
if (error) {
callback(null, error);
} else {
callback(result.value);
}
});
} else {
var error = { responseText: 'Could not retrieve access token' };
callback(null, error);
}
});
}
And that's the moment i get totally lost, i tried adding '$where':GivenName='AG' in the query{} section, as well as '$filter':GivenName='AG', but neither of them worked. I searched online for an answer but in every one i founded, the JSON file was "available" ( meaning for me that they have,somewhere this kind of code :
[
{"name":"Lenovo Thinkpad 41A4298","website":"google222"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"}
]
But i don't have this type of code anywhere, so i'm wondering if it is possible to do it like i tried to, or if i have to find a way to retrieve the JSON file in order to obtain something like just above ?
I hope i've been clear enough despite my lack of experience in this field, i'd be glad to give some more details/codes if you ask too !
Thanks in advance and have a great day :)
Thanks to Useless Code and his link i managed to send the right request (error was coming from the fact that filter properties must be listed first in the orderby) from the outlook sandbox and get the expected answer with this URL:
https://outlook.office.com/api/v2.0/me/contacts?$filter=GivenName eq 'AG-Carto'&$orderby=GivenName ASC&$select=GivenName,Surname,EmailAddresses
Now what i'm trying to do is to get my javascript code to send it right.
So i know i have to modify the query{} part of the function, i tried this :
query: {
'$filter': 'GivenName eq AG-carto',
'$orderby': 'GivenName ASC',
'$select': 'GivenName,Surname,EmailAddresses'
}
But when i run it, i got a bad request error, and i see that the url sent by the js code is this one :
https://outlook.office.com/api/v2.0/Me/contacts?%24filter=GivenName+eq+AG-carto&%24orderby=GivenName+ASC&%24select=GivenName%2CSurname%2CEmailAddresses
So i'm obviously seeing that they aren't the same, and i have no idea on how to modify the query{} section so that the URL sent by js is the same as my working URL. If anyone could help me on that i'd be grateful !

javascript - make facebook page post

I am not using the Javascript SDK because that is client-side whereas I'm making a server-side call.
I want to make a page post so that I can make an ad creative with it. I can do the call perfectly fine in the Graph API Explorer tool, but I cannot make the same call (with the same long-lived access tokens that continue to work in the Graph Explorer) from Javascript. Here is my code:
tok = <valid and never expiring user token>;
var pg_tok = <valid and never expiring page token>;
var act_id = <account_id>;
var pg_id = <page_id>;
var call_to_action = 'INSTALL_MOBILE_APP';
var fb_app_url = 'https://itunes.apple.com/us/app/id284882215';
var msg = 'Test creative, ya see';
var pic_url = 'https://s3.amazonaws.com/<path_to_my_image>';
var ROOT = 'https://graph.facebook.com/';
var pagepost_endpoint = ROOT+pg_id+'/feed';
console.log(pagepost_endpoint);
var pagepost_params = {
access_token: pg_tok,
call_to_action: {
type: call_to_action,
value: {link: fb_app_url}
},
message: msg,
picture: pic_url,
published: false
};
console.log(pagepost_params);
var pagepost_res = HTTP.post(pagepost_endpoint, {params: pagepost_params});
console.log(pagepost_res);
I have played around a bunch with params vs. data for where pagepost_params goes in the HTTP.post that is giving the error (that is Meteor's HTTP btw).
-Putting everything in params gives the error: {"error":{"type":"Exception","message":"No Call To Action Type was parseable. Please refer to the call to action api documentation","code":1373054,"is_transient":false}}.
-Putting everything in data gives the error: {"error":{"message":"(#200) This API call requires a valid app_id.","type":"OAuthException","code":200}}.
-Putting access_token in params and everything else in data gives the error: {"error":{"message":"Invalid parameter","type":"FacebookApiException","code":100,"error_subcode":1349125}}.
One more clue for everyone, if I change the HTTP.post to HTTP.get, and just put access_token in params and include no other parameters (in params or in data), the call succeeds and I see past posts I have made on this page through the Graph Explorer (only the ones with published: true, though), so the access token and endpoint do work, just something is faulty about POST-ing instead of GET-ing and the specific parameters I'm using.
Have you tried posting to /photos instead of /feed? The error subcode is the same as mentioned here Posting to facebook wall using graph api
Hope this helps
Turned out to be an issue with Meteor's HTTP. It does not handle nested JSON very well, and we're going to submit a pull request for that. But for those seeing this, the important thing to take away is that the call_to_action may not be a valid JSON object, and even if it is, it may not be being stringified/parsed as expected. My fix was using request.post instead of HTTP.post. (then instead of params or data, you use form. look up node's request https://github.com/mikeal/request)

Is it possible to use the Yahoo BOSS OAuth with JavaScript only?

Here is the problem, I have a Google Chrome extension and I want to use the BOSS API in it. The problem is that I do not know if it is possible to use the API without a webserver running.
The documentation does not provide any example using JavaScript. Thus my question:
Is it possible to use the Yahoo BOSS OAuth with JavaScript only?
Probably not...
All the examples Yahoo provides are using server side languages
http://developer.yahoo.com/boss/search/boss_api_guide/codeexamples.html
First you'd have to figure out how to use OAuth with JavaScript, and how will you obscure your API keys from users in a JS File? If you don't have to worry about that, say you are just using this for personal use. Maybe check out the code sample for Node.JS and modify it for your own uses.
http://developer.yahoo.com/boss/search/boss_api_guide/codeexamples.html#oauth_js
function yahooSearch(consumerKey, consumerSecret, query, count,
callback_error_data_response){
var webSearchUrl = 'https://yboss.yahooapis.com/ysearch/web';
var finalUrl = webSearchUrl + '?' + qs.stringify({
q: query, //search keywords
format: 'json',
count: count,
});
var oa = new OAuth(webSearchUrl, webSearchUrl, consumerKey, consumerSecret, "1.0", null, "HMAC-SHA1");
oa.setClientOptions({ requestTokenHttpMethod: 'GET' });
oa.getProtectedResource(finalUrl, "GET", '','', callback_error_data_response);
}
// Use this function to make a call back. Make sure to provide the right key, secret and query for this to work correctly yahooSearch('YAHOO CONSUMER KEY GOES HERE', 'YAHOO CONSUMER SECRET GOES HERE', 'SEARCH QUERY', 10, function(error, data, response){
// enter some code here and access the results from the "data" variable in JSON format
});
You can go to YQL Console and then enter your request, you can select Json or XML, after your result is fetched, look at the bottom of the page and then copy the url. You will be able to use that url inside script tags in an html doc and run it with your browser without a server.

Categories