6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Sinatra と jpstock を使って簡単なAPIをつくる

Posted at

既存のサービスとかであるかもしれないが、株価をjsonで取得できるAPIが欲しくて適当に作成

##1.構成

サーバー : CentOS6.7
Ruby : 2.3
sinatra : 1.4.7
jpstock : 0.6.7
working directory : /root/api_stock

##2. 準備

データを取得するやつ

tool.rb
#!/usr/bin/ruby
# coding: utf-8

require 'jpstock'
require 'curses'
require 'holiday_japan'
require 'json'

## calculate businness days

class Date
  def business_days(i)
    date = self
    i.times.each do |j|
      date -= 1
      date -= 1 while (date.wday <= 0 || date.wday >= 6) or (date.national_holiday?)
    end
    date
  end
end

## get share price

class Stock
  def  initialize(scode)
    @scode = scode
  end

  def get_code(scode)
    stocks = scode
    stock = JpStock.price(:code => stocks )
    name = JpStock.sector(:code => stocks )
      hstocks = JpStock.historical_prices(
      :code => stocks,
      :start_date => Date.today.business_days(24),
      :end_date => Date.today
     )
    last_day = hstocks[0].close
    this_day = stock.close
    rate = ((this_day - last_day)/last_day * 100).round(2)
    company =  "#{name.company_name}"
    price = "#{stock.close}"
    ration = "#{rate}"
   shash = {"会社名":company, "現在値": price, "前日比": ration}
   shash.to_json
  end

end

動かすやつ(GETのみ)

s_api.rb
#!/usr/bin/ruby
# coding: utf-8

require 'sinatra'
require 'sinatra/reloader'
require 'json'
require_relative 'tool'

## set bind IP adress
set :bind, '192.168.0.1'
set :show_exceptions, false

## Get share info

get '/share/:id' do

   content_type :json
   num = params['id']
   sprice = Stock.new(num.to_i)
   astock = sprice.get_code(num.to_i)
  return astock
  
end

error do

  "Sorry!\s No exist share code number!!\n"

end

##3.デーモン化

thinを利用

config.ru
config.ru

ENV['RACK_ENV'] = "production"

require File.expand_path '/root/api_stock/s_api.rb', __FILE__

run Sinatra::Application
config.ym
 environment: production
 chdir: /root/api_stock
 address: 192.168.0.1
 user: root
 group: root
 port: 4567
 pid: /root/api_stock/thin.pid
 rackup: /root/api_stock/config.ru
 log: /root/api_stock/thin.log
 max_conns: 1024
 timeout: 30
 max_persistent_conns: 512
 daemonize: true

起動

#thin -s 2 -C config.yml -R config.ru start

確認

#curl 'http://192.168.0.1:4567/share/7974' | jq '.'

結果


{
  "前日比": "9.69",
  "現在値": "23945.0",
  "会社名": "任天堂(株)"
}

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?