LoginSignup
0
0

More than 3 years have passed since last update.

PHPでGuzzleを使ったHTTPリクエスト

Posted at

はじめに

PHPからguzzleを使用して外部API(GithubやQiitaなど)をシンプルに実行するためのメモです。
エラー処理だけLaravel独自のメソッドがありますが、ほとんどフレームワークを選ばず使用できます。

guzzleとは

シンプルなインターフェースで同期、非同期リクエストを行えるPHPのHTTPクライアントになります。

詳しくはこちら↓
https://github.com/guzzle/guzzle

実装

まずはベース部分を実装します。

    /**
     * @param string $base_url
     * @param string $path
     * @param array $headers
     * @param array $form_params
     * @param string $method
     * @return array
     */
    private function requestClient(
        string $base_url,
        string $path,
        array $headers,
        array $form_params = [],
        string $method = 'GET'
    ): array {
        try {
            $client = new \GuzzleHttp\Client([
                'base_uri' => $base_url,
            ]);

            $response = $client->request($method, $path, [
                'headers' => $headers,
                'form_params' => $form_params,
            ]);
            return json_decode($response->getBody()->getContents(), true);
        } catch (\GuzzleHttp\Exception\GuzzleException $e) {
            report($e); // ログ出力
            return [];
        }
    }
Qiitaからの取得
    /**
     * @return array
     */
    public function getQiitaList(): array
    {
        $base_url = 'https://qiita.com';
        $path = '/api/v2/authenticated_user/items?page=1&per_page=20';
        $headers = ['Authorization' => 'Bearer xxxxxxxxxxxxxxxxx'];
        return $this->requestClient($base_url, $path, $headers);
    }
Githubからの取得
    /**
     * @return array
     */
    public function getGithubList(): array
    {
        $base_url = 'https://api.github.com';
        $path = '/repos/terumichi1209/laravel-test/commits?sha=develop';
        $headers = [];
        return $this->requestClient($base_url, $path, $headers);
    }

終わりに

要件によってはこの辺りのオプション使うと良さそうです。
http://docs.guzzlephp.org/en/latest/request-options.html

0
0
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
0
0