LoginSignup
0
0

RailsのRestClientで日本語のクエリが送れない

Posted at

はじめに

RailsでAPIを叩く時になぜか日本語のクエリだけがうまくいかなかったのでまとめます

問題

検索機能を作成しており、キーワードを使って他のAPIを叩く実装をしていました

  def get_contract_by_keyword(keyword)
    return nil if company_name.blank?

    url = UserApi.protocol + "#{UserApi.host}:#{UserApi.port}/v1/contract?keyword=#{keyword}"
    p url

    begin
      res = RestClient.get(url)
      data = JSON.parse(res.body)

なぜか英語での検索はいけるのですが、日本語でAPIにリクエストがうまくいっていませんでした

解決方法

RestClientは以下のようにパラメーターを付与するようでした

  def get_contract_by_keyword(keyword)
    return nil if keyword.blank?

    url = UserApi.protocol + "#{UserApi.host}:#{UserApi.port}/v1/contract"
    p url

    begin
      res = RestClient.get(url, params: {keyword: keyword})
      data = JSON.parse(res.body)

おそらくurlには日本語が入ることがないのでエンコードされているようです

おわりに

RestClientの仕様について調べたので早くかいけつできてよかったです

参考

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