Unable to create Eventbrite event using API - node.js

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,
};

Related

Spotify: Create Playlist

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'
}
}
...

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);
});

Using Request to post from NodeJS

I am running into an issue with posting a json doc via request from my nodeJs app.
The problem is for me how to pass the json doc to post. Here is what works for me
const options = {
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,
body: { "message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "html",
"content": "</p>\r\n\r\n<ul type=\"disc\">\r\n\t<li><strong>Ready to Use Experiences</strong> – Get instant access to our fully configured and integrated environments allowing you to use and experience the products as a customer would in their own deployment. We’ve set up the products alongside partner solutions so you can experience the entire ecosystem including Office 365, Salesforce, and more. </li>\r\n</ul>"
},
"toRecipients": [
{
"emailAddress": {
"address": "test#ueser.com"
}} ]}}}
request(options, function(err, res, body) {
console.log(res.statusCode)
})
the problem i have is if i want to pass the body from a string like this
var mybody = `{ "message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "html",
"content": "This is a test"
},
"toRecipients": [
{
"emailAddress": {
"address": "test#user.com"
}
}]}}`
and then call it like this
const options = {
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,
body: mybody
}
request(options, function(err, res, body) {
console.log(res.statusCode)
})
which throws errors like
SyntaxError: Unexpected token " in JSON at position 0
Have you tried using stringify? Node.js has a a built in module called querystring.
const querystring = require("querystring");
const myStringBody = querystring.stringify(myBody);
Then write it to your request.
req.write(myStringBody);

How to capture dialogflow response?

I have a dialogflow intent and I want to write a javascript code to get json response of this intent and show it in an html file. I used webhook fulfillment for this intent and now I want to show chat history between dialogflow and user in an html file. I used this javascript code to extract and have dialogflow response:
baseUrl = "https://api.dialogflow.com/v1/",
$.ajax({
type: "POST",
url: baseUrl + "query",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({query: text, lang: "en", sessionId: "b1973977-20be-4cdc-85a5-7f4225cfdb5a"}),
success: function(data) {
console.log("data",data);
prepareResponse(data);
},
error: function() {
respond(messageInternalError);
}
});
}
But the json it returns me is incorrect and has no fulfillment part in order to extract correct data and show response.
The returned json is :
id: "a0114c2a-afdb-415e-af08-e7a2c5b7d925"
lang: "en"
result: {…}
action: ""
metadata: Object { intentName: "Edit.Attributes", intentId: "9601923d-596b-44df-80de-92dff61869cf", webhookUsed: "true", … }
parameters: Object { VarName: […], percentage: "20%", currncy: "", … }
resolvedQuery: "Change the attribute vacancy rate to 20%"
score: 1
source: "agent"
speech: ""
__proto__: Object { … }
sessionId: "b1973977-20be-4cdc-85a5-7f4225cfdb5a"
status: Object { code: 200, errorType: "success", webhookTimedOut: false }
timestamp: "2018-01-24T12:35:46.342Z"
In my case, this was the solution:
Putting :
url: baseUrl + "query?v=20170712",
instead of :
url: baseUrl + "query",
in ajax call,solved my problem.
The dialogflow response is contained in speech and displayText propery.

Create an Issue with Jira API REST

When I try to create an Issue via the Jira API REST, I get a 500 Internal server error, I succeeded to get an issue from a project with a get-request but when I try the post-request to create a new issue it doesn't work I get the error.
Here is my JavaScript code :
createIssue: function(req, res) {
var Http = require('machinepack-http');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
Http.sendHttpRequest({
url: '/rest/api/2/issue/',
baseUrl: 'https://jira.mydomain.com',
method: 'post',
data: {
"fields": {
"project": {
"key": "TEST"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
},
headers: {
"Authorization": "Basic YWxbG9wMS4zp0bWFuzeThYS5l1TIqaXoxOTg5554Jh"
},
}).exec({
serverError: function(result) {
res.send("server error" + JSON.stringify(result))
},
success: function(result) {
res.send("issue has been created succefly");
},
});
}
Error content :
{
"body": "{\"errorMessages\":[\"Internal server error\"],\"errors\":{}}",
"headers": "{\"server\":\"nginx/1.6.0\",\"date\":\"Tue, 14 Apr 2015 13:45:38 GMT\",\"content-type\":\"application/json;charset=UTF-8\",\"transfer-encoding\":\"chunked\",\"connection\":\"close\",\"x-arequestid\":\"945x246734x1\",\"set-cookie\":[\"JSESSIONID=838923A79DA31F77BDD62510399065CF; Path=/; HttpOnly\",\"atlassian.xsrf.token=BQIV-TVLW-FGBG-OTYU|63c1b4a7b87a9367fff6185f0101c415f757e85b|lin; Path=/\"],\"x-seraph-loginreason\":\"OK\",\"x-asessionid\":\"ughpoh\",\"x-ausername\":\"alaa\",\"cache-control\":\"no-cache, no-store, no-transform\",\"x-content-type-options\":\"nosniff\"}",
"status": 500
}
Use params instead of data
JS:-
createIssue: function(req, res) {
var Http = require('machinepack-http');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
Http.sendHttpRequest({
url: '/rest/api/2/issue/',
baseUrl: 'https://jira.mydomain.com',
method: 'post',
params: {
"fields": {
"project": {
"key": "TASC"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
},
headers: {
"Authorization": "Basic YWxbG9wMS4zp0bWFuzeThYS5l1TIqaXoxOTg5554Jh"
},
}).exec({
serverError: function(result) {
res.send("server error" + JSON.stringify(result))
},
success: function(result) {
res.send("issue has been created succefly");
},
});
}
Reference
It looks like it's expecting some non-null value when it's trying to parse the project or issuetype fields, though without the full stacktrace, it's hard to be sure.
You might try adding an id property to both the project and issuetype fields:
params: {
"fields": {
"project": {
"key": "TASC",
"id": "10001"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"id": "1",
"name": "Bug"
}
}
}
Obviously you'll want to make sure to use an appropriate value in both cases.

Resources