REST API Specification – ApiRestHelper class

This is a PHP helper class that is used in all PHP samples in API specification, so you don’t have to repeat the code in all samples.

Function ApiRestHelper::createApiCall($url, $method, $headers, $data = array()) accepts the following parameters:
$url is api call url.
$method is a request method. It can be ‘PUT’, ‘POST’, ‘GET’ or ‘DELETE’.
$headers is an array of HTTP headers to be sent with the request.
$data is an array of data to be sent with the request.

class ApiRestHelper
{
    public static function createApiCall($url, $method, $headers, $data = array())
    {
        if ($method == 'PUT')
        {
            $headers[] = 'X-HTTP-Method-Override: PUT';
        }

        $handle = curl_init();
        curl_setopt($handle, CURLOPT_URL, $url);
        curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);

        switch($method)
        {
            case 'GET':
                break;
            case 'POST':
                curl_setopt($handle, CURLOPT_POST, true);
                curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
                break;
            case 'PUT':
                curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
                break;
            case 'DELETE':
                curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
                break;
        }
        $response = curl_exec($handle);
        return $response;
    }
}

Leave a Comment

  • Mohiuddin Muhin

    This function is returning null value even though I have sent all the parameters while calling. Please help me

    • test

      nfokho

  • oldrose

    If you use a squid proxy you may have problems with the api calls failing without a helpful error. Our squid proxy (managed by a 3rd party and therefore impossible to have changed) was dropping requests over a certain length.

    We had to add the following to the curl_init() section.
    //needed to ignore the proxy which drops long http requests
    curl_setopt($handle, CURLOPT_PROXY, false);

    Note this only works if you can get away with not using the proxy server.