【问题标题】:Create function to send requests to an API创建函数以向 API 发送请求
【发布时间】:2020-01-14 03:16:08
【问题描述】:

我有一个 API,我正在尝试创建一个函数来发送请求,文档在这里:http://simportal-api.azurewebsites.net/Help

我想过在 PHP 中创建这个函数:

function jola_api_request($url, $vars = array(), $type = 'POST') {
    $username = '***';
    $password = '***';

    $url = 'https://simportal-api.azurewebsites.net/api/v1/'.$url;

    if($type == 'GET') {
        $call_vars = '';
        if(!empty($vars)) {
            foreach($vars as $name => $val) {
                $call_vars.= $name.'='.urlencode($val).'&';
            }
            $url.= '?'.$call_vars;
        }
    }

    $ch = curl_init($url);

    // Specify the username and password using the CURLOPT_USERPWD option.
    curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  

    if($type == 'POST') {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
    }

    // Tell cURL to return the output as a string instead
    // of dumping it to the browser.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //Execute the cURL request.
    $response = curl_exec($ch);

    // Check for errors.
    if(curl_errno($ch)){
        // If an error occured, throw an Exception.
        //throw new Exception(curl_error($ch));
        $obj = array('success' => false, 'errors' => curl_error($ch));
    } else {
        $response = json_decode($response);
        $obj = array('success' => true, 'response' => $response);
    }

    return $obj;
}

因此,这决定了它是 GET 还是 POST 请求,但某些调用返回的响应是不支持 GET 或不支持 POST,尽管我为每个调用指定了正确的响应。

我认为我的功能以某种方式出错,并想知道是否有人可以帮助我朝着正确的方向前进?正如我也注意到的,我也需要允许 DELETE 请求。

【问题讨论】:

  • 为什么不使用 Guzzle 或某种久经考验的库来为您完成所有繁重的工作?
  • 你试过用邮递员或其他程序检查url或请求是否正确吗?
  • 如果服务器响应“GET is not supported or POST is not supported”,那么你只是简单地为API设置了错误的HTTP方法
  • 您能与我们分享您使用什么作为函数的参数吗?

标签: php api


【解决方案1】:

为了更轻松的生活,试试 guzzle。 http://docs.guzzlephp.org/en/stable/

你可以提出这样的要求:

use GuzzleHttp\Client;
$client = new Client();
$myAPI = $client->request('GET', 'Your URL goes here');
$myData = json_decode($myAPI->getBody(), true); 

然后你可以像访问数组一样访问数据

$myData["Head"][0]

【讨论】:

【解决方案2】:

GuzzleHttp 是使用 Web 服务的标准方式。

您可以使用auth 参数发送您的身份验证详细信息。此外,您可以使用任何方便的方法使用 Oath 或 Beer 代币。如果您尝试通过令牌方法调用服务,请记住您需要通过 header 而不是 auth 来传递授权。

看到这个GuzzleHttp authentication via token。此外,您可以非常快速地捕获异常。见Handle Guzzle exception and get HTTP body

试试下面从官方网站获取的代码;)

  $client = new GuzzleHttp\Client();
  $res = $client->request('GET', 'https://api.github.com/user', [
      'auth' => ['user', 'pass']
  ]);
  echo $res->getStatusCode();
  // "200"
  echo $res->getHeader('content-type')[0];
  // 'application/json; charset=utf8'
  echo $res->getBody();
  // {"type":"User"...'

  // Send an asynchronous request.
  $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
  $promise = $client->sendAsync($request)->then(function ($response) {
      echo 'I completed! ' . $response->getBody();
  });
  $promise->wait();

您可以在此处找到有关 GuzzleHttp 请求的更多信息:http://docs.guzzlephp.org/en/stable/quickstart.html#making-a-request

希望这是你想要的!

【讨论】:

    【解决方案3】:

    问题在于您尝试为 GET 请求创建 $url。

    您的 GET 请求 $url 如下所示:

    GET https://simportal-api.azurewebsites.net/api/v1/?param1=val1&param2=val2
    

    但是从文档中你可以清楚地看到你 $url 应该是:

    GET https://simportal-api.azurewebsites.net/api/v1/param1/val1/param2
    

    例如:

    GET https://simportal-api.azurewebsites.net/api/v1/customers/{id}
    

    【讨论】:

      【解决方案4】:

      我认为您应该先尝试使用 Postman Tool 来请求该 API。如果邮递员完成这项工作,则意味着您的 PHP 代码存在问题。但是,如果您已经使用过邮递员并且仍然无法获取响应,那么该 API 可能存在问题。像 URL 块。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多