Search code examples
node.jstwitterfetch

How can i use Twitter's search API in nodejs using the fetch API?


I'm trying to use Twitter's search API in nodejs. I know there are 3rd party libraries for it, but I'm trying to hit the endpoint using fetch. Here's my code:

const fetch = require('fetch');
const url = `https://api.twitter.com/1.1/search/tweets.json`
const options = {
    outputEncoding: 'utf-8',    
    headers: {
        q: 'cbd',
        consumer_key: '****',
        consumer_secret: '****',
        access_token: '****',
        access_token_secret: '****',
    }
}
fetch.fetchUrl(url, options, (err, meta, data) => {
    if(err) console.log(err)
    console.log(data)
})

I am confused as to where the keys would go. I have put them in the options for the fetch call, but I'm not sure if that's where it should be. I get a 'Bad Authentication Data' error here. Any help would be appreciated.


Solution

  • You need to use something like following.

    var fetchUrl = require("fetch").fetchUrl;
    
    fetchUrl('https://api.twitter.com/1.1/search/tweets.json?q=from%3Atwitterdev&result_type=mixed&count=2',
           {
             headers: {
                authorization: `Oauth-generated-key`
                }
            }, (err, meta, body) => {
                if (err) {
                    console.log('error', err);
                    return false;
                }
                console.log('body', body.toString());
                console.log('meta', meta);
               }
    
           )
    

    You can replace Oauth-generated-key with

    OAuth oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog",
    oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",
    oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D",
    oauth_signature_method="HMAC-SHA1", oauth_timestamp="1569222858",
    oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb",
    oauth_version="1.0"