Spotify API Error Code 400 - No Search Query - javascript

I am trying to use the Spotify API search function to recieve album data. This my request:
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
// use the access token to access the Spotify Web API
var token = body.access_token;
var options = {
url: 'https://api.spotify.com/v1/search',
data: {
q: 'currents',
type: 'album',
},
headers: {
'Authorization': 'Bearer ' + token
},
json: true
};
request.get(options, function(error, response, body) {
console.log(body);
});
}
});
However, when this code executes I continually get an Error Code 400 - "no search query" response. Can anyone help spot why this my query options are not being properly read?
Thanks.

Solved: The request library requires a querystring object called qs in the options object. Changing "data" to "qs" fixed it.

Related

Why is this nested request not running in Node.js with Spotify API?

I am using the authorization code flow to have a user log in and allow me to access and create playlists on their account. I have followed along with the docs and I am now trying to read the users playlists but my nested request is not running. Here is my code:
request.get(options, function(error, response, body) {
console.log(body);
if(response){
request.get({url: 'https://api.spotify.com/v1/users/'+body.id+'/playlists',
headers:{ 'Authorization': 'Bearer ' + access_token },
function(error, res){
//var playlists = JSON.parse(response.body);
console.log("this code runs");
}
})
}
});
As of now I retrieve the the users id, which does log to the console, and then pass the user's id to the next endpoint but the second request is not running. I am using this endpoint.
The reason this is not working is because I passed the function as a property in the options object instead of the second argument. Here is the fixed code:
request.get({
url: 'https://api.spotify.com/v1/users/' + body.id + '/playlists',
headers: { 'Authorization': 'Bearer ' + access_token }
},
function (error, response, body) {
//var playlists = JSON.parse(response.body);
console.log("this code runs");
}
)

how to pass value in api body in protractor while requesting the api

