ZAICO APIサンプルコード(納品データ編)

 
require 'net/http'
require 'rest-client'
require 'json'

# APIの設定
$zaicoapi_token = "YOUR_TOKEN_HERE"
$zaicoapi_url = "https://web.zaico.co.jp/api/v1/packing_slips"


# 納品データ一覧取得
def get_packing_slips()
    puts "納品データ一覧"
    slips = RestClient.get($zaicoapi_url, headers={'Authorization' => 'Bearer ' + $zaicoapi_token})
    JSON.parse(slips.body).each do |slip|
        put_packing_slip(slip)
    end
    puts ""
end

# 納品データ表示
def put_packing_slip(slip)
    puts "PackingSlip ID: #{slip["id"]}"
    puts "番号: #{slip["num"]}"
    puts "取引先名: #{slip["nucustomer_namem"]}"
    puts "状態: #{slip["status"]}"
    puts "<明細>"
    slip["deliveries"].each do |delivery|
        puts "物品名: #{delivery["title"]} 納品数量: #{delivery["quantity"]} 納品単価: #{delivery["unit_price"]}"
    end
    puts "------------------"
end

# 納品データ一覧取得(1,000件以上対応)
def get_all_packing_slips()
    # ページ数の取得
    pages = parse_link_header($zaicoapi_url, headers={'Authorization' => 'Bearer ' + $zaicoapi_token})
    total_pages = pages[:last]
    # 全ページ取得
    puts "納品データ一覧"
    for i in 1..total_pages.to_i
        pagenation_url = $zaicoapi_url + "?page=#{i}"
        slips = RestClient.get(pagenation_url, headers={'Authorization' => 'Bearer ' + $zaicoapi_token})
        puts "================================================================="
        puts "#{i}ページ目"
        puts pagenation_url
        puts "================================================================="
        puts "------------------"
        JSON.parse(slips.body).each do |slip|
            put_packing_slip(slip)
        end
        puts ""
    end 
end

def parse_link_header(url, headers={})
    response = RestClient.get(url, headers)
    pages = Hash.new
    parts = response.headers[:link].split(',')
    parts.each do |part, index|
      section = part.split(';')
      page_number = section[0].match(/page=(\d+).*$/)[1]
      name = section[1][/rel="(.*)"/,1].to_sym
      pages[name] = page_number
    end
    return pages
end

if __FILE__ == $0
  get_packing_slips
  get_all_packing_slips()
end