Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
How to obtain a twitter api access token in JavaScript

I am trying to convert a Python app I made some years ago to a (better) NodeJS implementation. The function in question obtains an access token from the Twitter api to attach to future requests, but my implementation returns 403 bad request. Here is a the functional Python implementation..

def get_bearer_header():
    uri_token_endpoint = 'https://api.twitter.com/oauth2/token'
    key_secret = f"{twitter_creds.CONSUMER_KEY}:{twitter_creds.CONSUMER_KEY_SECRET}".encode('ascii')
    b64_encoded_key = base64.b64encode(key_secret)
    b64_encoded_key = b64_encoded_key.decode('ascii')

    auth_headers = {
        'Authorization': 'Basic {}'.format(b64_encoded_key),
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        }

    auth_data = {
        'grant_type': 'client_credentials'
        }

    auth_resp = requests.post(uri_token_endpoint, headers=auth_headers, data=auth_data)
    bearer_token = auth_resp.json()['access_token']

    bearer_header = {
        'Accept-Encoding': 'gzip',
        'Authorization': 'Bearer {}'.format(bearer_token),
        'oauth_consumer_key': twitter_creds.CONSUMER_KEY 
    }
    return bearer_header

and here is the JS implementation so far..

export const getBearerHeader = async () => {
    const keyAndSecret = btoa(`${config.twitterApi.consumerKey}:${config.twitterApi.consumerKeySecret}`)
    const buff = Buffer.from(keyAndSecret, 'utf-8');
    const b64KeyAndSecret = buff.toString('base64');
    const body = new URLSearchParams({
        'grant_type': 'client_credentials'
    })
    const url = config.twitterApi.oauthTokenEndpoint
    const headers =  {
        'Authorization': `Basic ${b64KeyAndSecret}`,
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }

    const resp = await axios.post(url, body, headers)
    console.log("RESPONSE.data")
    console.log(resp.data)
}

the request looks fine according to twitter docs, but my response says 403!

Any assistance appreciated!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Get Twitter access token v2 by python and node.js code.

To create API Key and Secret from Twitter Developer Portal

Main idea to use curl commend for getting access token. POST oauth2/token

Using config.json file

{
    "API_KEY" : "Xx7MxxxxxTkzxxxxxq9xxxxxQ",
    "API_KEY_SECRET" : "om4QxxxxxPrcPlxxxxxFikDxxxxxoC5mQxxxxxLy7M17xxxxxK"
}

Node.js code

const axios = require('axios')
const config = require('./config.json');

const getAccessToken = async () => {
    try {
        const resp = await axios.post(
            'https://api.twitter.com/oauth2/token',
            '',
            {
                params: {
                    'grant_type': 'client_credentials'
                },
                auth: {
                    username: config.API_KEY,
                    password: config.API_KEY_SECRET
                }
            }
        );
        console.log(resp.data);
    } catch (err) {
        // Handle Error Here
        console.error(err);
    }
};

getAccessToken();

python code

import requests
import json
import ast

def get_access_token():
    with open('config.json') as config_file:
        data = json.load(config_file)

        params = {
            'grant_type': 'client_credentials',
        }

        response = requests.post('https://api.twitter.com/oauth2/token', params=params, auth=(data['API_KEY'], data['API_KEY_SECRET']))

        print(response.content)
        json_data = ast.literal_eval(response.content.decode("UTF-8"))
        return json_data['access_token']


print(get_access_token())

run from terminal enter image description here

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!