LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby on Rails】API 作成 してみた

Posted at

背景

Dockerを用いてRuby on Railsの環境構築をしてみたので、簡単に何かしらの成果物を作成しようと試みたところに。

↓Dockerを用いたRuby on Railsの環境構築はこちら
【初心者用】Docker を用いた Ruby on Rails の環境構築

Railsの環境構築できたから何か簡単なものを作ってみたい、とりあえずポートフォリオを作成したい、といった人向けの記事です。

今回作成していくもの

スクリーンショット 2023-04-08 11.12.11.png
FarStepさん、がYoutube上でRuby on Railsを用いてAPIを作成されていました。
こちらを参考にさせていただき、全く同じ手順で作っていこうかと。

↓リンク
【Ruby on Rails】rails で api を叩いてみよう(初心者から中級者向け)Use an API with Ruby on Rails

PC環境

  • MacBook Pro (M1 Max, 2021)
  • mac OS Monterey (ver 12.5)
  • SSD 2TB
  • RAM 32GB
  • Docker 20.10.21

手順

ファイルの編集はローカル環境で行うため、作業ディレクトリに移動します。
コマンドプロンプトもcd コマンドを使いながら、作業ディレクトリに移動します。
スクリーンショット_2023-04-07_16_18_14.png
スクリーンショット_2023-04-08_11_45_54-3.png

以下のコマンドを叩いて、コンテナ内に入ります。

docker-compose exec web bash

スクリーンショット_2023-04-08_11_54_10.png
そうすると、コンテナ内に入れるようになります。
スクリーンショット_2023-04-08_11_55_53.png

続いて、コンテナ内で下記コマンドを実行し,app/controllers/内にsearchコントローラーを作成します。

rails g controller search search

スクリーンショット_2023-04-08_12_10_26.png

vscodeなどのエディターに移動し、ルーティングを記述するため、/config/route.rb を以下のように書き換えます。

route.rb
Rails.application.routes.draw do
  get 'search', to: "search#search"
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  # root "articles#index"
end

検索するフォームを作るために、/app/views/layouts/application.html.erb を以下のように書き換えます。

application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>PostalCodeSearch</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <div class="container">
      <%= form_with url: search_path, method: :get, local: true do |f| %>
        <%= f.text_field :postal_code, class: "search_form", placeholder: "郵便番号を入力してください" %>
      <% end %>
      <%= yield %>
    </div>
  </body>
</html>

Search コントローラを書き換えます。
/app/controllers/search_controller.rbを、以下のように書き換えます。

search_controller.rb
class SearchController < ApplicationController
  def search
    if postal_code = params[:postal_code]
      require 'net/http'
      params = URI.encode_www_form({zipcode: postal_code})
      uri = URI.parse("http://zipcloud.ibsnet.co.jp/api/search?#{params}")
      response = Net::HTTP.get_response(uri)
      result = JSON.parse(response.body)
      if result["results"]
        @zipcode = result["results"][0]["zipcode"]
        @address1 = result["results"][0]["address1"]
        @address2 = result["results"][0]["address2"]
        @address3 = result["results"][0]["address3"]
      end
    end
  end
end

search_controller.rbを書き換える際に、動画上のと一点違うところがあるのですが、

require 'net/http'

4行目に、require 'net/http'を打たないと「uninitialized constant Net::HTTP」のエラーが出ます。
私のRailsのバージョンが7だからなのかよくわかりませんが、念の為打っておいてください。

上記が完了したら、/app/views/search/search.html.erb を以下のように書き換えます。

search.html.erb
<p>
  郵便番号:<%= @zipcode %>
</p>
<p>
  都道府県:<%= @address1 %>
</p>
<p>
  市区町村:<%= @address2 %>
</p>
<p>
  町域:<%= @address3 %>
</p>

最後に見栄えを良くするために、/app/assets/stylesheets/application.cssを以下のように書き換えます。

application.css
*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */

 .container {
    margin-top: 50px;
    text-align: center;
  }
 
  .search_form{
    width: 400px;
    padding: 10px 15px;
    font-size: 16px;
    border-radius: 3px;
    border: 2px solid #ddd;
  }

以上が完了し、ブラウザのURLに「http://localhost:3000/search」と打って、郵便番号を入力し、都道府県名などが表示されると成功です。
スクリーンショット_2023-04-10_12_50_17.png

本当はビデオとかも載せたいのですが、モザイクかけるのめんどくさかったので割愛。

最後に

折角、Ruby on Railsの環境を構築できたのでAPIを作成。
細かい説明であったり、ファイルの場所がわからない等は、FarStepさんの動画を参照してください。

0
0
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
0
0