Posting an Asana task using fetch - asana

I'm trying to work with the Asana API as I learn React and Redux. I've been able to get data from the Asana API using fetch() just fine so far, but I'm having trouble posting a task.
Here is the code I'm using:
const options = (type, data) => {
const defaultHeaders = {
'Authorization': `Bearer ${apiKey}`,
'Asana-Fast-Api': 'true',
}
switch(type) {
case 'get':
return {
headers: defaultHeaders,
}
case 'post':
const body = JSON.stringify(data)
console.log(body);
return {
method: 'POST',
headers: defaultHeaders,
contentType: 'application/json',
body: body,
}
default:
return {
headers: defaultHeaders,
}
}
};
const asanaUrl = (props) => {
const numOfProps = props.length;
switch (numOfProps) {
case 3:
return `https://app.asana.com/api/1.0/${props[0]}/${props[1]}?${props[2]}`
case 2:
return `https://app.asana.com/api/1.0/${props[0]}?${props[1]}`
case 1:
return `https://app.asana.com/api/1.0/${props[0]}`
default:
return console.log(props)
}
}
export const asanaPost = (props, data) => {
return fetch(asanaUrl(props), options('post', data))
.then(response => response.json() )
}
In the console, I see the return from the console.log which shows the JSON I'm sending into my body key:
{"assignee":22800770039251,"name":"test","notes":"test"}
and the following error
Failed to load resource: the server responded with a status of 400 (Bad Request)
The URL appears to be correct: https://app.asana.com/api/1.0/tasks?workspace=31542879721131
The error message is:
"Must specify exactly one of project, tag, or assignee + workspace"
It doesn't seem to matter what fields I include in the body (including a project resulted in the same error), which makes me suspect that something else is afoot and the Asana API isn't getting a hold of the body or isn't able to interpret it with how I've set things up.
Thanks for helping me out with this!

The api url I use is
https://app.asana.com/api/1.0/tasks?opt_fields=html_notes
I also pass projects as a key and a string value in the body.
I do not use 'Asana-Fast-Api': 'true' in the headers

Related

Zapier: Pull Data From Two API EndPoints In One Trigger

​
I am working on a trigger where I need to pull data from two API end points. The first endpoint is a contact from a database that retrieves an email address, then to obtain the details for that contact (email) I need to use another end point. once is /Subscriber and the other is /Subsriber/ {email}/ Properties.
 
I am wondering if I can use a variable to obtain all the data in one trigger, as I have is set up in separate triggers right now.
 
Here is the code for both
Subscriber:
url: 'https://edapi.campaigner.com/v1/Subscribers?PageSize=1',
method: 'GET',
headers: {
'Accept': 'application/json',
'X-API-KEY': bundle.authData.ApiKey
},
params: {
'ApiKey': bundle.authData.ApiKey
}
};
return z.request(options).then((response) => {
response.throwForStatus();
const result = z.JSON.parse(response.content);
result.id = result.Items;
return [result];
});
And Subscriber Properties
const options = {
url: `https://edapi.campaigner.com/v1/Subscribers/${bundle.inputData.email_address}/Properties`,
method: 'GET',
headers: {
'Accept': 'application/json',
'X-API-KEY': bundle.authData.ApiKey
},
params: {
'email_address': bundle.inputData.email_address,
'ApiKey': bundle.authData.ApiKey
}
}
return z.request(options).then((response) => {
response.throwForStatus();
const result = z.JSON.parse(response.content);
result.id = result.CustomFields;
return [result];
});
Any help is appreciated.
​
Yes, definitely possible! Unless your subscriber data actually needs to be a separate trigger (which is unlikely, since you probably just trigger off new contacts), it can just be a function. Try something like:
const subscriberPerform = async (z, bundle) => {
const emailResponse = await z.request({
url: "https://edapi.campaigner.com/v1/Subscribers?PageSize=1",
method: "GET",
headers: {
Accept: "application/json",
"X-API-KEY": bundle.authData.ApiKey, // does this need to be both places?
},
params: {
ApiKey: bundle.authData.ApiKey, // does this need to be both places?
},
});
// requires core version 10+
const email = emailResponse.data.email;
const emailDataResponse = await z.request({
url: `https://edapi.campaigner.com/v1/Subscribers/${email}/Properties`,
method: "GET",
headers: {
Accept: "application/json",
"X-API-KEY": bundle.authData.ApiKey,
},
params: {
email_address: bundle.inputData.email_address, // lots of duplicated data here
ApiKey: bundle.authData.ApiKey,
},
});
return [emailDataResponse.data.SOMETHING];
};
That's the general idea. These JS functions may not need to be triggers at all, depending on how you're using them.
One last note - you don't want to perform this extra lookup every time you poll for new contacts; that's wasteful. If you're doing that, check out dehydration.

