Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Example of how to generate and use a Twitter bearer token for the purpose of performing application-only authentication for the Twitter API
# Generate and use an oauth2 bearer token for the Twitter API in Ruby
# For Application-Only authentication to the twitter API, a 'bearer token'
# is required to authenticate agains their endpoints for rate limiting
# purposes.
# This script generates a bearer token by posting to twitter and then it
# uses that token to poll their API.
# Note, the base 64 encoded consumer credentials for the bearer token needs
# to be stripped of newlines in order for this to work.
# The <consumer_key> and <consumer_secret> can be found by administering
# a twitter app at:
# For documentation on how to generate this bearer token, refer:
require 'rubygems'
require 'base64'
require 'httparty'
require 'json'
consumer_key = "<consumer_key>"
consumer_secret = "<consumer_secret>"
credentials = Base64.encode64("#{consumer_key}:#{consumer_secret}").gsub("\n", '')
url = ""
body = "grant_type=client_credentials"
headers = {
"Authorization" => "Basic #{credentials}",
"Content-Type" => "application/x-www-form-urlencoded;charset=UTF-8"
r =, body: body, headers: headers)
bearer_token = JSON.parse(r.body)['access_token']
puts "Twitter bearer token is: #{bearer_token}"
api_auth_header = {"Authorization" => "Bearer #{bearer_token}"}
url = ""
puts HTTParty.get(url, headers: api_auth_header).body

This comment has been minimized.

Show comment Hide comment

sunsheeppoplar Nov 4, 2016

thanks, bruh!

thanks, bruh!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment