Not getting individual data using curl - php

i am trying to get indivdual data using curl from this website http://dummy.restapiexample.com/ .. I use the following code to get all data
<?php
$url='http://dummy.restapiexample.com/api/v1/employees';
$my_curl = curl_init();
curl_setopt($my_curl, CURLOPT_URL, $url);
curl_setopt($my_curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($my_curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($my_curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($my_curl, CURLOPT_SSL_VERIFYPEER, 0);
$my_data = curl_exec($my_curl);
$my_json = json_decode($my_data);
echo '<pre>'; print_r($my_json ); echo '</pre>';
?>
1) This is working . But i want to get the indvidual data , so i tried to chage url and use the same code
$url="http://dummy.restapiexample.com/api/v1/employee/1"
But it is not working .
2) Also i try to create a new record , that is working
$data = array("name" => "Hagridbo", "salary" => "123", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init('http://dummy.restapiexample.com/api/v1/create');
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);
But how can i get the response like data is inserted ? what data is inserted ?

1. Regarding individual employee data is not coming
If you look to the http://dummy.restapiexample.com/api/v1/employees, you will see that employee id 1 is not there. That's why you are not getting any data.
for example check data of this link:- http://dummy.restapiexample.com/api/v1/employee/20276
Also it seems that v1/employees API data changing on a regular interval.
2. Regarding created an employee successfully, but not getting any response.
do var_dump($result); after $result = curl_exec($ch);and see what it give you. I think it will give you a json data response of added user.
I said it based on details of that API link, check here: http://dummy.restapiexample.com/create

Related

Invalid json format using this api when using curl php

This is my json data
$data = array(
"api_key"=>"xxxx",
"email_details"=> array( "fromname"=>"test",
"subject"=>"Registration",
"from"=>"xxx#xxx.com",
"content"=>"test"),
"recipients"=>["xxx#gmail.com"]
);
generated the json data:
$str_data = json_encode($data);
it gives following format of json:
{"api_key":"xxxx",
"email_details":{"fromname":"test","subject":"Registration","from":"xxx#xxx.com","content":"test"},
"recipients":["xxx#gmail.com"]}
it is valid json format
verified from this url
http://jsonlint.com/
from the postman i have tried to run the API:
https://api.xxx.com/xxx/json?data={"api_key":"xxxx","email_details": {"fromname":"xxx","subject":"Registration","from":"xxx#xxx.com","content":"test" },"recipients":["xxx#gmail.com"]}
it is given the success message
when i tried to run this api from php code :
$url_email="https://api.xxx.com/xxx/json?data=";
$chh = curl_init();
curl_setopt($chh, CURLOPT_URL,$url_email);
curl_setopt($chh, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($chh, CURLOPT_POSTFIELDS, $str_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($str_data))
);
curl_setopt($chh, CURLOPT_RETURNTRANSFER, true);
curl_exec($chh);
curl_close($chh);
i didn't get the o/p
getting the error message :
{"message":"ERROR","errorcode": "100" ,"errormessage":"Invalid JSON format used in API Call.Hence failed."}
whats wrong here ?
I suppose it should be:
$url_email="https://api.xxx.com/xxx/json"; // no `data` here
$chh = curl_init();
curl_setopt($chh, CURLOPT_URL, $url_email);
curl_setopt($chh, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($chh, CURLOPT_POSTFIELDS, 'data=' . $str_data); // `data` moved here

PUT Request via CURL

I'm trying to make an CURL PUT REQUEST, my code looks like:
public function assignProfile($token, $organizationId, $profileId)
{
//define enviroment and path
$host = enviroment;
$path = "/admin/organizations/".$organizationId."/users";
$data_string = '["'.$profileId.'"]';
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer '.$token.'',
'Content-Length: ' . strlen($data_string)
));
echo "<br>OK<br>";
// execute the request
$output = curl_exec($ch);
// return ID for a new case
$output = json_decode($output);
var_dump($output);
}
Each part looks correct, when I var_dump $path, $host, even $data_string looks correct. However var_dump() at the end throw just NULL
I expect I'm doing something wrong or missing something really important.
May I ask you for some advise?
Thanks
EDIT:
What i do with it:
// define
define("Audavin","here is some uniqe ID");
.
.
.
$Users = new Users;
// this return Auth token ( I verify this work with echo )
$token = $Users->authorization();
// Calling method mentioned above
$Users->assignProfile($token,"here is org id", Audavin);
I would start by making sure the URL you're making the request to actually works and returns a valid response, you can do so by using a simple REST client (like POSTMAN chrome extension for example)
If you do get a response back, try and see if it's indeed a valid JSON, if not, that could be why you're not getting anything back from json_decode (more on return values here: http://php.net/manual/en/function.json-decode.php)
Finally, It is suggested you add curl_close($ch) to the end of your code to make sure your release the curl handle.

Updating order WooCommerce API PHP CURL

I'm developing a web application for my co-workers, so they'll have an iPad with an application, to package our orders.
Whole app is almost finished, one of the last steps is to change order status from processing to completed.
What I'm doing:
Get current order ID, then change status with curl or API. What happens is very strange, I get JSON data back, and the completed_at time updated, but status is still processing.
Below you will see my code:
$data = array("status" => "completed");
$data_string = json_encode($data);
$username = 'XXX'; // Add your own Consumer Key here
$password = 'XXX'; // Add your own Consumer Secret here
$ch = curl_init('https://www.deallerleukste.nl/wc-api/v2/orders/5764?consumer_key='.$username.'&consumer_secret='.$password);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
echo $result;
Anyone who sees what I'm doing wrong? Please help!
Regards,
Jelmer
Try Using this code
$data='{ "order": { "status": "completed" }}';
or
Dynamically
$data=json_encode( array( 'order' => array( 'status' => $status)));
in $status you can pass the status u want.
I see it is a quite old post, but today I ran into the same problem, so maybe it is useful.
You have to use PUT instead of POST here:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
and data should be a valid JSON in this format:
$data='{"status": "completed"}';

how to send xml file to server backend using php? [duplicate]

This question already has answers here:
How to properly send and receive XML using curl?
(2 answers)
Closed 9 years ago.
I have fetched data from server using this code, `$server = 'LOCALHOST:9000';
$headers = array(
"Content-type: text/xml"
,"Content-length: ".strlen($requestXML)
,"Connection: close"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch)){
print curl_error($ch);
echo " something went wrong..... try later";
}else{
echo " request accepted";
print $data;
curl_close($ch);
}`
Now I have to do reverse, how to send the data into server using php? curl method is the only way or is there any other method to do the same. Give me some example.
Sending/Receiving using cURL is the exact same thing. cURL is based on sending data to an given URL and possibly receiving a response. Let's take a simple example of getting a user and sending a user.
Getting a user would be
$data = array(
'user_id' => 1
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/getUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
getUser.php does nothing more than search for a user and return the data found.
$response would possibly contain data of the user, perhaps just a text-response containing the name. A serialized PHP array, an XML response with a full user profile.. etc.
Inserting/Sending data
$data = array(
'user_name' => 'Joshua',
'user_email' => 'my#email.com'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/addUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
addUser.php performs some validation of the fields and if validated inserts a user in the database
$response in this case does not contain the userdata (however: it's a possibility), but more likely the $response contains a result. An ok textresponse, a json/xml response or perhaps a '200 OK' header response
It's all basically the same. There is no difference in getting/sending data using cURL. It's all based on sending a request and in most cases do something with the outcome.

Google Apps Calendar free/busy query POST with curl

I am trying to do a free/busy query on a Google Resource Calendar (Google Apps). The API documentation for Freebusy query gives these directions about the request:
HTTP Request:
POST https://www.googleapis.com/calendar/v3/freeBusy
Request Body Structure:
{ "timeMin": {datetime},
"timeMax": {datetime},
"items": [
{"id": {string}
}
]
}
Here's my attempt, using curl:
$url = "https://www.googleapis.com/calendar/v3/freeBusy";
global $headers; // holds ClientLogin authentification
$freebusy_post = array(
"timeMin" => '2012-12-31T00:00:00',
"timeMax" => '2013-01-08T23:00:00',
"timeZone" => 'America/New York',
/*** "items" below commented out because posting a multidimensional array returns an
"Array to string conversion" error. However, I think the API requires
"items" to be an array. ***/
//"items" => array(
// "id" => "https://www.googleapis.com/calendar/v3/calendars/gdev.wellesley.edu_313736333535343332#resource.calendar.google.com"
// )
/*** My attempt at using a plain string instead of an array ***/
"items" => "gdev.wellesley.edu_313736333535343332#resource.calendar.google.com",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $freebusy_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
print_r($data);
My problem: $data doesn't print anything.
I'm brand new to PHP, curl, and the Google Apps Calendar API. I'd love any help/ lessons/ advice you can offer!
Not sure, but you have probably to convert the php array to a json first.
$freebusyjson = json_encode($freebusy_post);
i started with your code and modified it and the following worked for me...
Note how i formatted the calendar ID in the item variable. I also only needed to attach an API key to the URL as it is a public calendar. I don't think I needed it initially, but then I reached the number of requests that could be made without using an API key.
Finally, note the format of the Time/Date. I'm saying this is the only way to do it, but it worked for me.
$url = "https://www.googleapis.com/calendar/v3/freeBusy/?key=MY_API_KEY";
$freebusy_post = array(
"timeMin" => '2016-11-01T00:00:00.000Z',
"timeMax" => '2016-12-21T00:00:00.000Z',
"timeZone" => ' America/New York',
"items" => array(array('id'=>"mywebsite.com_randomlettershere#group.calendar.google.com")),
);
$freebusy_post = json_encode($freebusy_post);
$ch = curl_init();curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $freebusy_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
print_r($data);

Categories