Spotify: Create Playlist - node.js

Extending https://github.com/spotify/web-api-auth-examples - the code in the authorization_code folder.
It logs out access_token okay, but then hangs at the post request:
app.get('/createPlaylist', function(req, res) {
console.log('access_token=' + access_token)
request.post(
'https://api.spotify.com/v1/users/' + user_id + '/playlists',
{
headers: {
'Authorization' : access_token,
'Content-Type': 'application/json'
},
json: {
"collaborative": false,
"description": null,
// "external_urls": {
// "spotify": "http://open.spotify.com/user/thelinmichael/playlist/7d2D2S200NyUE5KYs80PwO"
// },
// "followers": {
// "href": null,
// "total": 0
// },
// "href": "https://api.spotify.com/v1/users/thelinmichael/playlists/7d2D2S200NyUE5KYs80PwO",
// "id": "7d2D2S200NyUE5KYs80PwO",
"href": null,
"id": null,
"images": [],
"name": "A Generated Playlist",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/1150816110"
},
"href": "https://api.spotify.com/v1/users/1150816110",
"id": "1150816110",
"type": "user",
"uri": "spotify:user:1150816110"
},
"public": true,
// "snapshot_id": "s0o3TSuYnRLl2jch+oA4OEbKwq/fNxhGBkSPnvhZdmWjNV0q3uCAWuGIhEx8SHIx",
"tracks": {
"href": "https://api.spotify.com/v1/users/thelinmichael/playlists/7d2D2S200NyUE5KYs80PwO/tracks",
// "href": "https://api.spotify.com/v1/users/kb8mc65qdvz4lz0gdk0i4ztp3/playlist/46RFjEgbskxglR8rVsu38x/tracks",
"items": [],
"limit": 100,
"next": null,
"offset": 0,
"previous": null,
"total": 0
},
"type": "playlist",
// "uri": "spotify:user:thelinmichael:playlist:7d2D2S200NyUE5KYs80PwO"
}
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
);
});
Any idea what is wrong?
'It looks like your post is mostly code; please add some more details.'
What details StackOverflow? I just wanna know why the POST request hangs.
Modified my code to Kevin's specs ... can't believe I misread output for input ... but it still hangs ... node version v12.14.1
app.get('/createPlaylist', function (req, res) {
console.log('access_token=' + access_token)
request.post(
'https://api.spotify.com/v1/users/' + user_id + '/playlists',
{
headers: {
'Authorization': access_token,
'Content-Type': 'application/json'
},
json: {
name: 'A generated playlist',
public: true,
collaborative: false,
description: 'Generated at ' + Date.now(),
}
},
function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
}
);
});

Comparing your code to the documentation, it looks like the code is sending the JSON output as the input in the example.
To create a playlist, there are only 4 body parameters:
name - string - required
public - boolean - optional
collaborative - boolean - optional
description - string - optional.
I don't know where all the other information is coming from but the API could be hanging up on all of it.
Also be sure you have the right scopes involved with permission to create a playlist for a user.
The request would look trimmed down:
request.post(
'https://api.spotify.com/v1/users/' + user_id + '/playlists',
{
headers: {
'Authorization' : access_token,
'Content-Type': 'application/json'
},
json: {
name: 'A generated playlist',
public: true,
description: 'A playlist generated by JS'
}
}
...

Related

Can't get a succesful jira create issue api response

I am trying to call jira rest api POST /rest/api/3/issue from a node js application. I am getting the following error even though am passing correct details. I am passing issueType as 10103 and remaining sensitive params as required. Here is my
nodejs code.
app.post("/webhook", function(req,res,next){
console.log(req.body);
let options = {
method: 'POST',
url: req.body.tags["jira:endpointURL"]+"/rest/api/3/issue",
auth: {
user: req.body.tags["jira:user"],
password: req.body.tags["jira:token"]
},
headers: {
'Content-Type': 'application/json'
},
json: {
"update": {},
"fields": {
//"summary": req.body["subject"],
"summary": "Test",
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"text": "body",
"type": "text"
}
]
}
]
},
"issuetype": {
"id": req.body.tags["jira:issueType"]
},
"project": {
"key": req.body.tags["jira:project"]
}
}
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(
'Response: ' + response.statusCode + ' ' + response.statusMessage
);
console.log(body);
res.send("OK");
});
});
Error thrown
summary: "Field 'summary' cannot be set. It is not on the appropriate screen, or unknown.",
description: "Field 'description' cannot be set. It is not on the appropriate screen
You have to configure the fields to the screens first.
See:
https://support.atlassian.com/jira-cloud-administration/docs/add-a-custom-field-to-a-screen/
https://support.atlassian.com/jira-cloud-administration/docs/configure-issue-screens/#Configure-a-screen--x27-s-tabs-and-fields

