高木のブログ

codicのAPIをRubyで試してみる

2019/06/07

前回の記事の続き的な。(codicのAPIを試してみる | 高木のブログ)
Rubyで書くとこんな感じになる。

require 'net/http'
require 'uri'
require 'json'

uri = URI.parse(URI.encode('https://api.codic.jp/v1/engine/translate.json?text=記事を書く&casing=lower+underscore'))
request = Net::HTTP::Get.new(uri)
request['Authorization'] = 'Bearer {ACCESS_TOKEN}'

response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(request)
end

JSON.parse(response.body)
# => [
#        {
#            "successful": true,
#            "text": "記事を書く",
#            "translated_text": "write_article",
#            "words": [
#                {
#                    "successful": true,
#                    "text": "書く",
#                    "translated_text": "write",
#                    "candidates": [
#                        {
#                            "text": "write"
#                        },
#                        {
#                            "text": "writing"
#                        }
#                    ]
#                },
#                {
#                    "successful": true,
#                    "text": "を",
#                    "translated_text": null,
#                    "candidates": [
#                        {
#                            "text": null
#                        },
#                        {
#                            "text": "that"
#                        },
#                        {
#                            "text": "to"
#                        },
#                        {
#                            "text": "for"
#                        },
#                        {
#                            "text": "from"
#                        },
#                        {
#                            "text": "is"
#                        },
#                        {
#                            "text": "of"
#                        }
#                    ]
#                },
#                {
#                    "successful": true,
#                    "text": "記事",
#                    "translated_text": "article",
#                    "candidates": [
#                        {
#                            "text": "article"
#                        },
#                        {
#                            "text": "posts"
#                        },
#                        {
#                            "text": "post"
#                        },
#                        {
#                            "text": "news"
#                        }
#                    ]
#                }
#            ]
#        }
#    ]

Pixela