首页 > 解决方案 > 创建函数以向 API 发送请求

问题描述

我有一个 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 请求。

标签: phpapi

解决方案


为了更轻松的生活,请尝试 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]

推荐阅读