1. Instagram Graph APIの準備
1-1. Instagramアカウントの種類を確認
- ビジネスアカウントまたはクリエイターアカウントが必要です。
- 個人アカウントの場合は、Instagramアプリから「プロアカウント」に切り替えてください。
1-2. Facebookページを作成
- InstagramビジネスアカウントはFacebookページと連携が必要です。
- Facebookで新しいページを作成します。
1-3. InstagramアカウントとFacebookページを連携
- Instagramアプリの「設定」→「アカウント」→「他のアプリと連携」→「Facebook」で連携します。
1-4. Facebook for Developersでアプリを作成
- Facebook for Developersにアクセスし、アプリを新規作成します。
1-5. Instagram Graph APIを追加
- 作成したアプリの「製品を追加」から「Instagram Graph API」を選択し追加します。
1-6. アクセストークンを取得
- 「ツール」→「Graph API Explorer」でアクセストークンを取得します。
- 必要な権限: instagram_basic, pages_show_list, pages_read_engagement
- アクセストークンは有効期限があるので注意(長期運用にはリフレッシュが必要)。
1-7. InstagramユーザーIDを取得
- Graph API Explorerで
https://graph.instagram.com/me?fields=id,username&access_token=取得したアクセストークン
にアクセスし、idを控えておきます。
2. Railsアプリの準備
2-1. httpartyをインストール
Gemfileに以下を追加し、bundle installを実行します。
Gemfile
$ gem 'httparty'
$ bundle install
2-2. 環境変数の設定
.envファイル(またはcredentials、環境変数)に以下を記載します。
.env
INSTAGRAM_USER_ID=取得したInstagramユーザーID
INSTAGRAM_ACCESS_TOKEN=取得したアクセストークン
3. コントローラーの編集
app/controllers/tweets_controller.rb の先頭に
tweets_controller.rb
require 'httparty'
を追加し、indexアクションを以下のように編集します。
tweets_controller.rb
def index
@tweets = Tweet.all
access_token = ENV['INSTAGRAM_ACCESS_TOKEN']
user_id = ENV['INSTAGRAM_USER_ID']
@instagram_posts = []
if access_token && user_id
url = "https://graph.instagram.com/#{user_id}/media?fields=id,caption,media_url,permalink,timestamp&access_token=#{access_token}&limit=3"
begin
response = HTTParty.get(url)
if response.code == 200 && response.parsed_response["data"]
@instagram_posts = response.parsed_response["data"]
end
rescue => e
Rails.logger.error("Instagram API error: #{e.message}")
end
end
end
4. ビューの編集
app/views/tweets/index.html.erb に以下を追加します(ツイート一覧の下などに)
index.html.erb
<h2>Instagram 最新投稿</h2>
<div class="instagram-debug">
<h4>デバッグ情報(APIレスポンス)</h4>
<pre><%= JSON.pretty_generate(@instagram_posts) rescue @instagram_posts.inspect %></pre>
</div>
<div class="instagram-posts">
<% @instagram_posts.each do |post| %>
<div class="instagram-post">
<a href="<%= post["permalink"] %>" target="_blank">
<% if post["media_url"] %>
<img src="<%= post["media_url"] %>" style="max-width:200px; max-height:200px; border:2px solid #0af;" />
<% else %>
<span style="color:red;">画像なし</span>
<% end %>
</a>
<p><%= post["caption"] %></p>
</div>
<% end %>
</div>
Gemを追加した場合や環境変数を変更した場合は、必ずRailsサーバーを再起動してください。