Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying API through Curl/PHP

I'm looking at the Parse.com REST API and making calls using the Curl wrapper PHP uses.

Raw Curl code(works):

curl -X GET \
  -H "X-Parse-Application-Id: myApplicationID" \
  -H "X-Parse-REST-API-Key: myRestAPIKey" \
  https://api.parse.com/1/classes/Steps

PhP code(works):

$ch = curl_init('https://api.parse.com/1/classes/Steps');

curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Parse-Application-Id: myApplicationID',
    'X-Parse-REST-API-Key: myRestAPIKey',
    'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_exec($ch);
curl_close($ch);

Thats good and dandy, but now when I try to add a query constraint:

Raw Curl code(works):

curl -X GET \
  -H "X-Parse-Application-Id: myApplicationID" \
  -H "X-Parse-REST-API-Key: myRestAPIKey" \
  -G \
--data-urlencode 'where={"steps":9243}' \
https://api.parse.com/1/classes/Steps

Alas, we ultimately arrive at my question- What is the php analogue to the above code?

PHP code(does not work):

$ch = curl_init('https://api.parse.com/1/classes/Steps');

$query = urlencode('where={"steps":9243}');

curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Parse-Application-Id: myApplicationID',
    'X-Parse-REST-API-Key: myRestAPIKey',
    'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);

curl_exec($ch);
curl_close($ch);

Error response:

Object ( [code] => 107 [error] => invalid json: where%3D%7B%22steps%22%3A9243%7D )
like image 687
JRam13 Avatar asked Aug 02 '13 21:08

JRam13


People also ask

Can we use cURL to call REST API?

curl can send all common HTTP commands to a REST API including GET , POST , PUT , and DELETE . The curl utility is straightforward to use. It has a few main options for data transmission, user authentication, and making header changes. For more information about curl, see the curl documentation.

Can you cURL API?

Curl is also an important tool for testing remote APIs. If a service you rely on or provide is unresponsive, you can use the curl command to test it. The term API is short for Application Programming Interface.

Can I use cURL in PHP?

Uses of cURL in PHPcURL is a PHP extension that allows you to use the URL syntax to receive and submit data. cURL makes it simple to connect between various websites and domains. Obtaining a copy of a website's material.


2 Answers

Your last PHP example has changed the request to a POST from a GET. Pass your parameters in the query string instead of the POST body. Try:

$query = urlencode('where={"steps":9243}');
$ch = curl_init('https://api.parse.com/1/classes/Steps?'.$query);

curl_setopt(
    $ch, 
    CURLOPT_HTTPHEADER,
    array(
        'X-Parse-Application-Id: myApplicationID',
        'X-Parse-REST-API-Key: myRestAPIKey',
        'Content-Type: application/json'
    )
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_exec($ch);
curl_close($ch);
like image 158
Matt S Avatar answered Oct 05 '22 22:10

Matt S


To call GET,POST,DELETE,PUT All kind of request, i have created one common function

define("SITEURL", "http://localhost:82/slimdemo/RESTAPI");

function CallAPI($method, $api, $data, $headers) {
    $url = SITEURL . "/" . $api;
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    switch ($method) {
        case "GET":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
            break;
        case "POST":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            break;
        case "DELETE":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            break;
    }
    $response = curl_exec($curl);
    $data = json_decode($response);

    /* Check for 404 (file not found). */
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    // Check the HTTP Status code
    switch ($httpCode) {
        case 200:
            $error_status = "200: Success";
            return ($data);
            break;
        case 404:
            $error_status = "404: API Not found";
            break;
        case 500:
            $error_status = "500: servers replied with an error.";
            break;
        case 502:
            $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
            break;
        case 503:
            $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
            break;
        default:
            $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
            break;
    }
    curl_close($curl);
    echo $error_status;
    die;
}

CALL DeleteAPI

$data = array('id'=>$_GET['did']);
$header = array('USERTOKEN:' . GenerateToken());
$result = CallAPI('DELETE', "DeleteCategory", $data, $header);

CALL PostAPI

$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$header = array('USERTOKEN:' . GenerateToken());
$result = CallAPI('POST', "InsertCategory", $data, $header);

CALL GetAPI

$data = array('id'=>$_GET['eid']);
$header = array('USERTOKEN:' . GenerateToken());
$result = CallAPI('GET', "GetCategoryById", $data, $header);

CALL PutAPI

$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$header = array('USERTOKEN:' . GenerateToken());
$result = CallAPI('POST', "UpdateCategory", $data, $header);
like image 40
Juned Ansari Avatar answered Oct 05 '22 23:10

Juned Ansari