Skip to content

Instantly share code, notes, and snippets.

@jkotchoff
Last active April 27, 2023 23:10
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jkotchoff/03add042c9b1b7db350c to your computer and use it in GitHub Desktop.
Save jkotchoff/03add042c9b1b7db350c to your computer and use it in GitHub Desktop.
Send Tweets to the Twitter API with an OAuth1 token
# 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:
# http://apps.twitter.com
#
# For documentation on how to generate this bearer token, refer:
# https://dev.twitter.com/oauth/reference/post/oauth2/token
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 = "https://api.twitter.com/oauth2/token"
body = "grant_type=client_credentials"
headers = {
"Authorization" => "Basic #{credentials}",
"Content-Type" => "application/x-www-form-urlencoded;charset=UTF-8"
}
r = HTTParty.post(url, 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 = "https://api.twitter.com/1.1/search/tweets.json?q=nba"
puts HTTParty.get(url, headers: api_auth_header).body
@sunsheeppoplar
Copy link

thanks, bruh!

@marisveide
Copy link

Perfect!
Thanks, @jkotchoff!

@bolahanna44
Copy link

got error header Authorization has field value "Basic XXXXX" this cannot include CR/LF

@gousesair
Copy link

Can anyone recreate this in javascript using fetch or axios?

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