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
1class Api::TranslationsController < ApplicationController 2 require 'httpclient' 3 4 def translate 5 api_key = Rails.application.credentials.deepl[:api_key] 6 url = "https://api-free.deepl.com/v2/translate" 7 client = HTTPClient.new 8 query = { 9 auth_key: api_key, #認証キー 10 text: "This is a test", #翻訳したい文章 11 target_lang: "JA" #日本語で翻訳結果を表示する 12 } 13 @response = client.get(url, params: query) 14 render json: @response 15 end 16end
routes.rb
1namespace :api, format: 'json' do 2 get '/translate', to: 'translations#translate' 3end
Vue.js側設定
Vue
1methods: { 2translateWithDeepL: function() { 3 axios.get('/api/translate') 4 .then(response => { 5 this.result = response.data 6 console.log(response.data) 7 }) 8 } 9}
実行結果(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"あたりに原因があると考えていますが全く別の原因が考えられる場合はその旨もご教示いただけると幸いです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/01/27 11:12