Post

ランダムな猫の画像を取得するAPIを作ってみた!

ランダムな猫の画像を取得するAPIを作ってみた!

既存のプロジェクトを使って、ランダムな猫の画像を取得するAPIを作ってみました。 猫の画像はGoogle 検索APIを使って取得します。

事前準備

1. Google APIの有効化

Custom Search JSON APIでAPIキーを取得します。

googleApi キーを取得ボタンを押すとAPIキーが取得できます。

2. Google cx ID 取得

Google Custom Search EngineでGoogle cx IDを取得します。

googleCxId

  1. 検索エンジンを選択するか、新規作成します
  2. 「検索エンジンID」という項目にCX IDが表示されています
  3. パブリックURLのクエリパラメータ「?cx=**」でもCX IDを確認できます

3. guzzleのインストール

1
composer require guzzlehttp/guzzle

プロジェクトディレクトリに移動して、上記のコマンドを実行します。

4. .envファイスの設定

1
2
GOOGLE_API_KEY= APIキー
GOOGLE_CX= CXキー

前の段階で取得したAPIキーとCX IDを.envファイルに設定します。

5. コントローラーの作成

1
php artisan make:controller CatImageController

app/Http/Controllers/CatImageController.phpが作成されました。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;

class CatImageController extends Controller
{
    public function getRandomCatImage()
    {
        $googleApiKey = config('services.google.api_key');
        $googleCx = config('services.google.cx');

        $query = 'cute cat';
        $url = "https://www.googleapis.com/customsearch/v1";

        $client = new Client();
        try {
            $response = $client->get($url, [
                'query' => [
                    'key' => $googleApiKey,
                    'cx' => $googleCx,
                    'q' => $query,
                    'searchType' => 'image',
                    'num' => 10, 
                    'start' => rand(1, 90),
                ],
            ]);

            $data = json_decode($response->getBody(), true);

            if (isset($data['items']) && count($data['items']) > 0) {
                $randomImage = $data['items'][array_rand($data['items'])]['link'];
                return response()->json(['image' => $randomImage], 200);
            } else {
                return response()->json(['error' => 'No images found'], 404);
            }
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to fetch images'], 500);
        }
    }
}

コントローラーの内容を作成します。

‘start’ => rand(1, 90),で検索開始位置をランダムに設定します。

6. Routing設定

1
2
3
use App\Http\Controllers\CatImageController;

Route::get('/random-cat', [CatImageController::class, 'getRandomCatImage']);

routes/api.phpに上記の内容を追加します。

7. サービス設定

1
2
3
4
5
6
7
8
return [
    //...

    'google' => [
        'api_key' => env('GOOGLE_API_KEY'),
        'cx' => env('GOOGLE_CX'),
    ],
];

config/services.phpに上記の内容を追加します。

8. テスト

8.1 ローカルサーバを起動

1
php artisan serve

8.2 Getリクエストを送信

alt text

http://127.0.0.1:8000/api/random-cat にGetリクエストを送信します。

猫の写真

可愛い猫の写真が返ってきました。

This post is licensed under CC BY 4.0 by the author.