Try using the Rails API (zip code)

There was a video of hitting the API on Youtube and it was very easy to understand While doing hands-on, if you don't understand something I will dig deep and write a research article.

I don't need to read anything in particular If you can parse the URL properly, you can use it

Operating environment

ruby 2.5.1p57 Rails

What is API?

API:(Application Programming Interface)… Interface → The part that becomes the ** window ** for using the functions of the application

It is usually published on the Web and can be used by anyone for free. You will be able to embed the functions of other software in your own software

API is a function for linking with external applications.

** Hitting the API ** is ... Going to get data using the API The returned data is ** JSON format text **


・ ** Can develop with more new services ** → It is possible to specialize in a certain function, or to make it easier to use and improve only some functions. ・ ** Data can be used secondarily ** → You can use data from other companies and easily analyze the information. ・ ** Can be developed efficiently ** → If the function you want to create is published by API, you do not need to create the same program from scratch ・ ** Improved convenience for service users ** → You can create a function that allows you to log in using the user information of other companies. ・ ** Improved security ** → You can use the system of a company with a high security level

Let's actually use it


rails new app name

So, create a Searches controller, the action name is "search"

rails g controller searches search

Describe the routing


Rails.application.routes.draw do
  get 'search', to: 'searches#search'

Create form

Next, modify the view


<!DOCTYPE html>
    <title>Post code search engine</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

    <div class="container">
      #Send with get
      <%= form_with url: search_path, method: :get, local: true do |f| %>
        <%= f.text_field :postal_code, class: "search_form", placeholder: "Please enter your zip code" %>
      <% end %>
      <%= yield %>

【point】 -The form_with method performs ** ajax asynchronous communication ** by default. Therefore, HTML will not be rendered without the local: true option. -Specify the parameter name in the part of <% = f.text_field: postal_code%> → You can get it by typing "params [: postal_encode]" on the controller. ・ Enter the default characters in the form with placeholder

Controller implementation

Next, we will implement the contents of the controller


class SearchsController < ApplicationController
  # require 'net/http'

  def search
    #Get the parameters sent in the form
    if postal_code = params[:postal_code]
      #Encode here. URI.encode_www_In the form method, "zipcode" at the end of the URL=Making a "zip code"
      params = URI.encode_www_form({zipcode: postal_code})
      #Get the URL with this, params is a variable so you need to expand it
      uri = URI.parse("{params}")
      #Getting the response, GET![Screenshot 2020-12-18 23.46.27.png](

      response = Net::HTTP.get_response(uri)
      #Convert to JSON format
      if result = JSON.parse(response.body)
        #Stored in an instance variable for use in view
        #Get by specifying the prefecture name and city / ward / town / village in the response
        @zipcode = result["results"][0]["zipcode"]
        @address1 = result["results"][0]["address1"]
        @address2 = result["results"][0]["address2"]
        @address3 = result["results"][0]["address3"]

** URI.encode_www_form ** method What is encode ... According to certain rules, data in a certain format such as characters Converting to data in another format

Completed screen

[Click here for the completed screen] Just hit the URL and insert the zip code and you'll get this result スクリーンショット 2020-12-18 23.52.24.png

We will also create a view that displays the acquired results


<p>Postal code: <%= @zipcode %></p>
<p>Prefectures: <%= @address1 %></p>
<p>Municipality: <%= @address2 %></p>
<p>Town area: <%= @address3 %></p>

The actual screen looks like this

スクリーンショット 2020-12-19 0.14.48.png

If you get an error

I sometimes got an error, I solved it by doing " require'net/http' "on the controller. Also, if you just want to display it with GET, it seems that you only need to read above (** require **)

Reference video

Recommended Posts

Try using the Rails API (zip code)
[API] I tried using the zip code search API
Try hitting the zip code search API with Spring Boot
Try using the Stream API in Java
Try using the Emotion API from Android
Try using the COTOHA API parsing in Java
Try using view_component with rails
[Rails] Test code using Rspec
[Rails] Try using Faraday middleware
Try using the query attribute of Ruby on Rails
[Rails] Create an echo bot using the LINE Messaging API.
[Ruby on Rails] Automatically enter the address from the zip code
[Parse] Hit the API using callFunctionInBackground
[Rails 6] API development using GraphQL (Query)
Try using the messaging system Pulsar
[Rails 6] destroy using the resources method
Rails API
[Swift] Hit the API using Decodable / Generics
Try using the service on Android Oreo
Rails API server environment construction using docker-compose
Try using JSON format API in Java
Try using Spring Boot with VS Code
Try using the Wii remote with Java
Try using libGDX
ChatWork4j for using the ChatWork API in Java
Try using powermock-mockito2-2.0.2
Try using GraalVM
03. I sent a request from Spring Boot to the zip code search API
Try using jmockit 1.48
Try using sql-migrate
Try using Sourcetrail (win version) in Java code
Try using GCP's Cloud Vision API in Java
Try using Sourcetrail (macOS version) in Java code
The code I used to connect Rails 3 to PostgreSQL 10
Try accessing the dataset from Java using JZOS
Try using SwiftLint
Try using Log4j 2.0
[Rails] Set validation for the search function using Rakuten API (from the implementation of Rakuten API)
Try to summarize the common layout with rails
Try searching for a zip code with REST API using SpringBoot, H2 DB and JPA REST-Only 3 classes to create-
A review of the code used by rails beginners
Try implementing the Eratosthenes sieve using the Java standard library
Using PAY.JP API with Rails ~ Implementation Preparation ~ (payjp.js v2)
Try to implement using Rakuten product search API (easy)
Rails6: Input the initial data of ActionText using seed
Try global hooking in Java using the JNativeHook library
[Rails] Put together the same code with controller actions
Using PAY.JP API with Rails ~ Card Registration ~ (payjp.js v2)
Differences in code when using the length system in Java
Command to try using Docker for the time being
Try to implement tagging function using rails and js
Try using Axon Framework
Try using JobScheduler's REST-API
Try using java.lang.Math methods
Try using PowerMock's WhiteBox
Try using Talend Part 2
Try using Talend Part 1
Try using F # list
Try using each_with_index method
Master the [Rails] scope!
Try using Spring JDBC