How to show data in React Table with structure {_id:" xx",timestamp:"xx" ,message:"{"temperature:22","humi":45}" }?

React-Table
I have made an axios.get request to the back-end which in turn gives a large data-set from mongodb. The
structure of data returned is :
[
1: {_id: "5dd3be2ecf55e1ec388f502b", timestamp: 1574157870567, message: "{"temperature":58,"humidity":59,"pressure":"1 bar"}"}
2: {_id: "5dd3be2ecf55e1ec388f502a", timestamp: 1574157870067, message: "{"temperature":78,"humidity":79,"pressure":"1 bar"}"}
...
]
I want to show it to react-table.The id and timestamp is being displayed but the temperature and other variable are not being displayed.The message is string.How can I parse such amount of data at back-end to convert message into object?
Back-end code
router.get('/viewData',async(req,res) =>{
collection.find({},{_id:0,timestamp:0}).sort({timestamp:-1}).limit(400).toArray(function (err, resultantData) {
if (err)
throw err;
//var storedDataArray ;
//var gotData=[];
//var index =0;
//storedDataArray=resultantData;
//console.log(storedDataArray)
// storedDataArray.forEach(element => {
// gotData[index]=JSON.parse(element);
// console.log(gotData[index])
// index++;
// })
// console.log(gotData.length);
res.status(200).json(resultantData);
});
Is there any way to show temperature and other quantities in react table?
React-Table
class deviceData extends Component {
constructor(props) {
super(props)
this.state = {
dataList:[],
data : ' '
};
}
componentDidMount(){
const url="http://localhost:5000/api/data/viewData";
fetch (url,{
method: "GET"
}).then(response=> response.json()).then(result=>{
console.log(result);
this.setState({
dataList : result,
});
});
}
render() {
const columns =[
{
Header:"Message ID",
accessor:"_id",
sortable: true,
filterable: false,
style:{
textAlign: "left"
},
width: 300,
maxWidth: 100,
minWidth: 100,
},
{
Header:"Time Stamp",
accessor:"timestamp",
width: 300,
maxWidth: 100,
minWidth: 100,
},
{
Header:"Temperature",
id:'temperature',
filterable: false,
accessor: 'temperature'
},
{
Header:"Pressure",
id:'pressure',
filterable: false,
accessor: 'pressure'
},
{
Header:"Humidity",
id:'humidity',
filterable: false,
accessor: 'humidity'
},
]
return(
<div className="ReactTable">
<ReactTable
columns={columns}
data={this.state.dataList}
defaultPageSize={10}
className="-striped -highlight"
>
</ReactTable>
<div id={"#"+ this.props.id} ></div>
</div>
);
}
}
[![React-Table][1]][1]
Backend Response
[
{
"_id": "5dd3be2fcf55e1ec388f502c",
"timestamp": 1574157871067,
"message": "{\"temperature\":93,\"humidity\":94,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ecf55e1ec388f502b",
"timestamp": 1574157870567,
"message": "{\"temperature\":58,\"humidity\":59,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ecf55e1ec388f502a",
"timestamp": 1574157870067,
"message": "{\"temperature\":78,\"humidity\":79,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2dcf55e1ec388f5029",
"timestamp": 1574157869567,
"message": "{\"temperature\":88,\"humidity\":89,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2dcf55e1ec388f5028",
"timestamp": 1574157869066,
"message": "{\"temperature\":99,\"humidity\":100,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ccf55e1ec388f5027",
"timestamp": 1574157868567,
"message": "{\"temperature\":38,\"humidity\":39,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ccf55e1ec388f5026",
"timestamp": 1574157868067,
"message": "{\"temperature\":82,\"humidity\":83,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2bcf55e1ec388f5025",
"timestamp": 1574157867566,
"message": "{\"temperature\":76,\"humidity\":77,\"pressure\":\"1 bar\"}"
}
]
Convert string back to object by using parse()
ex: var object = JSON.parse(str);
Important thing is to define column with correct accessor. Try this one:
const columns = [
{
Header: "Id",
accessor: "_id"
},
{
Header: "timestamp",
accessor: "timestamp"
},
{
Header: "Temprature",
accessor: "message.temprature"
},
{
Header: "humidity",
accessor: "message.humidity"
},
{
Header: "pressure",
accessor: "message.pressure"
}
];
And Use it in React-table like this:
<ReactTable
data={loans} // Instead of loans, use variable where you store your response
columns={columns}
defaultPageSize={10}
sortable={true}
/>
I think you can try with adding a headers in your fetch method
fetch (url,{
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
}
})
It will ensure your response is JSON
N.B. Try your url with postman first, setting those headers and see whether result is JSON or not, if it is JSON I believe my code will help you, if it is not a JSON return try to change your back-end code to ensure it return JSON using postman

using request-promise to querystring in JSON

I have a big API I want to query for userId and receive its details.
var options = {
uri: 'http://www.theapi.net/0862710324bo0',
method : 'GET',
useQuerystring: true,
qs: {
"must": [
{ "match": { "data.clients.id": req.params.userId }},
]
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
console.log(options.qs.must)
rp(options)
.then(function (repos) {
console.log(repos.clients.name);
res.status(200).json({
data:repos.clients[0].name
})
})...
This code returns:
[
{
match: { 'data.clients.id': 'b2d445-2160-4va7-ref-4edf860bd' }
}
]
undefined (because I didn't specify the object array index)
{
"data": "Sergio"
}
What I need:
{
"id":"ec9c1c4d-ab1a-41b2-bc1a-520b889cdeb9",
"name":"Sergio",
"email":"sergio#jorge.com",
},
I believe adding a "bool" tag would help you out.
var options = {
uri: 'http://www.theapi.net/0862710324bo0',
method : 'GET',
useQuerystring: true,
qs: {
"bool": { // Tag added
"must": [
{ "match": { "data.clients.id": req.params.userId }},
]
}
}
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
console.log(options.qs.must)
rp(options)
.then(function (repos) {
console.log(repos.clients.name);
res.status(200).json({
data:repos.clients[0].name
})
})
Beware - Untested code!
for (const [key, value] of Object.entries(repos.clients)) {
if (req.params.userId === repos.clients[key].id) {
return res.status(200).json({
data:repos.clients[key]
})
}
}

Querystring of a javascript object

I need to make a HTTP GET request but i have some trouble with making a querystring of a javascript object. This is my object.
var params = {
from: {
zip: '42100',
country: 'IT'
},
to: {
zip: '20019',
country: 'IT'
},
packages: [ { "width": 50, "height": 40, "length": 40, "weight": 2 } ]
};
I manually made my querystring and this is the result
from[zip]=42100&from[country]=IT&to[zip]=20019&to[country]=IT&packages[0]=[width]=50&[height]=40&[length]=40&[weight]=2
The problem is that Google says "Your client has issued a malformed or illegal request."
This is my NodeJS script.
var request = require('request');
var params = {
from: {
zip: '42100',
country: 'IT'
},
to: {
zip: '20019',
country: 'IT'
},
packages: [ { "width": 50, "height": 40, "length": 40, "weight": 2 } ]
};
function packagesToQueryString(packages) {
let stringa = "";
for (const onePackage of packages) {
stringa += '[width]='+ onePackage.width + '&[height]='+ onePackage.height +'&[length]='+ onePackage.length +'&[weight]='+ onePackage.weight +'';
}
return 'packages[' + (packages.length - 1) + ']=' + stringa;
}
function paramsToQueryString(obj) {
return 'from[zip]=' + obj.from.zip +'&from[country]=' + obj.from.country + '&to[zip]=' + obj.to.zip + '&to[country]=' + obj.to.country+ '&';
}
const formData = paramsToQueryString(params) + packagesToQueryString(params.packages);
console.log(formData);
request({
headers: {
'Authorization': 'fcd3dda8...2577',
'Content-Type': 'application/json'
},
body: formData,
uri: 'https://api.packlink.com/v1/services',
method: 'GET'
}, function (err, res, body) {
console.log(body);
});
Google error
There are 2 reasons that causes the "malformed or illegal request" error:
In your HTTP request, the Content-Type is defined as application/json. However, the value of body is formData (from[zip]=42100&from[country]=...), which is NOT json.
Even for the formData, your assemble logic is incorrect. For params object, its corresponding query string is: from%5Bzip%5D=42100&from%5Bcountry%5D=IT&to%5Bzip%5D=20019&to%5Bcountry%5D=IT&packages%5B0%5D%5Bwidth%5D=50&packages%5B0%5D%5Bheight%5D=40&packages%5B0%5D%5Blength%5D=40&packages%5B0%5D%5Bweight%5D=2
In order to successfully send that HTTP GET request, you need to use the qs option of request module. The code would look like below:
var request = require('request');
var params = {
from: {
zip: '42100',
country: 'IT'
},
to: {
zip: '20019',
country: 'IT'
},
packages: [ { "width": 50, "height": 40, "length": 40, "weight": 2 } ]
};
request({
headers: {
'Authorization': 'fcd3dda8...2577'
},
qs: params,
uri: 'https://api.packlink.com/v1/services',
method: 'GET'
}, function (err, res, body) {
console.log(body);
});

Unable to create Eventbrite event using API

I am trying to create an event using V3 API. The parameters I am sending are:
var _event = {
"event" : {
"name": {
"html": "Test Event 01"
},
"description": {
"html": "Test Event 01"
},
"start": {
"timezone": "America/Chicago",
"utc": "2017-07-10T18:00:00Z"
},
"end": {
"timezone": "America/Chicago",
"utc": "2017-07-10T20:00:00Z"
},
"currency": "USD"
}
};
This is how I am sending the request using NodeJS:
var request = require('request');
var _headers = {
'Authorization': 'Bearer ' + _token,
'Content-Type': 'application/json',
}
// Configure the request
var options = {
url: EVENTBRITE_API_URL + "events/",
method: 'POST',
headers: _headers,
form: _event
}
I have also tried Content-Type: application/x-url-form-encoded and inside options, JSON.stringify(_event). I also tried to change _event object to:
var _event = {
"name": {
"html": "Test Event 01"
},
"description": {
"html": "Test Event 01"
},
"start": {
"timezone": "America/Chicago",
"utc": "2017-07-10T18:00:00Z"
},
"end": {
"timezone": "America/Chicago",
"utc": "2017-07-10T20:00:00Z"
},
"currency": "USD"
};
I have tried all the combinations but I always get the same response:
{
"status_code": 400,
"error_description": "There are errors with your arguments: event[currency] - Unknown parameter, event.start.timezone - This field is required., event.currency - This field is required., event.start.utc - This field is required., event[start][timezone] - Unknown parameter, event.end.utc - This field is required., event[end][utc] - Unknown parameter, event[description][html] - Unknown parameter, event[name][html] - Unknown parameter, event[end][timezone] - Unknown parameter, event[start][utc] - Unknown parameter, event.end.timezone - This field is required., event.name.html - This field is required.",
"error": "ARGUMENTS_ERROR"
}
Is there any sample create event request anywhere I can look into? What is the problem with above request?
I think the issue is that you're currently sending a form post (by virtue of using the form option), but then your parameters should look like { "event.currency": "USD", "event.name.html": "Test Event 01", ... }. If you want to send JSON, you need to use json: true and pass a JSON-serializable body:
var request = require('request');
var _headers = {
'Authorization': 'Bearer ' + _token,
'Content-Type': 'application/json',
}
// Configure the request
var options = {
url: EVENTBRITE_API_URL + "events/",
method: 'POST',
headers: _headers,
// Instead of this:
// form: _event
// use this:
json: true, // says you're sending JSON
body: _event, // so the body should be JSON-serializable
};
If you want to stick with a form post, I think this should do it:
var _event = {
"event.name.html": "Test Event 01",
"event.description.html": "Test Event 01",
"event.start.timezone": "America/Chicago",
"event.start.utc": "2017-07-10T18:00:00Z",
"event.end.timezone": "America/Chicago",
"event.end.utc": "2017-07-10T20:00:00Z",
"event.currency": "USD",
};
var request = require('request');
var _headers = {
'Authorization': 'Bearer ' + _token,
'Content-Type': 'application/x-www-form-urlencoded',
}
// Configure the request
var options = {
url: EVENTBRITE_API_URL + "events/",
method: 'POST',
headers: _headers,
form: _event,
};

Resources