LoginSignup
1
2

More than 1 year has passed since last update.

【超簡単】RailsでAPI叩いてレシピ検索サイト作ってみた

Posted at

今回のやりたいこと

https://www.edamam.com/ で料理APIを登録し、railsアプリ内でレシピの検索をできるようにする

Edamamの登録

このURLにアクセスする。
基本情報を入力し、sign upする。
image.png

右上のAccountsボタンからGo to Dashboardをクリックする。
ApplicationsのCreate a new applicationをクリックする。
image.png

Recipe Search APIをクリックする
image.png
適当に入力して、Create Applicationをクリック
image.png
後で使うので、Application IDとApplication Keysをメモしておいてください
これでEdamamの設定終わり
ちなみにこのリンクの下記の場所をクリックするとAPIの詳細がわかると思います
Screenshot 2023-03-06 2.50.41.png

簡単に紹介すると、、、
https://api.edamam.com/api/recipes/v2?type=public&q=<検索したいキーワード>&app_id=<自分のid>&app_key=<自分のkey>&calories=<検索したいカロリー>
こんな感じです。

Railsアプリ

次に、rails側で先ほどのAPIを叩いていこうと思います。

Gemfile
gem 'dotenv-rails'
gem 'httpclient'

dotenv-railsはenvファイルを扱うためで、httpclientはHTTP通信をするためのGemです。

terminal
bundle install

アプリケーションディレクトリ直下に.envファイルを作成

.env
application_id = "自分のApplication ID"
application_keys = "自分のApplication Keys"
.gitignore
/.env

ページ表示するためにroute書いてるだけです。

routes.rb
  resources :edamams
# どっちでも可
  get "/edamams", to: "edamams#index"
terminal
rails g controller edamams
edamams_controller
class EdamamsController < ApplicationController
  require 'httpclient'
  def index
    if params[:search].blank?
      query = "banana"
    else
      query = params[:search]
    end
    client = HTTPClient.new()
    res = client.get("https://api.edamam.com/api/recipes/v2?type=public&q=#{query}&app_id=#{ENV['application_id']}&app_key=#{ENV['application_keys']}")
    @foods = JSON.parse(res.body)
  end
end
edamams/index.html
<h1>料理検索</h1>
<%= form_tag({controller:"edamams",action:"index"}, method: :get) do %>
  <p>英語で検索してね〜</p>
  <%= text_field_tag :search %> <br>
  <%= submit_tag '検索する'  %>
<% end %>

<% @foods["hits"].first(5).each do |recipe| %>
  <%= link_to recipe["recipe"]["label"], recipe["recipe"]["url"] %> <br>
  <%= recipe["recipe"]["calories"] %>cal <br>
  <%= image_tag recipe["recipe"]["image"] %> <br>
<% end %>

料理名 recipe["recipe"]["label"]
レシピへのリンク recipe["recipe"]["url"]
料理のカロリー recipe["recipe"]["calories"]
料理の画像 recipe["recipe"]["image"]

これ以外にも取得できるデータはあるので探してみてください
Postmanで見ればすぐわかるかと思います
Screenshot 2023-03-06 3.02.08.png

image.png
最後こんな感じになってればオッケです!
終わり〜〜〜

1
2
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
1
2