LoginSignup
4
3

More than 3 years have passed since last update.

【Rails】Pinterest APIで自分のアカウントのピン一覧を取得し、JSONを返すサンプルコード

Last updated at Posted at 2020-02-12

はじめに

Pinterest APIを使ってみたので自分用に備忘録を残します。

今回対象とする機能は、「自分のアカウントのピン一覧を取得する」です。
公式ドキュメントはこちら

※利用制限等についてはご注意下さい。

(著作権所有者の許可を得ている場合を除いて)画像を保存または改変しないこと、また Pinterest にある画像をユーザーが印刷できるようにしないこと

ピン以外のデータを保存しないこと

などなど、制限があります。
デベロッパー向けガイドライン | Pinterest Policy

環境

OS: macOS Catalina 10.15.3
Ruby: 2.6.5
Rails: 6.0.2.1

前提

  • Access Tokenの取得方法
  • rails newなど最低限の下準備

などは細かく触れていません。

Access Tokenの取得はこちらから

1. net_http_module.rb

HTTPリクエストを投げる部分は分割しておきます。
今回はGETリクエストを投げるだけなので、超シンプルです。

app/controllers/concerns/net_http_module.rb
require 'active_support'

module NetHttpModule
  extend ActiveSupport::Concern

  require 'net/http'

  def api_get(set_URL)
    uri = URI.parse(set_URL)
    response = Net::HTTP.get_response(uri)
  end
end

2. pins_controller.rb

※事前に以下のようなPinモデル、コントローラーが作成済とします。

$ rails g model Pin pin_id:integer pin_url:string image_url:string width:integer height: integer
$ rails g controller api/v1/pins index
app/controllers/api/v1/pins_controller.rb
class Api::V1::PinsController < ApplicationController
  include NetHttpModule

  def index
    # Pinterest APIのAccess Tokenはcredentialsで管理
    url = "https://api.pinterest.com/v1/me/pins/?access_token=#{Rails.application.credentials.api_key[:pinterest]}&fields=id%2Cnote%2Curl%2Cimage"
    # NetHttpModuleで定義したapi_getメソッドを使用
    response = api_get(url)
    # 429(リクエスト多すぎ)ならエラーメッセージを返す
    if response.code == "429"
      render json: { error: response.message }, status: response.code
    elsif response.code == "200"
      #privateで定義したメソッドを使用してDBにpin情報を保存
      save_pins_and_cursor(response)
      # Vue.jsに返すJSONを作成する(この辺は必要に応じて変更)
      res = {
        message: response.message,
        pins: Pin.all.as_json,
      }
      render json: res, status: response.code
    else
      render json: { error: response.message }, status: response.code
    end
  end

  private

  def save_pins_and_cursor(response)
    pins = JSON.parse(response.body)['data']
    # 返ってきたデータの数だけpin情報をDBに保存する
    pins.each do |pin|
      Pin.create(
                  pin_id: pin['id'], # Pinterestが各ピンにつけている一意なID
                  pin_url: pin['url'], # Pinterestの該当ピンに飛ぶURL
                  image_url: pin['image']['original']['url'], # 画像が保存されているURL
                  width: pin['image']['original']['width'], # 画像の幅
                  height: pin['image']['original']['height'] # 画像の高さ
                )
    end
  end
end

あとはこれで返したJSONをフロントエンド側でゴニョゴニョすればOKです!

【便利】APIを試せるツールも公式に用意されている

こちらのリンクから、APIの各種機能を試せるAPI Explorerにアクセスできます。

GUIで使えるのは頭が疲れてるときにも優しいですね。便利。

スクリーンショット 2020-02-12 18.29.21.png

以上です!

おわりに

最後まで読んで頂きありがとうございました:bow_tone1:

どなたかの参考になれば幸いです:relaxed:

参考にさせて頂いたサイト(いつもありがとうございます)

4
3
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
4
3