I was using cURL for posting data to an API but have decided to switch to Guzzle. Using cURL I would do this
$data =
"<Lead>
<Name>$newProject->projectName</Name>
<Description>$newProject->projectName</Description>
<EstimatedValue>$newProject->projectValue</EstimatedValue>
</Lead>";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.someurl.com/lead.api/add?apiKey=12345&accountKey=12345");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($data)
));
$output = curl_exec($ch);
This is what I am currently attempting with Guzzle.
$data = "<Lead>
<Name>$campaign->campaignName</Name>
<Description>$campaign->campaignName</Description>
<EstimatedValue>$campaign->campaignValue</EstimatedValue>
</Lead>";
$client = new GuzzleHttp\Client();
$req = $client->request('POST', 'https://somurl', [
'body' => $data,
'headers' => [
'Content-Type' => 'text/xml',
'Content-Length' => strlen($data),
]
]);
$res = $client->send($req);
$output = $res->getBody()->getContents();
The first problem I am facing is that it is stating that arguement 3 for request needs to be an array, and I am passing it a string. Thats fine, but then how can I send my xml block? Additionally, I think I may have set the headers incorrectly?
I have gone through the documentation and see that parameter 3 needs to be an array, but I do not see how to post an XML string.
Any advice appreciated.
Thanks
You can create an array using the 'body' param:
$client->request('POST', 'http://whatever', ['body' => $data]);
Read more at: http://docs.guzzlephp.org/en/latest/quickstart.html?highlight=post#post-form-requests
To set headers, you can do something like:
$response = $client->request('POST', 'http://whatever', [
'body' => $data,
'headers' => [
'Content-Type' => 'text/xml',
'Content-Length' => strlen($data),
]
]);
$output = $response->getBody()->getContents();
Read more at: http://docs.guzzlephp.org/en/latest/request-options.html#headers
Related
I am trying to connect to Moz API V2, using HTTP Request by file get contents function but I am new using this... could you guys help me?
Example HTPP Request in their doc:
POST /v2/url_metrics
Host: lsapi.seomoz.com
Content-Length: [length of request payload in bytes]
User-Agent: [user agent string]
Authorization: Basic [credentials]
{
"targets": ["facebook.com"]
}
Here's the code I am trying:
$url = 'https://lsapi.seomoz.com/v2/url_metrics';
$domains = json_encode(['targets' => 'moz.com']);
$opts = ['http' =>
[
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded\r\n'.
("Authorization: Basic " . base64_encode("mozscape-XXXXX:XXXXX")),
'content-length' => strlen($domains),
'user-agent' => $_SERVER['HTTP_USER_AGENT'],
'content' => $domains,
]
];
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
print_r($result);
Here is the link of documentation : https://moz.com/help/links-api/making-calls/url-metrics
I got nothing when I print result, Probably I am missing some parameter... :(
Thank you for your time :)
Most probably you're simply making an invalid request. You declare the content type as application/x-www-form-urlencoded yet sending the data as application/json.
You also need basic error handling (eg. in case of invalid credentials).
I'd write it this way:
$url = 'https://lsapi.seomoz.com/v2/url_metrics';
$content = json_encode(['targets' => 'moz.com']);
$opts = ['http' => [
'method' => 'POST',
'content' => $content,
'header' => implode("\r\n", [
'Authorization: Basic ' . base64_encode("mozscape-XXXXX:XXXXX"),
'Content-Type: application/json',
'Content-Length: ' . strlen($content),
'User-Agent: ' . $_SERVER['HTTP_USER_AGENT'],
]),
]];
$stream = fopen($url, 'r', false, stream_context_create($opts));
if (!is_resource($stream)) {
die('The call failed');
}
// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));
// actual data
var_dump(stream_get_contents($stream));
// free resources
fclose($stream);
To be honest, the sockets & fopen is pretty low level. It would be better for you to use an abstraction layer instead: like Guzzle.
Sorry for late solution I forgot to post here before...
Maybe someone is looking for how to use moz API V2 with PHP...
$username='Access ID';
$password='Secret Key';
$URL='https://lsapi.seomoz.com/v2/url_metrics';
$payload = json_encode(array("targets" => ["moz.com"]));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_close ($ch);
print_r(json_decode($result, true));
Am using the following post request on guzzle to microsoft graph which works.
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $token ]
]);
$url = "myurl";
$response = $client->post(
$url,
[
'body' => json_encode(
[
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
"meeting"=>$arr['subject']
]
)]
);
$payload = json_decode($response->getBody()->getContents());
var_dump($payload) //here has data
The am doing the same request via curl using
$post = [
"meeting"=>$arr['subject'],
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
];
$authorization = "Authorization: Bearer ".$token;
$headers = [
'Content-Type' => 'application/json',
$authorization
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$error = curl_errno($ch) ? curl_error($ch) : '';
curl_close($ch);
if ($error){
var_dump($error);
throw new Exception($error,500);
}
return $response;
But in curl the above in micorsoft graph throws an error Expected not null\r\nParameter name: meeting but the meeting parameter is not empty. I have also tried setting the value of meeting directly via
$post = [
"meeting"=>"Test meeting",
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
];
But still doesnt solve. I guess it has something to do with body parameter i have set on guzzle which works. How can i resolve this to have it work even on curl
I have tried making a HTTP request using CURL as below:
$rawQuery = '{
"CUSTNAME" : "1970188",
"CURDATE":"2020-12-28T00:00:00+02:00",
"BOOKNUM":"Test BookNum",
"DETAILS":"Test Details"
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://somelink.co.de");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $rawQuery);
$curl_response = curl_exec($ch);
This one is returning me result. But when I try to implement the same using Symfony HTTP Client, I am getting 400 error.
This is the code, I have tried.
$response = $this->client->request('POST', $url, [
'auth_basic' => [
'username',
'password'
],
'headers' => [
'Accept' => 'application/json',
],
'json' => $rawQuery
]);
I am not sure what I am missing in Client
Can anybody please help me ?
Your Raw query is incorrect.. This should be a php array, Symfony is trying to json_encode() this for you when you use the 'json' key in the request. Reformat your $rawQuery to be
$rawQuery = [
"CUSTNAME" => "1970188",
"CURDATE" => "2020-12-28T00:00:00+02:00",
"BOOKNUM" => "Test BookNum",
"DETAILS" => "Test Details"
];
I'm trying to connect to the Talentlink Api. I'm able to do it on curl but I can't connect using GuzzleHttp. I'm using Guzzle through the m6web/guzzle-http-bundle on Symfony. My code is below. Does anybody have an idea?
CURL
$headers = [
'username: XXXXX',
'password: XXXXX'
];
$body = '{
"searchCriteriaSorting": {
"categoryListsSorting": "LABEL",
"customLovsSorting": "ORDER",
"standardLovsSorting": "ORDER"
}
}';
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, "https://api3.lumesse-talenthub.com/CareerPortal/REST/FoAdvert/advertisement-by-id?api_key=XXXXXX&lang=FR&postingTargetId=1");
curl_setopt($tuCurl, CURLOPT_VERBOSE, 1);
curl_setopt($tuCurl, CURLOPT_HEADER, 1);
curl_setopt($tuCurl, CURLINFO_HEADER_OUT, 1);
curl_setopt($tuCurl, CURLOPT_HTTPHEADER, $headers);
$head = curl_exec($tuCurl);
$httpCode = curl_getinfo($tuCurl, CURLINFO_HTTP_CODE);
curl_close($tuCurl);
GUZZLE
$headers = [
'username' => 'XXXXXX',
'password' => 'XXXXXX'
];
try {
$response = $client->request('GET',
'https://api3.lumesse-talenthub.com/CareerPortal/REST/FoAdvert/advertisement-by-id?api_key=XXXXX&lang=FR&postingTargetId=1',
array(
'debug' => true,
$headers
));
} catch (ClientException $e) {
die((string)$e->getResponse()->getBody()->getContents());
}
On Guzzle, I keep getting a page with a login form as if I wasn't connected. However, the status is always 200 so it's difficult to debug.
SOLUTION
It was a problem with the array I was sending. It should be like this wit the 'header' key:
$response = $client->request('GET',
'https://api3.lumesse-talenthub.com/CareerPortal/REST/FoAdvert/advertisement-by-id?api_key=XXXX&lang=FR&postingTargetId=1',
[
'headers' => $headers,
//'debug' => true
]);
I wrote this code. I send data to $url = "https://upload.box.com/api/2.0/files/content", but i don't get a response. Maybe someone has also had this problem?
$absolutePath = 'home/my/path/uploads/media/ClientPDF/0001/01/c607bea86bdb42220bb49aac722b4a5eb44be3db.pdf';
$json = json_encode([
'name' => 'c607bea86bdb42220bb49aac722b4a5eb44be3db.pdf,
'parent' => ['id' => 7479666489] //parent folder
]);
$fields = [
'attributes' => $json,
'file' => #$absolutePath
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer MY_TOKEN_KEY'
'Content-Type:multipart/form-data'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$response = curl_exec($ch);
var_dump(json_decode($response, true)); die;
var_dump - print nothing, i can't debug this request. Please, help me to solve this problem