LoginSignup
6
4

More than 5 years have passed since last update.

PHPで中継用WebAPIを作成する

Posted at

PHPで中継用WebAPIを作成した際のメモ。

基本情報

  • 執筆:2018/5/8
  • OS:Windows10(64bit)
  • nginx ver:1.14.0
  • PHP-FPM ver:7.2.4
  • インタフェース:json

機能概要

イメージは下図のとおり。HTTP POSTリクエストを受けて外部のWebAPIにアクセスし、返却されたデータを編集してresponseデータを返却する。

POSTで受け渡されたパラメータの取得(上図②部分)

受け渡される形式により処理を変える必要がある。

  • HTMLフォームでリクエストが受け渡される場合
$_POST['id'];
  • jsonで受け渡される場合(今回のケース)
$params = json_decode(file_get_contents('php://input'), true);
echo $params['id'];

※こちらのサイトを参考にさせて頂きました。
http://blog.takady.net/blog/2017/10/28/php_get_json_from_post_request_body/

PHPからのPOSTリクエスト(上図③部分)

パラメータ、レスポンス共にjson形式でやり取りするAPIなので、json_encode/decodeを利用し連想配列との変換を行う。

// API仕様に基づく構造をまず連想配列で作成しjson形式へencode
$param = array('name1' => 'value1', 'name2' => 'value2');
$data_json = json_encode($param);
// リクエストヘッダーは仕様に基づいて設定
$header  = array(
    'Content-Type: application/json',
    'charset: UTF-8'
);
// contextはお決まり(かな?)
$context = array(
    "http" => array(
        "method"  => "POST",
        "header"  => implode("\r\n", $header),
        "content" => $data_json
    )
);
$context = stream_context_create($context);
// URLはもちろん仕様に基づくものへ。返却値は再び連想配列へdecode
$contents = file_get_contents('http://hogehoge.com/jsonapi', false, $context);
$res_json = json_decode($contents , true);                
6
4
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
6
4