Make POST JSon requests to HBase REST by CURL with PHP - php

[Solved] I have an HBase 1.1.2 standalone installation on Ubuntu 14 and I need to retrieve and update data by PHP POST request (I cannot use GET because of length limit) through a REST server. I was going to use a curl PHP object but my problem is I don't understand how to format the request (in JSON or XML) to be submitted in POST at REST server.
Can anyone help me?
Thanks
Let me add my object i would like to use for all the request: getting rows by key and set\create row. My problem is how make $DATA field according different action.
function method($method, $data=NULL, & $http_code, & $response)
{
$ch = curl_init();
if(isset($header))
{
curl_setop(CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_URL, "http://" . $GLOBALS['DBDW']['hostname'] . $GLOBALS['DBDW']['port']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//nuovi
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'Connection: ' . ( $this->options['alive'] ? 'Keep-Alive' : 'Close' ),
));
// fine nuovi
switch(strtoupper($method)){
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
// i have to set CURLOPT_POSTFIELDS and if yes how?
break;
case 'POST':
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// how setting CURLOPT_POSTFIELDS and if yes how?
break;
case 'GET':
curl_setopt($curl, CURLOPT_HTTPGET, 1);
// i have to set CURLOPT_POSTFIELDS and if yes how?
break;
}
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$this->log(LOG_DEBUG, "HTTP code: " . $http_code, __FILE__, __LINE__, __CLASS__);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if ($response === false)
{
$this->log(LOG_ERR, "HTTP " . $method . " failed on url '" . $url . "'", __FILE__, __LINE__, __CLASS__);
$this->log(LOG_ERR, "cURL error: " . $curl_errno . ":" . $curl_error, __FILE__, __LINE__, __CLASS__);
$http_code=ERR_COMMUNICATION_FAILED;
return false;
}
return true;
}

CURLOPT_POSTFIELDS is only required if you're using post, so you switch/case is correct as is.
If you want to make GET requests, you just append the GET stuff to the url, just like you would see it in your broswer. This function is handy for that purpose: http_build_query.
// define the url in a variable above the switch
$url = "http://" . $GLOBALS['DBDW']['hostname'] . $GLOBALS['DBDW']['port'];
switch(strtoupper($method)){
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
// append the GET parameters if any
if(!empty($data)) $url .= "?".http_build_query($data);
break;
case 'POST':
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case 'GET':
curl_setopt($curl, CURLOPT_HTTPGET, 1);
// append the GET parameters if any
if(!empty($data)) $url .= "?".http_build_query($data);
break;
}
// move this line below the switch
curl_setopt($ch, CURLOPT_URL, $url);
This is the function I use for cURL stuff. You can refer to it (or use it) if you want.

Related

PHP Curl get data

I'm created a simple PHP curl client that call a external webservice. This webservice return the XML.
<?php
// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
$response = CallAPI('GET','https://s1-en.ogame.gameforge.com/api/universes.xml');
var_dump($response);
//print string(1121) " "
?>
But it always gives me back the wrong value. I print string(1121) " ".
How can I get the call data? (line 41 in the test.php).
This is because you are viewing the result in browser and the browser parses the xml as valid html tag. So you get empty result.
Its not your code issue. you can press ctrl + u (view source) in browser to see the actual result.
Or you can edit your var_dump to echo htmlentities($response); on line 41.

TypeError: Cannot call method "trim" of undefined