I want to pass the value in API request body.
I tried below code for that
var options = { method: 'POST',
url: 'https://ssgpreprod.serviceurl.in/gonogo-api/atm/tw/cro-approval',
headers:
{ 'Postman-Token': '9d6a0ad1-c3a1-402f-b845-b6416f49df6b',
'cache-control': 'no-cache',
'Content-Type': 'application/json' },
body:
{ oHeader:
{ sReqType: 'application/json',
sAppSource: 'WEB 2.02.01',
sSourceID: 'GONOGO_HDBFS',
sAppID: 610961419000670,
dtSubmit: '',
sCroId: 'HDB_TW_CRO#cell.com',
sDsaId: 'default',
sInstID: 4019,
sUserName: 'CHDBTWCRO',
sProduct: 'TW',
sDealerId: '61096' },
sRefID:testData.twPreIpa.twReferenceId,
sAppStat: testData.twCroDetails.twCroDecision,
aCroJustification: [ { sRemark: testData.twCroDetails.twRemark, sSubTo: testData.twCroDetails.twSubjectTo} ],
bApprAmtExist: true,
dApprAmt: testData.twApplyDetails.twLoanAmount,
dItrRt: testData.twCroDetails.twRoi,
dLtv: testData.twCroDetails.twLtv,
aDedupeRefID: [] },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
browser.logger.info(JSON.stringify(body));
browser.logger.info(JSON.stringify(response));
browser.logger.info('status code is : ' + response.statusCode);
expect(response.statusCode).toBe(200).then(function () {
browser.logger.info('case is approved');
this.logOut(testData);
})
});
I am passing value from xlsx file i.e testData.twPreIpa.twReferenceId but I am getting 422 status code and below output
[2019-05-28 15:42:10.403] [INFO] : - {"title":"Conversion Failed","status":422,"detail":"The content you've sent is probably malformed."}
Also, when I add - browser.logger.info('approved'); above var options it prints on console.. but when I add - browser.logger.info(testData.twPreIpa.twReferenceId);
It gives me error .. ouput displayed -
Failed: Cannot read property 'twReferenceId' of undefined
TypeError: Cannot read property 'twReferenceId' of undefined
While this may not directly answer your question it should be helpful to you.
I worked on a similar framework to what (I assume) yours looks like,some api and some UI validations.
I had a separate class for my API calls which returned some value, sometimes the entire response body. I allowed myself the ability to pass in whatever body I needed as a parameter.
This is an example of the approach I took.
module.exports = class Endpoints {
addSomethingToUser(bearerToken, userId, JSONbody) {
//Function will preform a POST request and return the status code if successful
//Else if will return the body of the response
let endpoint = 'http://myApp.com:9090/api/users/' + userId;
return new Promise((resolve, reject) => {
let options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
},
body: JSON.stringify(JSONbody),
};
request(
endpoint,
options ,
function (error, response, body) {
if (!error && (response.statusCode >= 200 && response.statusCode < 300)) {
resolve(response.statusCode);
} else {
console.log('error:', error, response && response.statusCode);
reject(JSON.stringify(response, undefined, 2));
};
}
);
});
};
}
It is called like
let apiCallsFile = require('../apiCalls/restCalls');
let apiCalls = new apiCallsFile();
it('simple test', async function(){
let requiredBody = {
"NAME": "Test Name",
"GENDER": "MALE",
};
let apiResult = await apiCalls.addSomethingToUser(bearerToken, userId, requiredBody );
expect(apiResult).toBe('201');
}
Your issue seems to be related to the actual values you are using from excel. You should attempt to print out your values before attempting to send the request to ensure they are all present and in the format you expect.

Node post request is getting unauthorized server status but client fetch api is not

When making the following fetch request on my front-end I'm getting my desired type and id values.
export const getUserProfile = () => {
return (
fetch(
"https://api.spotify.com/v1/me", {
headers: {"Authorization": "Bearer " + user_id}
})
.then(response => {
return response.json()
})
.then(data => {
console.log(data.type)
console.log(data.id)
})
)
}
Knowing you can't use fetch api in Node I used the npm install request package to get the data on my node server.
request.post(authOptions, function(error, response, body) {
var access_token = body.access_token
let postInfo = {
url: 'https://api.spotify.com/v1/me',
headers: {
"Authoriztion": "Bearer " + access_token
},
json: true
}
request.post(postInfo, function(error, response, body) {
const route = body.type
const current_user_id = body.id
console.log(body)
let uri = process.env.FRONTEND_URI || `http://localhost:3000/${route}/${current_user_id}`
res.redirect(uri + '?access_token=' + access_token)
})
})
The purpose of doing this is so when the res.redirect gets called it sends the client to the user's home page. However when the client gets redirected the url is http://localhost:3000/undefined/undefined?accesss_token={some token}
when looking why the values are undefined I console.log(body) and I get
{
error: {
status: 401,
message: 'No token provided'
}
}
but I can see when logging the response that the token is included
_header: 'POST /v1/me HTTP/1.1\r\nAuthoriztion: Bearer {some token}=\r\nhost: api.spotify.com\r\naccept: application/json\r\ncontent-length: 0\r\nConnection: close\r\n\r\n'
I can see why my values are undefined but why am I getting an unauthorized status in node but not on the client using fetch api? Also I noticed that the url access_token doesn't match the server logged token.
Here are the docs I'm using:
https://www.npmjs.com/package/request
https://developer.spotify.com/documentation/web-api/reference/users-profile/get-current-users-profile/
Github file: https://github.com/ryansaam/litphum-server/blob/master/server.js
If you use node-fetch in your server code, you have a similar API as fetch.

Problem with Github-Api v3 using JavaScript

For a homework (in Signavio Workflow Accelerator) I need to add users to an organization on Github using the GitHub-API v3. The Code has to be written in JavaScript which i a language I'm not very familiar with.
At the moment I get the following error code: "SyntaxError: Unexpected token o in JSON at position 1 at Request._callback". So I have the feeling that there might be a problem with the parsing.
var link = 'https://api.github.com/orgs/myorganization/memberships/' + githubUser
var token = 'mytoken'
request({url: link, method: 'put', headers: {'User-Agent': 'request'}, auth: {username: token}, JSON: true},
function (response, body) {
console.log(body)
if(body !== undefined){
body = JSON.parse(body)
body['state'][0]['main']
status = body['main']['state']
status = body.main.state
}
else{
status = 'error'
}
})
I don't know if this might be helpful, but if I perform this put request using cURL it works and the answer starts with:
{
"url": "https://api.github.com/orgs/myorganization/memberships/githubUser",
"state": "pending",
...}
So this "state" is the value I want to read in the code above.
Already thanks for helping!
I worked together with a friend of mine and together we found a working solution. So if anyone else is having the same struggle: This piece of code does the magic!
var link = 'https://api.github.com/orgs/myorganization/memberships/' + githubUser
var token = 'mytoken'
const options = {
url: link,
method: 'put',
headers: {'User-Agent': 'request'}, auth: {username: token}
}
function callback(error, response, body) {
console.log(error)
if(!error && response.statusCode == 200){
const info = JSON.parse(body)
status = info['state'][0]['main']
console.log(status)
status = info['state']
status = info.state
}
console.log(body)
}
request(options, callback)

Javascript REST API - You must specify an API key to make request

I get a 403 "You must specify an API key to make request" when trying to get data from a 3rd party API (Klaviyo).
const { id } = req.body
request.get({
url: `https://a.klaviyo.com/api/v1/person/${id}`,
headers: {
api_key: process.env.KLAVIYO_API_KEY
}
}, (error, response, body) => {
const profile = JSON.parse(body)
console.log(profile)
if (response.statusCode === 200) {
res.json({ profile, status: 201 })
} else {
res.json({ error: 'Did not get customer data', status: 500, response: response, err: error })
}
})
I've also tried with:
headers: {"Authorization": [API_KEY]}
data: {api_key: [API_KEY]}
Solution:
const { id } = req.body
request.get({
url: `https://a.klaviyo.com/api/v1/person/${id}`,
qs: {
api_key: process.env.KLAVIYO_API_KEY
}
}, (error, response, body) => {
const profile = JSON.parse(body)
console.log(profile)
if (response.statusCode === 200) {
res.json({ profile, status: 201 })
} else {
res.json({ error: 'Did not get customer data', status: 500, response: response, err: error })
}
})
Short answer: add it under params.api_key (as part of the GET request).
From the klaviyo documentation:
"You authenticate to the People API by providing one of your private API keys as part of each request. (...) Authentication happens via the api_key parameter in each request. It can be sent as part of the GET or POST parameters."
I think you are using GET request with POST header method. In GET you need to put it in URL

Categories