2017-08-14 8 views
0

私はPhPを初めて使い、curlを使用してサードパーティAPIにリクエストしようとしています。これが私の試みですが、APIのルートエンドポイントにあるものだけで応答しています。PHPでのCurl APIコール

$service_url = 'http://api.kivaws.org/graphql'; 
$curl = curl_init($service_url); 
$curl_post_data = array(
     'Pragma' => 'no-cache', 
     'Origin' => 'http://api.kivaws.org', 
     'Accept-Encoding' => 'gzip, deflate', 
     'Accept-Language' => 'en-US,en;q=0.8', 
     'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36', 
     'content-type' => 'application/json', 
     'accept' => 'application/json', 
     'Cache-Control' => 'no-cache', 
     'Connection' => 'keep-alive', 
     'data' => '{"query":"{ 
      loans (filters: {gender: male, status:funded, country: [\"KE\", \"US\"]}, sortBy: newest, limit: 2) { 
      totalCount 
      values { 
       name 
       status 
       loanAmount 
      } 
      } 
     }","variables":null,"operationName":null}' 
); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data); 
$curl_response = curl_exec($curl); 
if ($curl_response === false) { 
    $info = curl_getinfo($curl); 
    curl_close($curl); 
    die('error occured during curl exec. Additioanl info: ' . var_export($info)); 
} 
curl_close($curl); 

echo $curl_response; 
+0

あなたは、エンドポイントの応答が何であるかを投稿PLSすることはできますか? –

+0

希望する出力は何ですか? –

+0

こんにちは@ブレット私はあなたのApiカールからこの応答を得ましたこれは正しいですか? ** {"データ":{"hello": "KivaのGraphQL APIへようこそ!"}} ** –

答えて

0

これはトリックをやっているように見える:それは体内で私たちに結果を返し、その後、json_encodeを使用してクエリをコードするようにTrueCURLOPT_HTTPHEADERCURLOPT_RETURNTRANSFERのようないくつかの重要なことを、設定するcurl_setoptを使用。

$service_url = 'http://api.kivaws.org/graphql'; 

$curl = curl_init($service_url); 

$curl_post_data = array("query" => '{loans (filters: {gender: male, status:funded, country: ["KE", "US"]}, sortBy: newest, limit: 2) {totalCount values { name status loanAmount }}}'); 
$data_string = json_encode($curl_post_data); 
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json', 
    'Content-Length: ' . strlen($data_string)) 
); 

$curl_response = curl_exec($curl); 
if ($curl_response === false) { 
    $info = curl_getinfo($curl); 
    curl_close($curl); 
    die('error occured during curl exec. Additioanl info: ' . var_export($info)); 
} 
curl_close($curl); 
echo $curl_response; 
echo $info; 

これは私を返します。

{"data":{"loans":{"totalCount":40425,"values":[{"name":"Davis","status":"funded","loanAmount":"100.00"},{"name":"James","status":"funded","loanAmount":"100.00"}]}}} 
+0

素晴らしいです。ありがとう、トン。 – Brett

関連する問題