YouTube Live Streaming API: LiveChatMessages userBannedEvent not showing

I'm currently creating a script that handles the ban events when a user is banned from a YouTube live chat, however the event is never emitted when a user is banned (even when I have mod perms on the stream). For authorization I'm using the youtube.force-ssl scope, but I still don't get the event, only textMessageEvent. Am I passing the improper permission/scope?
For anyone wondering, here's the code I'm using :)
I'm using a modified version of https://github.com/yuta0801/youtube-live-chat (made it so I could pass an authorization token and passing it in the request headers)
const YouTube = require('youtube-live-chat');
const yt = new YouTube("CHANNEL_ID", "API_KEY", "AUTH_TOKEN")
yt.on('ready', () => {
console.log('ready!')
yt.listen(5000)
})
yt.on('message', data => {
console.log(data.snippet.type)
})
yt.on('error', error => {
console.error(error)
})
request function in the lib that I modified
request(url, callback) {
let options = {
url: url,
method: 'GET',
json: true,
headers: {}
}
if(this.auth) options.headers.authorization = `Bearer ${this.auth}`
request(options, (error, response, data) => {
if (error)
this.emit('error', error)
else if (response.statusCode !== 200)
this.emit('error', data)
else
callback(data)
})
}
scope
eventLog

Microsoft Graph sendMail doesn't work and returns NULL

I'm trying to send e-mails with MS Graph 1.0 and I have not any get any result or response. E-Mails haven't been sent and sendMail method don't return any error o message... it only says "null".
My code is based on this example https://github.com/microsoftgraph/msgraph-sdk-javascript#post-and-patch and looks like this:
// Initialize Graph client
const client = graph.Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
try {
// construct the email object
var mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [{
emailAddress: {
address: "mail#domain.com"
}
}],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html"
}
};
client
.api('/me/sendMail')
.post({message: mail}, (err, res) => {
console.log("---> " + res);
});
console.log("Try ends");
} catch (err) {
parms.message = 'Error retrieving messages';
parms.error = { status: `${err.code}: ${err.message}` };
parms.debug = JSON.stringify(err.body, null, 2);
res.render('error', parms);
}
I guess mail var needs a header, but anyway, API should return me something, right? And, obviously, which is the problem with the email sending?
I finally added rawResponse to .post call and look at err log...
client
.api('/me/sendMail')
.header("Content-type", "application/json")
.post({message: mail}, (err, res, rawResponse) => {
console.log(rawResponse);
console.log(err);
});
... and I could see that I had problem with my authentication token. So, I was using the api correctly and code from the question is ok.

With a `new Request` in Node/React, how to pass params with a GET request?

I have the following API call in my Reactjs app:
static getAllSkills(title_id) {
const request = new Request(`http://localhost:4300/api/v1/job_title_skills`, {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify({title_id: title_id})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
Which points to a Rails endpoint which expects the param title_id like so:
def index
#skills = Skill.where(id: params[:title_id])
....
end
The controller is expecting a GET request however with the above, I'm getting the following JS console error:
Uncaught TypeError: Failed to construct 'Request': Request with GET/HEAD method cannot have body.
What is the right way to construct the Request and pass the param to the API?
I think the url in your api is waiting for the title_id maybe like:
api/v1/job_title_skills/:title_id
So you can append it in your url when you make the request:
static getAllSkills(title_id) {
const request = new Request(`http://localhost:4300/api/v1/job_title_skills/${title_id}`, {
headers: new Headers({
'Content-Type': 'application/json'
})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}

Fetch in ReactNative can not deliver the paras in body to the server

ReactNative provide me with fetch to send a httpRequest.The attribute of body includes my parameters which are to send to the server.But I can't get the parameters on my server.My codes are here:
fetch(`${keys.api}/login`,
{
method: 'POST',
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}
).then((response) => {
if(response._bodyText == 'success') {
this.props.resetToRoute({
name: '主页',
component: Main,
hideNavigationBar: true,
});
} else {
this.cancelLogin();
}
}).catch((error) => {
console.warn(error);
this.cancelLogin();
});
And the console in my J2EE Web Server prints the message:
The httpRequest message
There is no parameter in my httpRequest(In other words,The body can not deliver any parameters),I need help.
It's dangerous to show my username and password in the url.
i have met the problem twice on jetty-8.1 on different condition
first ,you should know that it has nothing to do with react-native
fetch put the data in body to header "payload" when the client made a request.i thought jetty-8.1 does not support get data from the payload header
,change the way
Getting request payload from POST request in Java servlet will be helpful
or maybe use the websockt or XMLhttpRequest object to send a request
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString()

Resources