kakakakakku blog

Weekly Tech Blog: Keep on Learning!

Unsplash API (unsplash_rb) を試した

写真サービスだと Unsplash が大好きで,気分転換に見ることも多いし,発表資料の背景写真はほとんど Unsplash から引っ張ってきている.全ての写真を自由に使えるし,シンプルなサービスながら,非常にクオリティが高い.

Unsplash 関連ツール

公式で Chrome 拡張も提供されていて,Unsplash Instant を使うと,新規タブの背景写真を Unsplash からランダムに取得できるようになってオススメ!

chrome.google.com

あと,最近だと Trello と Unsplash の連携があり,Trello のタスクボードの背景写真を Unsplash から引っ張ってくることができるようになった.この機能も気に入ってて,定期的に背景写真を変えて Trello に飽きないように工夫している.

trello.com

Unsplash API

そんな Unsplash から API が提供されていることを最近知って,さらに Ruby ラッパーも公式で提供されていたため,少し試してみた.事前に Application ID を取得しておく必要がある.なぜ今まで知らなかったのだろう!

unsplash.com

github.com

サンプルコード

ザッと書いてみた.キーワード検索だけじゃなく,キュレーション検索もできるし,ランダム検索もできる.また,写真によっては Exif 情報も取れるし,ロケーションも取れる場合もある.他にもまだまだ多くのレスポンスが返ってくるので,詳しくはドキュメントを参照してもらえればと.あと,utm パラメータを付けないとダメなど,ある程度のガイドラインがあるため,実際にアプリケーションに組み込む場合は,確認しておく必要がありそう.

require 'unsplash'
require 'active_support'
require 'active_support/core_ext'

Unsplash.configure do |config|
  config.application_id = ENV['UNSPLASH_APPLICATION_ID']
  config.application_secret = ENV['UNSPLASH_SECRET']
  config.application_redirect_uri = 'https://example.com/callback'
  config.utm_source = 'example_app'
end

def info(photo)
  # Basic
  puts "===== #{photo.id} ====="
  puts photo.width
  puts photo.height

  # Exif
  if photo.exif.present?
    puts photo.exif.make
    puts photo.exif.model
    puts photo.exif.iso
  end

  # Location
  if photo.location.present?
    puts photo.location.city
    puts photo.location.country
  end

  # URL
  if photo.urls.present?
    puts photo.urls.raw
    puts photo.urls.full
    puts photo.urls.thumb
  end
end

# Find by id
photo = Unsplash::Photo.find('srDN5nHM35g')
info(photo)

# Search by keyword
search_results = Unsplash::Photo.search('mountain', page = 1, per_page = 3)
search_results.each do |photo|
  info(photo)
end

# Search curation ( latest, oldest, popular )
search_results = Unsplash::Photo.curated(page = 1, per_page = 3, 'popular')
search_results.each do |photo|
  info(photo)
end

# Search random
photo = Unsplash::Photo.random
info(photo)

Ruby 以外の公式ライブラリ

PHP と js も提供されていた!

github.com

github.com

Unsplash Team の Hiring も発見して,Rails Engineer ならリモート歓迎って書いてある.気になるなー!

unsplash.com