Help us understand the problem. What is going on with this article?

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

はじめに

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away