如何使用PHP cURL发出API请求?

时间:2017-08-25 18:42:57

标签: php api curl

我的请求需要令牌才能发出API请求。以下是他们提供的cURL代码示例:

curl -v -L https://api.artsy.net/api/artists/andy-warhol -H 'X-Xapp-Token:myToken'

我的代码:

$postdata = array();
$postdata['client_id'] = 'myId';
$postdata['client_secret'] = 'myClient';
$postdata['xapp_token'] = 'myToken';
$cc =  curl_init();
curl_setopt($cc,CURLOPT_POST,1);
curl_setopt($cc,CURLOPT_RETURNTRANSFER,1);
curl_setopt($cc,CURLOPT_URL,"https://api.artsy.net/api/artists/andy-warhol");
curl_setopt($cc,CURLOPT_POSTFIELDS,$postdata);
$result = curl_exec($cc);
echo $result;

这应该会产生一个类似于:

的JSON对象
{
  "id": "4d8b92b34eb68a1b2c0003f4",
  "slug": "andy-warhol",
  "created_at": "2010-08-23T14:15:30+00:00",
  "updated_at": "2017-08-25T17:25:51+00:00",
  "name": "Andy Warhol",
  "sortable_name": "Warhol Andy",
  "gender": "male",
  "birthday": "1928",
  "hometown": "Pittsburgh, Pennsylvania",
  "location": "New York, New York",
  "nationality": "American",
//...

然而,这导致了这个结果:

{:type=>"other_error", :message=>"405 Not Allowed", "X-Frame-Options"=>"DENY", "X-Robots-Tag"=>"noindex", "Allow"=>"OPTIONS, GET, HEAD"}

我对cURL不太熟悉所以我试图翻译他们提供的示例代码时遇到了障碍。任何帮助都将深表感谢!

1 个答案:

答案 0 :(得分:3)

您正在使用POST

curl_setopt($cc,CURLOPT_POST,1);

看起来API不允许POST。

  

..."Allow"=>"OPTIONS, GET, HEAD"

您可以查看this Q&A以获取有关如何使用GET的示例。