I’ve started on a project where I need to call Twitter’s REST apis from a Node.js JavaScript app. I’ve built a Java app before that integrated with Twitter, but used a library to help with the OAUTH authentication. Looking around for a JavaScript library, it looks like node-oauth does what I need to do, so gave it a go.
Twitter’s API docs are pretty good, but I ran into an issue with node-oauth with an error coming back from:
POST /statuses/update.json
which returned this message:
{ statusCode: 401,
data: '{"errors":[{"code":32,"message":"Could not authenticate you."}]}' }
which is odd because using the node-oauth library to authenticate and then call any of the GET apis with node-oauth was working fine. If you Google this error there’s numerous posts about this error for all number of reasons, so I’m not sure it’s a particularly specific message.
Here’s a working example for a GET:
First, use node-oauth to authenticate with your Twitter key, secret, and app access token and secret (which you can set up here):
var oauth = new OAuth.OAuth(
'https://api.twitter.com/oauth/request_token',
'https://api.twitter.com/oauth/access_token',
config.twitterConsumerKey,
config.twitterSecretKey,
'1.0A',
null,
'HMAC-SHA1'
);
Next, using the returned value from this call, make the GET request (it builds the request including the OAUTH headers for you):
//GET /search/tweets.json
oauth.get(
'https://api.twitter.com/1.1/search/tweets.json?q=%40twitterapi',
config.accessToken,
config.accessTokenSecret,
function (e, data, res){
if (e) console.error(e);
console.log(data);
});
Attempting a POST to update the status for this account using the similar api:
var status = "{'status':'test 3 from nodejs'}";
oauth.post('https://api.twitter.com/1.1/statuses/update.json',
config.accessToken,
config.accessTokenSecret,
status,
function(error, data) {
console.log('\nPOST status:\n');
console.log(error || data);
});
And this is the call that returned the error about “could not authenticate”.
Looking through a few other tickets for the node-oauth project, this one gave a clue – this particular issue was about special chars in the body content to the POST, but it gave an example of the body formed like this:
var status = ({'status':'test from nodejs'});
I would have thought passing a String would have worked, but I guess the api is expecting an object? Anyway, this is working, and looks good so far.