【问题标题】:REST API Implementation Sample CodeREST API 实现示例代码
【发布时间】:2023-09-03 17:16:01
【问题描述】:

我对实现 API 一无所知。我确实有点了解 PHP。我有一种情况,我需要调用 REST API 方法来清除 CDN 服务器上的缓存。有人可以帮我提供一些示例代码吗?

以下是示例请求:

PUT <<url>>
Authorization: TOK:12345-12345
Accept: application/json
Content-Type: application/json
Host: api.edgecast.com
Content-Length: 87
{
   "MediaPath":"<<urlhere>>"
   "MediaType":"3"
}

有人可以帮我编写代码来实现这个 rest api 请求吗? 提前致谢。

【问题讨论】:

    标签: php json rest


    【解决方案1】:

    我也必须找到困难的方法。这已经过测试(对我的原始代码稍作修改)

    //## GoGrid PHP REST API Call
    
    define('TOKEN','XXXXX-XXXXX-XXXXX-XXXXXX');     // found on the cdn admin My Settings
    define('ACCOUNT_NUMBER','XXXX');        // found on the cdn admin Top Right corner
    
    function purgeCacheFileFromCDN($urlToPurge) {
      //## Build the request
      $request_params = (object) array('MediaPath' =>  $urlToPurge, 'MediaType' => 8);   // MediaType 8=small 3=large
      $data = json_encode($request_params);
    
      //## setup the connection and call.
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, 'https://api.edgecast.com/v2/mcc/customers/'.ACCOUNT_NUMBER.'/edge/purge');
      curl_setopt($ch, CURLOPT_PORT , 443);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLINFO_HEADER_OUT, 1);                  // For debugging
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);             // no caching  
      curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);            // no caching  
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
      curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: tok:'.TOKEN, 'Content-Type: application/json','Accept: application/json', 'Content-length: '.strlen($data)));
      $head = curl_exec($ch);
      $httpCode = curl_getinfo($ch);
      curl_close($ch);
    
      //## check if error
      if ($httpCode['http_code'] != 200) {
        echo 'Error reported: '.print_r(array($head,$httpCode),1);  // output it to stdout this will be emailed to me via cron capture.
      }
    }
    

    【讨论】:

      【解决方案2】:

      懒得从头开始写,所以从谷歌在结果第一页建议的 amazingly pink 网站复制。

          $data = array("a" => $a);
          $ch = curl_init($this->_serviceUrl . $id);
      
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
          curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
      
          $response = curl_exec($ch);
          if(!$response) {
              return false;
          }
      

      PS:来源搜索请求:http://www.google.ru/search?q=php+sample+put+request+curl

      【讨论】:

      • 天哪,它是惊人的粉红色。还有一个奇怪的仙女。 +1
      【解决方案3】:

      Here 是我完全实现的 Grunt 任务的源代码,供其他考虑使用 EdgeCast API 的人使用。您会在我的示例中发现,我使用节点模块执行 curl 命令来清除 CDN。

      这是我花了几个小时试图让 HTTP 请求在 Node.js 中工作后得到的结果。我能够得到一个在 Ruby 和 Python 中工作的人,但不符合这个项目的要求。

      【讨论】: