Rails にDeepL apiを導入したいのですがcontroller内でhttpclientを用いてgetリクエストを送信するよう実装したところ、status_code:403が帰ってきてしまい、望んだ結果が得られません。
*DeepL公式document
https://www.deepl.com/ja/docs-api/introduction/
# backend Ruby 2.6.5 Rails 6.0.3 #開発環境 docker #frontend Vue.js3
実現したいこと
DeepL api
https://api-free.deepl.com/v2/translate?auth_key=**********&text=hello&target_lang=ja
に対してgetリクエストを送り、
{"translations":[{"detected_source_language":"IT","text":"こんにちわ"}]}
のようなレスポンスを受け取りたい。
Rails側設定
*httpclient gemはinstall済み
api/translations_controller
class Api::TranslationsController < ApplicationController require 'httpclient' def translate api_key = Rails.application.credentials.deepl[:api_key] url = "https://api-free.deepl.com/v2/translate" client = HTTPClient.new query = { auth_key: api_key, #認証キー text: "This is a test", #翻訳したい文章 target_lang: "JA" #日本語で翻訳結果を表示する } @response = client.get(url, params: query) render json: @response end end
routes.rb
namespace :api, format: 'json' do get '/translate', to: 'translations#translate' end
Vue.js側設定
Vue
methods: { translateWithDeepL: function() { axios.get('/api/translate') .then(response => { this.result = response.data console.log(response.data) }) } }
実行結果(response.dataの中身)
"body_size": 0, "chunked": false, "request_method": "GET", "request_uri": { "scheme": "https", "user": null, "password": null, "host": "api-free.deepl.com", "port": 443, "path": "/v2/translate", "query": null, "fragment": null }, "request_query": { "params": { "auth_key": "DeepL認証KEY", "text": "This is a test", "target_lang": "JA" } }, "request_absolute_uri": null, "status_code": 403, "reason_phrase": "Forbidden", "body_type": null, "body_charset": null, "body_date": null, "body_encoding": null, "is_request": false, "header_item": [ [ "Server", "nginx" ], [ "Date", "Wed, 26 Jan 2022 12:06:14 GMT" ], [ "Content-Length", "0" ], [ "Connection", "keep-alive" ], [ "Access-Control-Allow-Origin", "*" ] ], "dumped": false }, "peer_cert": {}, "http_body": { "body": "", "size": 0, "positions": null, "chunk_size": null }, "previous": null }
望んだresponseが得られないのは上記の "status_code": 403, "reason_phrase": "Forbidden"あたりに原因があると考えていますが全く別の原因が考えられる場合はその旨もご教示いただけると幸いです。
まだ回答がついていません
会員登録して回答してみよう