I have some PHP that is making a cURL call to an API on a website that automates the creation of new user accounts. When I submit my form the PHP takes over but I get an error message saying:
TypeError: Cannot call method "trim" of undefined (createUser#17)
Nowhere in my code do I try and use a method called "trim" so I'm not sure where the issue is coming from.
Here is the code I'm using with a couple of details redacted (replaced with xxxxx):
<?php
ini_set('display_errors', 1);
require_once("java/Java.inc");
// Assign form input values to variables.
$emailAddress=$_POST['emailAddress'];
$firstName=$_POST['firstName'];
$surname=$_POST['surname'];
$phoneNumber=$_POST['phoneNumber'];
// Initiate cURL.
$curl = curl_init();
$headers = array('Accept: application/json','Content-Type: application/json','appKey: xxxxxxxxxxxxxxxxx');
$postfields = array('fname'=>$firstName,'lname'=>$surname,'mobileNumber'=>$phoneNumber,'email'=>$emailAddress);
$fields_string = http_build_query($postfields);
// Setting up cURL.
curl_setopt($curl, CURLOPT_URL, 'xxxxxxxxxxxxxxxxx');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Forces it to use HTTP/1.1
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);
// Execute cURL.
$response = curl_exec($curl);
// Display cURL response.
echo('Response: '.$response);
// Display error if POST fails.
if(curl_exec($curl) === false){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
} else {
echo('Executed with no errors.');
};
if (!curl_errno($curl)) {
switch ($http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
case 200: # OK
break;
default:
echo ' Unexpected HTTP code: ', $http_code, "\n";
}
}
curl_close($curl);
?>

How to use transltr api

How can I call transltr api from my localhost using php? I have zero knowledge in calling api and what to type in the php file. Thank you in advance !
php cUrl library must be loaded and enabled.
You can check this using phpinfo file.
To use API, you can try code below.
<?php
$params = array('text'=>'something', 'from'=>'en', 'to'=>'de');
$data_string = json_encode($params);
$ch = curl_init('http://www.transltr.org/api/translate');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
if(!$result){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
echo $result;
?>
Hope this helps
You can use curl_exec function from CURL extension.
In the most simple form it looks like:
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$result = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
Now $result holds what you need.

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 )
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);
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);
This line:
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
is trying to set a request body, which is not valid for a GET request. cURL appears to let you set a body on a GET request (example).
It looks like your PHP is not making a POST request (at least best I can tell from looking at other PHP examples that use curl_setopt($ch,CURLOPT_POST, count($fields));. I believe you need to pass an array to the postfields option:
$fields = array(
'where' => urlencode('{"steps":9243}')
);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
Try this:
$query = json_encode(
array(
'where' => array( 'steps' => 9243 )
)
);
I've gleaned this from here - not tested though! The Python example appears to JSON-encode the query before sending it, so it might be worth trying that.

PHP CURL DELETE request

I'm trying to do a DELETE http request using PHP and cURL.
I have read how to do it many places, but nothing seems to work for me.
This is how I do it:
public function curl_req($path,$json,$req)
{
$ch = curl_init($this->__url.$path);
$data = json_encode($json);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data)));
$result = curl_exec($ch);
$result = json_decode($result);
return $result;
}
I then go ahead and use my function:
public function deleteUser($extid)
{
$path = "/rest/user/".$extid."/;token=".$this->__token;
$result = $this->curl_req($path,"","DELETE");
return $result;
}
This gives me HTTP internal server ERROR.
In my other functions using the same curl_req method with GET and POST, everything goes well.
So what am I doing wrong?
I finally solved this myself. If anyone else is having this problem, here is my solution:
I created a new method:
public function curl_del($path)
{
$url = $this->__url.$path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $result;
}
Update 2
Since this seems to help some people, here is my final curl DELETE method, which returns the HTTP response in JSON decoded object:
/**
* #desc Do a DELETE request with cURL
*
* #param string $path path that goes after the URL fx. "/user/login"
* #param array $json If you need to send some json with your request.
* For me delete requests are always blank
* #return Obj $result HTTP response from REST interface in JSON decoded.
*/
public function curl_del($path, $json = '')
{
$url = $this->__url.$path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
return $result;
}
To call GET,POST,DELETE,PUT All kind of request, i have created one common function
function CallAPI($method, $api, $data) {
$url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
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 Delete Method
$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);
CALL Post Method
$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);
CALL Get Method
$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);
CALL Put Method
$data = array('id'=>$_REQUEST['eid'],'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);

Categories