Quick Start Examples
Ruby Examples
Quick start examples for integrating with the API using Ruby
This page provides practical Quick start examples for integrating with the API using Ruby.
Basic Client
require 'net/http'
require 'json'
require 'uri'
class IPOAlertsClient
def initialize(api_key)
@api_key = api_key
@base_url = 'https://api.ipoalerts.in'
end
def get_ipos(status: nil, type: nil, page: 1, limit: 10)
params = []
params << "status=#{status}" if status
params << "type=#{type}" if type
params << "page=#{page}"
params << "limit=#{limit}"
endpoint = "/ipos?#{params.join('&')}"
make_request(endpoint)
end
def get_ipo(identifier)
endpoint = "/ipos/#{identifier}"
response = make_request(endpoint)
response['ipo']
end
private
def make_request(endpoint)
uri = URI("#{@base_url}#{endpoint}")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri)
request['x-api-key'] = @api_key
request['Content-Type'] = 'application/json'
response = http.request(request)
if response.code.to_i >= 400
raise "HTTP error: #{response.code}"
end
JSON.parse(response.body)
end
end
# Usage
client = IPOAlertsClient.new('YOUR_API_KEY')
begin
# Get upcoming IPOs
ipos = client.get_ipos(status: 'upcoming', type: 'EQ', page: 1, limit: 10)
puts "Found #{ipos['meta']['count']} upcoming equity IPOs"
ipos['ipos'].each do |ipo|
puts "#{ipo['name']} (#{ipo['symbol']}) - #{ipo['priceRange']}"
end
# Get specific IPO
ipo_details = client.get_ipo('example-company-limited')
puts "IPO Details: #{ipo_details['name']}"
rescue => e
puts "Error: #{e.message}"
end
Advanced Client with Caching and Rate Limiting
require 'net/http'
require 'json'
require 'uri'
require 'time'
class AdvancedIPOAlertsClient < IPOAlertsClient
def initialize(api_key, requests_per_minute: 6)
super(api_key)
@requests_per_minute = requests_per_minute
@cache = {}
@cache_duration = 300 # 5 minutes
@request_times = []
@mutex = Mutex.new
end
def get_ipos(status: nil, type: nil, page: 1, limit: 10)
cache_key = cache_key_for_request('/ipos', { status: status, type: type, page: page, limit: limit })
if cache_valid?(cache_key)
puts "Returning cached data"
return @cache[cache_key][:data]
end
enforce_rate_limit
result = super(status: status, type: type, page: page, limit: limit)
@mutex.synchronize do
@cache[cache_key] = {
data: result,
timestamp: Time.now
}
end
result
end
def get_ipo(identifier)
cache_key = cache_key_for_request("/ipos/#{identifier}", { identifier: identifier })
if cache_valid?(cache_key)
puts "Returning cached IPO data"
return @cache[cache_key][:data]
end
enforce_rate_limit
result = super(identifier)
@mutex.synchronize do
@cache[cache_key] = {
data: result,
timestamp: Time.now
}
end
result
end
def clear_cache
@mutex.synchronize do
@cache.clear
end
end
def cache_stats
@mutex.synchronize do
{
cache_size: @cache.size,
request_count: @request_times.size
}
end
end
private
def cache_key_for_request(endpoint, params)
"#{endpoint}_#{params.to_json}"
end
def cache_valid?(cache_key)
@mutex.synchronize do
return false unless @cache[cache_key]
cached_time = @cache[cache_key][:timestamp]
Time.now - cached_time < @cache_duration
end
end
def enforce_rate_limit
@mutex.synchronize do
now = Time.now
# Remove requests older than 1 minute
@request_times.reject! { |time| now - time > 60 }
if @request_times.size >= @requests_per_minute
sleep_time = 60 - (now - @request_times.first)
sleep(sleep_time) if sleep_time > 0
end
@request_times << now
end
end
end
# Usage
client = AdvancedIPOAlertsClient.new('YOUR_API_KEY')
begin
# First request - will be cached
ipos1 = client.get_ipos(status: 'upcoming', type: 'EQ')
# Second request - will return cached data
ipos2 = client.get_ipos(status: 'upcoming', type: 'EQ')
puts "Cache stats: #{client.cache_stats}"
rescue => e
puts "Error: #{e.message}"
end
Rails Integration
# app/services/ipo_alerts_service.rb
class IPOAlertsService
include HTTParty
base_uri 'https://api.ipoalerts.in'
def initialize(api_key = nil)
@api_key = api_key || Rails.application.credentials.ipoalerts_api_key
@options = {
headers: {
'x-api-key' => @api_key,
'Content-Type' => 'application/json'
}
}
end
def get_ipos(status: nil, type: nil, page: 1, limit: 10)
cache_key = "ipoalerts_ipos_#{status}_#{type}_#{page}_#{limit}"
Rails.cache.fetch(cache_key, expires_in: 5.minutes) do
params = { page: page, limit: limit }
params[:status] = status if status
params[:type] = type if type
response = self.class.get('/ipos', @options.merge(query: params))
if response.success?
response.parsed_response
else
raise "API request failed: #{response.code}"
end
end
end
def get_ipo(identifier)
cache_key = "ipoalerts_ipo_#{identifier}"
Rails.cache.fetch(cache_key, expires_in: 5.minutes) do
response = self.class.get("/ipos/#{identifier}", @options)
if response.success?
response.parsed_response['ipo']
else
raise "API request failed: #{response.code}"
end
end
end
end
# app/controllers/ipos_controller.rb
class IPOsController < ApplicationController
before_action :set_ipo_alerts_service
def index
begin
@ipos = @ipo_alerts_service.get_ipos(
status: params[:status],
type: params[:type],
page: params[:page] || 1,
limit: params[:limit] || 10
)
render json: @ipos
rescue => e
render json: { error: e.message }, status: :internal_server_error
end
end
def show
begin
@ipo = @ipo_alerts_service.get_ipo(params[:id])
render json: { ipo: @ipo }
rescue => e
render json: { error: e.message }, status: :internal_server_error
end
end
private
def set_ipo_alerts_service
@ipo_alerts_service = IPOAlertsService.new
end
end
# config/routes.rb
Rails.application.routes.draw do
resources :ipos, only: [:index, :show]
end
# config/credentials.yml.enc
# Add your API key using: rails credentials:edit
# ipoalerts_api_key: your_api_key_here
Sinatra Integration
require 'sinatra'
require 'sinatra/cache'
require 'json'
require_relative 'ipo_alerts_service'
class IPOAlertsApp < Sinatra::Base
register Sinatra::Cache
configure do
set :cache_enabled, true
set :cache_store, :memory
end
before do
content_type :json
end
get '/ipos' do
begin
service = IPOAlertsService.new(ENV['IPOALERTS_API_KEY'])
cache_key = "ipos_#{params[:status]}_#{params[:type]}_#{params[:page]}_#{params[:limit]}"
result = cache(cache_key, expires: 300) do
service.get_ipos(
status: params[:status],
type: params[:type],
page: params[:page] || 1,
limit: params[:limit] || 10
)
end
result.to_json
rescue => e
status 500
{ error: e.message }.to_json
end
end
get '/ipos/:identifier' do
begin
service = IPOAlertsService.new(ENV['IPOALERTS_API_KEY'])
cache_key = "ipo_#{params[:identifier]}"
result = cache(cache_key, expires: 300) do
service.get_ipo(params[:identifier])
end
{ ipo: result }.to_json
rescue => e
status 500
{ error: e.message }.to_json
end
end
end
# Run the app
IPOAlertsApp.run! if __FILE__ == $0
Background Job Processing
# app/jobs/ipo_data_sync_job.rb
class IPODataSyncJob < ApplicationJob
queue_as :default
def perform
service = IPOAlertsService.new
# Sync upcoming IPOs
upcoming_ipos = service.get_ipos(status: 'upcoming')
upcoming_ipos['ipos'].each do |ipo_data|
ipo = IPO.find_or_initialize_by(external_id: ipo_data['id'])
ipo.update!(
name: ipo_data['name'],
symbol: ipo_data['symbol'],
status: ipo_data['status'],
price_range: ipo_data['priceRange'],
start_date: ipo_data['startDate'],
end_date: ipo_data['endDate'],
listing_date: ipo_data['listingDate']
)
end
# Sync open IPOs
open_ipos = service.get_ipos(status: 'open')
open_ipos['ipos'].each do |ipo_data|
ipo = IPO.find_or_initialize_by(external_id: ipo_data['id'])
ipo.update!(
name: ipo_data['name'],
symbol: ipo_data['symbol'],
status: ipo_data['status'],
price_range: ipo_data['priceRange'],
start_date: ipo_data['startDate'],
end_date: ipo_data['endDate'],
listing_date: ipo_data['listingDate']
)
end
Rails.logger.info "Synced #{upcoming_ipos['meta']['count']} upcoming and #{open_ipos['meta']['count']} open IPOs"
rescue => e
Rails.logger.error "IPO sync failed: #{e.message}"
raise e
end
end
# config/schedule.rb (using whenever gem)
every 1.hour do
runner "IPODataSyncJob.perform_later"
end