2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GASで翻訳API作成してLaravelで叩くまで

Last updated at Posted at 2020-01-13

はじめに

この記事では

GASで英語から日本語に翻訳するAPIを作成しLaravelで結果を取得までします

GASを作成

こちらの記事を参考に作成しました
3 分で作る無料の翻訳 API with Google Apps Script

controllerを作成

一部抜粋

TransController.php
    public function index() {
        
        $transApiUrl = '公開したAPIのURL';
        $transSource = 'en'; // 翻訳前の言語
        $transTarget = 'ja'; // 翻訳語の言語
        $transText = "Hello"; // 翻訳する文字

        $transApiUrl .= '?text=' . urlencode($transText);
        $transApiUrl .= '&source=' . $transSource;
        $transApiUrl .= '&target=' . $transTarget;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $transApiUrl);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($ch);
        curl_close($ch);



        return $res;
    }

GASの翻訳APIを叩く際に翻訳するテキスト量が多い際に
Moved Temporarily The document has moved here.

と出ることがあります
これは

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
この記載を追加することで回避できます

叩いてみる

APIの配下にcontrollerを作成したので
ルーティングを以下に追記

api.php
Route::get('trans', 'Api\TransController@index')->name('trans');

http://127.0.0.1:8000/api/transにアクセス

結果

{"code":200,"text":"こんにちは"}
2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?