LoginSignup
11
11

More than 5 years have passed since last update.

sinatraでfitbitのデータを利用する

Last updated at Posted at 2015-12-26

はじめに

消費カロリーや心拍数を集計する仕組みを作りたい。ということで
Fitbitのデータを取得してWebアプリから使用するための準備を行う。

Developer登録

Fitbit API をhttps://dev.fitbit.com/jp から、Developer登録を行う。

アプリを登録

必要事項を記載して、登録する。callback URLは、実際のCallback先でないと、リクエスト時に蹴られるので注意
http://localhost:3000/auth/fitbit_oauth2/callback
のように登録した

sinatraの準備

省略

Gemfile作成

bundle init
して、ひな形を作った後

gem 'sinatra'
gem 'omniauth'
gem 'omniauth-oauth2'
gem 'omniauth-fitbit-oauth2'
gem 'multi_json'
gem 'rest-client'

を追加。OAuthライブラリとしてomniauthを使う。便利。
bundle install
を実行

アプリ作成

こんな感じ

require 'rubygems'
require 'bundler'
Bundler.require

class HRMonitorApp < Sinatra::Base
  configure do
    use OmniAuth::Builder do
      provider :fitbit_oauth2, '#{OAuth 2.0 Client ID}','#{Client (Consumer) Secret}',
      scope: 'profile',
      expires_in: '2592000'
    end
    enable :sessions
    enable :inline_templates
    set :bind, '0.0.0.0'
    set :port, 3000
  end

  helpers do
    def get_profile
      res = JSON.parse RestClient.get "https://api.fitbit.com/1/user/-/profile.json", Authorization: "Bearer #{session[:token]}"
      warn "#{res}"
      "<body><h1><code>#{res}</code></h1></body>"
    rescue => e
      warn e
    end
  end

  get '/' do
    if session[:token]
      get_profile
    else
      redirect to '/auth/fitbit_oauth2'
    end
  end

  get '/auth/fitbit_oauth2/callback' do
    session[:token] = env['omniauth.auth']['credentials'].token
    redirect to '/'
  end
end

HRMonitorApp.run!

はまったポイント

  1. configureブロックで、enable :sessionsをやらないと、セッションがないとOmniAuthに怒られる
  2. HRMonitor.App.run! runにしてた。
  3. OmniAuthを使う場合、認証用のURLは固定。omniauth-*(今回はomniauth-fitbit-oauth2)で定義されている:nameを使った /auth/:name が認証用のURLとなる。
  4. https://github.com/codebender/omniauth-fitbit-oauth2/tree/master/lib/omniauth/strategies/fitbit_oauth2.rb だと、:name => fitbit_oauth2 なので /auth/fitbit_oauth2 に飛ばす必要がある。コールバックはこれに/callbackをつけたもの。なので、結局アプリ登録する際に指定するべきコールバックURLは自動的に決まる。
  5. スコープは https://dev.fitbit.com/docs/oauth2/#scope を参照

今後の予定

心拍数が一定以上になっている時間を列挙したり、睡眠時間を管理したり

11
11
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
11
11