外部連携APIを開発する際に、環境がないといったケースに対応するためスタブってテストを行う。そのために簡単なスタブを構築します。
<?php
/* スタブAPIが受け付けるPOSTパラメータ:name */
header('Access-Controll-Allow-Origin: *');
// header('Access-Controll-Allow-Origin: http://192.168.56.10:8000/post.php');
header('Access-Controll-Allow-Credentials: false'); // Basic認証やCookieのやりとりをする場合に必要
header('Access-Controll-Allow-Headers: Content-Type');
header('Content-Type: application/json; charset=utf-8');
date_default_timezone_set('Asia/Tokyo');
if(isset($_POST['name']) === false || $_POST['name'] === ''){
$_POST['name'] = 'TEST_API';
}
$postName = htmlspecialchars($_POST['name'], ENT_QUOTES);
$array = [
'name' => $postName . '_RECIEVED',
'date' => date("Y-m-d H:i:s"),
];
$json = json_encode($array);
// $file = new SqlFileObject('log.txt', 'a');
// $file->fwrite(
// "【→API】RequestParameter:" . $postName . "'\n【←API】ReturnParameter :" . $json . "\n----------\n"
// );
echo $json;
exit;
$url = "http://192.168.56.10:8000/api.php";
// 設定するHTTPヘッダフィールド
$headerdata = array(
'Content-Type: application/json',
'X-HTTP-Method-Override: GET'
);
$param = array(
"name" => "taro"
);
$postdata = json_encode($param);
$ch = curl_init($url);
$options = array(
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => $headerdata,
CURLOPT_POSTFIELDS => $postdata
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$response_info = curl_getinfo($ch);
$response_code = $response_info['http_code'];
$response_header_size = $response_info['header_size'];
curl_close($ch);
if($response_code == 200){
print "[Result] success.\n";
} else {
print "[Result] failed [$response_code]. \n";
}
$response_body = substr($response, $response_header_size);
print "[ResponseData]\n".trim($response_body);
なるほど、このような仕組みなのか…