I'm trying to use the Spotify Web API to search for songs through node, but it keeps sending me a status 400 error with the message: "Only valid bearer authentication supported". This is my code:
app.get("/", (req, res) => {
let searchurl = "https://api.spotify.com/v1/search?";
request.post(
{
url: searchurl,
data: {
q: "john",
type: "album",
},
headers: {
"Content-Type": "application/json",
Authorization:
"Basic " +
Buffer.from(client_id + ":" + client_secret).toString("base64"),
},
method: "POST",
},
function (e, r, body) {
console.log(body);
}
);
});
I don't understand what the issue is and have read through everything I could find, but got nowhere. Am I supposed to use a different access key?
Have a look at the Authorisation Guide for Spotify, you can use the Client Id and Client Secret to get an Access Token and it is that you send as part of an Authorization header when making the request to the Search for an Item endpoint you're trying to use
Related
I am unable to add new clients using the Clockify API in Node js. The following axios post request returns the error message: 'Full authentication is required to access this resource'. However, I am able to get a list of clients using the axios.get() method with the same API key, so I'm not sure why the post request says I'm not authenticated. Please let me know what I'm missing
async function addNewClient(clientName) {
return response = await axios.post(`${url}/workspaces/${workspaceId}/clients`, {
data: {
'name': clientName
},
headers: {
'X-Api-Key': CLOCKIFY_API_KEY,
'Content-Type': 'application/json',
},
}).catch(function (error) {
console.log(error.response.data.message);
return
});
}
I had the same issue. Regenerating API_KEY solved it.
When requesting 'organic_metrics' field in Twitter v2 API search endpoint I am getting the following: "Field Authorization Error"
This is my request script in Nodejs
function requestSearch (keyword) {
const search = {
method: 'GET',
uri: 'https://api.twitter.com/2/tweets/search/recent',
headers: {
"User-Agent": "v2RecentSearchJS",
"authorization": `Bearer ${process.env.TWITTER_BEARER_TOKEN}`
},
qs: {
query: "context:66.1001503516555337728 context:66.857879456773357569" // `entity: ${keyword}`
},
json: true,
gzip: true
};
const params = {
"ids": "1397885797957738496", // Edit Tweet IDs to look up
"tweet.fields": "context_annotations,entities,organic_metrics", // Edit optional query parameters here
"user.fields": "created_at" // Edit optional query parameters here,
}
const lookup = {
method: 'GET',
uri: 'https://api.twitter.com/2/tweets',
headers: {
"User-Agent": "v2RecentSearchJS",
"authorization": `Bearer ${process.env.TWITTER_BEARER_TOKEN}`
},
qs: params
}
return rp(lookup)
.then(response => {
// console.log('API call response:', response);
return response
})
.catch((err) => {
console.log('API call error:', err.message);
});
}
According to the Twitter documentation:
Public metrics can be requested with OAuth 2.0 Bearer Token authentication. Non-public metrics can be requested for owned/authorized Tweets only. This means developers are required to authenticate using OAuth 1.0a User Context authorization. If you need to generate an access token and secret for the Tweet owner, you can do so with the 3-legged OAuth process.
[...]
Organic metrics: Grouping of public and non-public metrics attributed to an organic context (posted and viewed in a regular manner). Requires OAuth 1.0a User Context authentication.
In this case, you are using a Bearer Token to access the API, so you will not be able to access the organic metrics (this is what the "Field Authorization Error" message is telling you). You could use the public_metrics field instead.
I have a node server which gets an access token from Spotify's Web API. The response looks like this:
Response:
{
"statusCode": 200,
"body": "{\"type\":\"success\",\"done\":{\"json\":{\"access_token\":\"BQDqtYhVpafUIMYtZbwmy6iJcC_wvzR9Xrw6bRDFfpL3zZYfkCp2-KZaQVS-ZoElMF1czAl_B1vEaDrtPBOElSV3D5k\",\"token_type\":\"Bearer\",\"expires_in\":3600,\"scope\":\"user-top-read\"}}}",
"headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token"
}
}
When I try to use the access_token on Spotify's online API tool, I get an error for incomplete JSON. I think this is because the token I generate is only 91 characters long while the code they generate is 171 characters long. Why is my auth code so short?
I want an access token so I can use this react module for accessing my top tracks.
Here is my code for getting the access token:
let getAccessToken = (queryStringParameters) => {
let url = 'https://accounts.spotify.com/api/token';
let encoded = (new Buffer(client_id + ':' + client_secret).toString('base64'));
console.log("encoded = " + encoded);
let params = {
grant_type: 'authorization_code',
username: username,
password: password,
scope: scope
};
const formParams = Object.keys(params).map((key) => {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
return fetch(url, {
method: 'POST',
headers: {
"Authorization": 'Basic ' + encoded,
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formParams
})
.then((response) => {
console.log(util.inspect(response, { showHidden: true, depth: null }));
return response.json();
})
.catch((error) => {
done({
error: error
});
});
};
According to the Authorisation Guide the authorization_code grant type only takes the code and redirect URI values. Not sure why the username and password ones you provide are even accepted, it is possible the token returned is a client credentials one as those tend to be shorter, that only access non-user related endpoints like loading Artist data, but the parameters you're providing appear to be undocumented at least in that guide.
I am trying to build a web app that integrates with the spotify API. For this, I am using the Authorization grant flow.
I managed to get an authorization code, but on the back end when I am testing the endpoint that should exchange the auth code with an access token, I keep getting a 415 response status.
Here is the service that the endpoint is using:
export async function getAccessAndRefresh(code: string): Promise<any> {
return axios.post(ACCESS_URL, {
data: {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": REDIRECT_URI
},
headers: {
"Authorization": " Basic " + Buffer.from(CLIENT_ID + ":" + CLIENT_SECRET).toString("base64"),
"Content-Type": "application/x-www-form-urlencoded",
},
method: "POST",
json:true
})
}
Also, I wrote this unit test in order to test the service(I got the 415 while running this unit test):
describe("Request tests", () => {
let server: Server;
function initServer() {
server = createServer(App);
server.listen(5000);
}
function destroyServer() {
server.close();
}
test("Test refresh and access token returned by spotify api", () => {
return getAccessAndRefresh(AUTH_CODE).then((value)=>{
expect(value).toHaveProperty("access_token");
})
})
beforeAll(() => {
initServer();
});
afterAll(()=>{
destroyServer();
})
})
In the test, AUTH_CODE is a code that I obtained manually in a browser by accessing the https://accounts.spotify.com/authorize endpoint with my API Key.
Can anyone help me figure this one out please? Thanks!
In the Spotify Dashboard you might need to set the Redirect URI to the URL you're using in your code, these need to match if getting the following error:
{ "error": "invalid_grant", "error_description": "Invalid redirect URI" }
That's all you need to do, just go to the Dashboard where you get the Client ID and Client Secret and then go to the Edit Settings and you'll see the option to set the Redirect URI
I've registered as the Web app as required by the Reddit API for the Oauth access with identity, edit, flair, history, modconfig, modflair, modlog, modposts, modwiki, mysubreddits, privatemessages, read, report, save, submit, subscribe, vote, wikiedit, wikiread scopes.
I'd authorized my app and have exchanged the generated code for the access_token with 3600 seconds validity.
'use strict';
let request = require('request');
const USER_AGENT = 'web:com.example.server:v0.0.1 (by /u/sridharrajs)';
const token = '<my access_token within 3600 seconds validity>';
request({
method: 'POST',
url: 'https://www.reddit.com/api/vote',
headers: {
'User-Agent': USER_AGENT,
'Authorization': `bearer ${token}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
id: "t1_9qy47p",
dir: "1"
},
json: false
}, function (error, response, body) {
if (error) {
console.log('error', error);
} else if (body.error) {
console.log('body.error', body);
}
return console.log(body);
});
But when I try to upvote a reddit submission using API, I get an error.
{"message": "Forbidden", "error": 403}
The link that I'm trying to upvote is Tim Cook warns of ‘data-industrial complex’ in call for comprehensive US privacy laws
I tried switching both bearer and Bearer as per the answer in Reddit API returns HTTP 403, and tried using different User-Agent as suggested in 403 error when trying to get data from Reddit API. Nothing seem to work.
What am I missing?
Solved. I need to use https://oauth.reddit.com instead of www.reddit.com.
You may now make API requests to reddit's servers on behalf of that user, by including the following header in your HTTP requests:
Authorization: bearer TOKEN
API requests with a bearer token should be made to https://oauth.reddit.com, NOT www.reddit.com.