Skip to content

Instantly share code, notes, and snippets.

@ivarvong
Last active February 16, 2016 22:42
Show Gist options
  • Save ivarvong/ed7f436cf8064d3cfa46 to your computer and use it in GitHub Desktop.
Save ivarvong/ed7f436cf8064d3cfa46 to your computer and use it in GitHub Desktop.

This is a quick example of making an authenticated call to Bitbucket using an OAuth 2 Authorization token. The token is from a 'client_credentials' grant, which allows for server-to-server API calls in high-trust situations. (I'm using it for internal access to our own Git repos hosted on Bitbucket)

You'll need an .env file with CLIENT_ID, CLIENT_SECRET and TEAM to make this work.

require 'httparty'
require 'json'
require 'dotenv'
Dotenv.load
class Bitbucket
include HTTParty
base_uri 'https://api.bitbucket.org/2.0'
attr_reader :access_token
def initialize
get_access_token
end
def headers
{
"Authorization" => "Bearer #{access_token}",
"Accept" => "application/json"
}
end
def get_access_token
response = HTTParty.post(
"https://bitbucket.org/site/oauth2/access_token",
basic_auth: {
username: ENV['CLIENT_ID'],
password: ENV['CLIENT_SECRET']
},
body: {
grant_type: 'client_credentials'
}
)
data = JSON.parse(response.body)
@access_token = data['access_token']
end
def repos
JSON.parse(self.class.get("/repositories/#{ENV['TEAM']}", headers: headers).body)
end
end
puts Bitbucket.new.repos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment