Skip to content

Example Ruby Client

Magali Ruffier edited this page Jun 25, 2014 · 2 revisions

gemfile

source 'https://rubygems.org' 
gem 'rest-client'
gem 'json'

Client

#!/usr/bin/env ruby

require 'rubygems'
require 'rest_client'
require 'json'

$server = 'http://rest.ensembl.org'


def get_variants(species, symbol)
  genes = rest_get("/xrefs/symbol/#{species}/#{symbol}?object_type=gene")

  raise "No genes for species '#{species}' and symbol '#{symbol}'" if genes.size == 0
  return rest_get("/overlap/id/#{genes[0]['id']}?feature=variation")
end


def rest_get(url)
  $request_counter ||= 0   # Initialise if unset
  $last_request_time ||= 0 # Initialise if unset

  # Rate limiting: Sleep for the remainder of a second since the last request on every third request
  $request_counter += 1
  if $request_counter == 15 
    diff = Time.now - $last_request_time
    sleep(1-diff) if diff < 1
    $request_counter = 0
  end
  
  begin
    response = RestClient.get "#{$server}/#{url}", {:accept => :json}
    
    $last_request_time = Time.now
    JSON.parse(response)
  rescue RestClient::Exception => e
    puts "Failed for #{url}! #{response ? "Status code: #{response}. " : ''}Reason: #{e.message}"
    
    # Sleep for specified number of seconds if there is a Retry-After header
    if e.response.headers[:retry_after]
      sleep(e.response.headers[:retry_after].to_f)
      retry # This retries from the start of the begin block
    else
      abort("Quitting... #{e.inspect}")
    end
  end
end


species = 'human'
symbol  = 'BRAF'

get_variants(species, symbol).each do |variant|
  puts "#{variant['seq_region_name']}:#{variant['start']}-#{variant['end']}:#{variant['strand']} ==> #{variant['id']} (#{variant['consequence_type']})"
end