创建函数以将请求发送到API

cha*_*lie 4 php 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;
}
Run Code Online (Sandbox Code Playgroud)

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

我认为我的功能有某种错误,但我想知道是否有人可以在正确的方向帮助我?我也注意到,我也需要允许DELETE请求。

小智 9

为了让生活更轻松,请尝试一下。 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); 
Run Code Online (Sandbox Code Playgroud)

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

$myData["Head"][0]
Run Code Online (Sandbox Code Playgroud)


小智 5

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

$url的GET请求如下所示:

GET https://simportal-api.azurewebsites.net/api/v1/?param1=val1&param2=val2
Run Code Online (Sandbox Code Playgroud)

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

GET https://simportal-api.azurewebsites.net/api/v1/param1/val1/param2
Run Code Online (Sandbox Code Playgroud)

例如:

GET https://simportal-api.azurewebsites.net/api/v1/customers/{id}
Run Code Online (Sandbox Code Playgroud)