How to send OData to RESTful API in PHP cURL Request - php

I am trying to send OData parameters in a GET request to a RESTful API using PHP. A properly formatted OData request to this service looks like so:
https://myapi.org/endpoint?filter=family_name eq 'Doe'
It seems like I should just append these variables to the end of my CURLOPT_URL before sending the request, but the API service doesn't seem to receive the OData.
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('OSDI-API-Token:xxxxxxxxxxxx'));
curl_setopt($ch, CURLOPT_URL, "https://myapi.org/endpoint?filter=family_name eq 'Doe'");
$response = curl_exec($ch);
curl_close($ch);
echo "<pre>";
print_r($response);
echo "</pre>";
Output is NULL. This seems like a strange response considering that this same request with identical headers and the same Odata URL searches and finds the correct data in the API's browser.
Can anybody confirm whether or not this is the correct way to send OData parameters through a cURL request?

Appending the OData parameters directly to the CURLOPT_URL doesn't work, because it doesn't form a valid URL. The spaces and quotes need to be escaped as family_name%20eq%20%27Doe%27 or family_name+eq+%27Doe%27.
A simpler way would be to use http_build_query() to attach the parameters to the URL prior to setting CURLOPT_URL:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('OSDI-API-Token: xxxxxxxxxx'));
$api_request_parameters = array('filter'=>"family_name eq 'Doe'");
$api_request_url = "https://myapi.org/endpoint";
$api_request_url .= "?".http_build_query($api_request_parameters);
$curl_setopt($ch, CURLOPT_URL, $api_request_url);
$response = curl_exec($ch);
curl_close($ch);

I know that this question has been closed for a while but just to complement the answer with more points above, you need to declare '$' in the filter key if you are going to use http_build_query (), for example:
$api_request_parameters = array ('$filter' => "family_name eq 'Doe'");
$api_request_url. = "?". http_build_query ($api_request_parameters);
If you declare without '$' in filter, the filter will not work correctly and the return of this will be all records and in some cases it may return an error.
If you choose not to use http_build_query () you need to escape all spaces, for example, let's say the request is this:
https://myapi.org/endpoint?filter=family_name eq 'Doe test 1234'
The parameters would look like this:
https://myapi.org/endpoint?filter=family_name+eq+%27Doe%20test%201234%27

Related

Send data GET lost data with hashmark# [duplicate]

Im a newbie im trying to get a script to trigger another script with Curl in PHP but it dosent seem to be sending the paramaters.
Is there a seperate function to append parameters?
<?php
$time = time();
$message = "hello world";
$urlmessage = urlencode( $message );
$ch = curl_init("http://mysite.php?message=$urlmessage&time=$time");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>
Could anyone point me in the right direction??
The accepted answer is good for POST, but what if OP wanted specifically to GET? Some REST APIs specify the http method and often it's no good POSTing when you should be GETting.
Here is a fragment of code that does GET with some params:
$endpoint = 'http://example.com/endpoint';
$params = array('foo' => 'bar');
$url = $endpoint . '?' . http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
This will cause your request to be made with GET to http://example.com/endpoint?foo=bar. This is the default http method, unless you set it to something else like POST with curl_setopt($ch, CURLOPT_POST, true) - so don't do that if you specifically need to GET.
If you need to use one of the other http methods (DELETE or PUT for example) then use curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method). This also works for GET and POST.
You need curl_setopt() along with the CURLOPT_POSTFIELDS param.
That'll POST the given params to the target page.
curl_setopt($ch, CURLOPT_POSTFIELDS, 'foo=1&bar=2&baz=3');
PS: also check http_build_query() which is handy when sending many variables.
you need set CURLOPT_POST as true and CURLOPT_POSTFIELDS => parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
a suggestion,set 'CURLOPT_RETURNTRANSFER', as true to return the transfer as a string of the return value of curl_exec($ch) instead of outputting it out directly
Here is A Simple Solution for this.
$mobile_number = $_POST['mobile_number'];
$sessionid = $_POST['session_id'];
CURLOPT_URL => 'https://xxyz.jkl.com/v2.0/search?varible_that_you_want_to_pass='.$mobile_number.'&requestId=1616581154955&locale=en-US&sessionId='.$sessionid,

CURL Request to Laravel API Returns NULL Values

