LoginSignup
15
17

More than 3 years have passed since last update.

Guzzleを使って外部APIへPOST送信

Last updated at Posted at 2020-05-16

Guzzleとは

PHP用のHTTPクライアントライブラリです。
WEBサーバに外部APIへPOST送信などを行いたい際にGuzzleが非常に便利でした。

導入方法・簡単な使い方をまとめてみました。

インストール方法

composerコマンドでguzzlehttp/guzzleパッケージのインストール

composer require guzzlehttp/guzzle

2020年5月現在、最新は6.5のようです。

composer.json
{
    "require": {
        "guzzlehttp/guzzle": "^6.5"
    }
}

使い方

app/src/Controller/Front/ApiController.php
use GuzzleHttp\Client;

public function getSession()
{
    $session = $this->request->getSession(); //セッションを取得
    $data = $session->read('data');          //Formで入力しているデータを取得します

    $this->postApi($data); 
    //略
}

public function postApi($data)
{
    $url         = "https://external.api";                  //API側(受取側)のURLを指定
    $basic       = "basic-id:basic-password"                //basic認証のIDとPASSWORD ※envに格納しましょう
    $encodeBasic = base64_encode($basic);                   //basic認証をエンコーディング
    $config      = ['base_uri' => 'https://www.this.com/']; //送信元のURLを指定

    $client = new Client($config);

            $option = [
            'http_errors' => true,                             //エラーを出力
            'verify'      => false,                            //SSL認証を無視

            'headers' =>    //ヘッダーにBASIC認証などを追加
            [                                     
                'Authorization' => 'Basic ' . $encodeBasic,    //エンコードしたbasic認証です。外部API側でデコードしてください
                'Host'          => "external.api",             //外部APIのホスト指定
                'Content-Type'  => "text/plain",               //コンテントタイプを指定 無くてもできました。
            ],

            'form_params' => //application / x-www-form-urlencoded POSTリクエストを送信するために使用
            [
                "username"      => $data["name"],      //外部APIとカラム名が異なっていたのでここで修正。
                "tel"           => $data["telephone"], //同上
                "address"       => $data["mail"],      //同上
                "contents"      => $data["content"],   //同上
            ],
        ];

    $response = $client->request("POST", $url, $option); //第1引数はPOST or GET、第2引数は受取側のAPI,第3引数はPOST送信データ
}

レスポンスのステータスコードのチェック

app/src/Controller/Front/ApiController.php
    $response->getStatusCode(); 

参考にした資料

Guzzleドキュメント
http://docs.guzzlephp.org/en/stable/index.html

Guzzle Httpを試してみたよ clustfe様
https://qiita.com/clustfe/items/f9ff2b12da7a501197f8

Guzzleでファイルアップロードする zaburo様
https://qiita.com/yousan/items/2a4d9eac82c77be8ba8b

15
17
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
15
17