実装した内容
- アクセスすると、クエリパラメータで指定した位置(緯度、経度)から500mの範囲内にあるお店を10件返すAPIの作成。
手順
-
Google APIの準備
- https://console.cloud.google.com/ にアクセスし、新規プロジェクトを作成
- Places API(新規)を有効化する
- APIキーを発行する
-
railsアプリケーションの作成し、プロジェクト内に移動する
rails new yonaka --api cd yonaka
-
Gemfileに以下を追記
gem 'httparty' # HTTPリクエストを送るため gem 'dotenv-rails' # 環境変数管理
-
追加したgemのインストール
bundle install
-
.envファイルをプロジェクト(yonaka)配下に作成しAPIキーを環境変数として定義する
GOOGLE_MAPS_API_KEY=your_google_maps_api_key
-
コントローラーの作成
rails generate controller Shops index
-
作成された
app/controllers/shops_controller.rb
に以下を記述require 'httparty' class ShopsController < ApplicationController def index # リクエストボディの作成 request_body = { includedTypes: ["restaurant"], maxResultCount: 10, locationRestriction: { circle: { center: { latitude: params[:latitude].to_f, longitude: params[:longitude].to_f }, radius: 500.0 } } } # APIキーを環境変数から取得 api_key = ENV['GOOGLE_MAPS_API_KEY'] # HTTPリクエストヘッダーの設定 headers = { "Content-Type" => "application/json", "X-Goog-Api-Key" => api_key, "X-Goog-FieldMask" => "places.id" } # APIエンドポイント url = "https://places.googleapis.com/v1/places:searchNearby" # HTTPartyでPOSTリクエストを送信 response = HTTParty.post( url, body: request_body.to_json, headers: headers ) places = response.parsed_response["places"] result = [] places.each do |place| result << fetch_place_details(place["id"], api_key) end render json: result end private # Place Details APIを呼び出して詳細情報を取得 def fetch_place_details(place_id, api_key) # Google Places APIのエンドポイント url = "https://places.googleapis.com/v1/places/#{place_id}" # リクエストヘッダー headers = { "Content-Type" => "application/json", "X-Goog-Api-Key" => api_key, "X-Goog-FieldMask" => "*" } # GETリクエストを送信 response = HTTParty.get(url, headers: headers) return nil unless response.code == 200 response.parsed_response end end
-
ルーティングの設定
Rails.application.routes.draw do resources :shops, only: [:index] end
-
サーバーを起動して動作確認
rails server
-
http://localhost:3000/shops?latitude=35.658034&longitude=139.701636 にアクセス