I'm attempting to send an array of objects as part of a JSON request with curl. The request must use json_encode in order to be sent by curl. However I am running into an issue on the Laravel API that is receiving it. Any attempt to get an object from the Request Laravel object returns null i.e.:
$request->order_number;
$request->items;
This is the case for normal fields and the array of objects I am also sending. The curl appears as:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json'
));
What is the mistake I am making?
EDIT:
To provide more specific information, here is the json_encode var dumped (some omissions):
string(694) "{"order_number":"11111","items":"[{"id":"1005","name":"UpRight 011238-004 Washer, Split Lock","sku":"","quantity":1,"price":0.01}]"}"
The solution ended up being rather convoluted:
public function postOrderInformation(Request $data) {
$request = json_decode(json_encode(json_decode($data->getContent(), true)));
}
This created a useable object from which the data could be extracted from the laravel Requets object. If anyone has a more elegant/less ugly solution, please post it.

sending xml string using php curl but not as post parameter

:)
I'm trying to send an XML using curl but not as post parameter. what I mean is this.
for example.
the receiving side of that XML won't be able to recieve the XML using $_POST variable.
he will need to use the following code:
$xmlStr=null;
$file=fopen('php://input','r');
$xmlStr=fgets($file);
I want to be able to send an xml string using curl via https.
so the following would be wrong:
public static function HttpsNoVerify($url,$postFields=null,$verbose=false) {
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ($postFields !=null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}
if ($verbose) {
curl_setopt($ch, CURLOPT_VERBOSE, 1);
}
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
because here i can use HttpsNoVerify($url,array('xml_file'=>'xml..')); and that
will paste it as post parameter. and i want it as post output.
so please I hope i explained myself properly and I explained exactly what I don't want to do.
how can I do what i want to do?
thanks! :)
kfir
Just directly pass the xml string as second parameter instead of an associative array item,
HttpsNoVerify($url, 'xml ..');
This will eventually call
curl_setopt($ch, CURLOPT_POSTFIELDS, "xml ...");
Which will be put in php://input for the remote server.

How to add a string at the end of url

I use cURL to send requests to REST API and I would like to add a string to created url befeore execute it. This string is not a parameter.
Do you know how can I do that?
It's called string concatenation. In php it can be done: $str = $string1.$string2;
p.s. Always read documentation before asking something. There you can find answers on most of your questions.
It depends on really what you want to do. If you want to call an URL by appending GET query parameters, you can use string concatenation.
<?php
function get_data($url, $add) {
$url = $url.$add;
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
echo get_data('http://example.com', '?page=mine');
?>
However, if you want to retrieve a specific URL by sending POST query parameters (e.g. to simulate a form being submitted), you need to implement something like this instead.

Php Curl adding Params

Im a newbie im trying to get a script to trigger another script with Curl in PHP but it dosent seem to be sending the paramaters.
Is there a seperate function to append parameters?
<?php
$time = time();
$message = "hello world";
$urlmessage = urlencode( $message );
$ch = curl_init("http://mysite.php?message=$urlmessage&time=$time");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>
Could anyone point me in the right direction??
The accepted answer is good for POST, but what if OP wanted specifically to GET? Some REST APIs specify the http method and often it's no good POSTing when you should be GETting.
Here is a fragment of code that does GET with some params:
$endpoint = 'http://example.com/endpoint';
$params = array('foo' => 'bar');
$url = $endpoint . '?' . http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
This will cause your request to be made with GET to http://example.com/endpoint?foo=bar. This is the default http method, unless you set it to something else like POST with curl_setopt($ch, CURLOPT_POST, true) - so don't do that if you specifically need to GET.
If you need to use one of the other http methods (DELETE or PUT for example) then use curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method). This also works for GET and POST.
You need curl_setopt() along with the CURLOPT_POSTFIELDS param.
That'll POST the given params to the target page.
curl_setopt($ch, CURLOPT_POSTFIELDS, 'foo=1&bar=2&baz=3');
PS: also check http_build_query() which is handy when sending many variables.
you need set CURLOPT_POST as true and CURLOPT_POSTFIELDS => parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
a suggestion,set 'CURLOPT_RETURNTRANSFER', as true to return the transfer as a string of the return value of curl_exec($ch) instead of outputting it out directly
Here is A Simple Solution for this.
$mobile_number = $_POST['mobile_number'];
$sessionid = $_POST['session_id'];
CURLOPT_URL => 'https://xxyz.jkl.com/v2.0/search?varible_that_you_want_to_pass='.$mobile_number.'&requestId=1616581154955&locale=en-US&sessionId='.$sessionid,

Categories