Could you help me I'm studying about cognitive services using the azure service, but I'm having some mistakes using the forncecido model in the documentation
<?php
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';
// Replace <Subscription Key> with a valid subscription key.
$ocpApimSubscriptionKey = '98471c5c832e466688890f6c86f6c88d';
$request = new Http_Request2('https://brazilsouth.api.cognitive.microsoft.com/face/v1.0/facelists/{faceListId}');
$url = $request->getUrl();
$headers = array(
// Request headers
'Content-Type' => 'application/json',
'Ocp-Apim-Subscription-Key' => $ocpApimSubscriptionKey ,
);
$request->setHeader($headers);
$parameters = array(
// Request parameters
'faceListId' => 'sahara'
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_PUT);
// Request body
$request->setBody("{body}");
try
{
$response = $request->send();
echo $response->getBody();
}
catch (HttpException $ex)
{
echo $ex;
}
?>
I run this script in php and it gives me the following error
{"error":{"code":"BadArgument","message":"Request body is invalid."}}
could you tell me what I'm doing wrong, please
According to the FaceList - Create API, the body format is
{
"name": "sample_list",
"userData": "User-provided data attached to the face list."
}
We need to send body with following way, then it should work.
// Request body
$request->setBody('{"name":"facelistName","userData":"it is optional"}'); //replace it with your name and userData
If want to reference 'HTTP/Request2.php';, we need to install http_request2
pear install http_request2
How to install the PEAR package manager, please refer to this link.
Demo code:
<?php
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';
$request = new Http_Request2('https://xxx.api.cognitive.microsoft.com/face/v1.0/facelists/{faceListId}');
$url = $request->getUrl();
$headers = array(
// Request headers
'Content-Type' => 'application/json',
'Ocp-Apim-Subscription-Key' => 'xxxxxxxxxx', //replace it with your key
);
$request->setHeader($headers);
$parameters = array(
'faceListId' => 'facelistId'
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_PUT);
// Request body
$request->setBody('{"name":"facelistName","userData":"it is optional"}');//replace it with your name and userData
try
{
$response = $request->send();
echo $response->getBody();
}
catch (HttpException $ex)
{
echo $ex;
}
?>
Related
I've tried several methods to download an mp3 file via API get request. I feel like as if I'm close but just can't seem to get the download.
My URL returns a binary mp3 file.
This is a portion of what I'm getting in my response header array returning with the get request. Hope this is helpful.
"Content-Disposition" => array:1 [
0 => "attachment; filename=RE3e327a2615b93f528fee111da9b60e17.mp3; filename*=UTF-8''sample.mp3"
]
Here is a sample of my code using the Guzzle client in Laravel. Trying Laravel's download method but I believe I need to get the actual file from the Content-Disposition. Much appreciated for any help. Thanks.
$client = new Client();
try {
$url = 'http://getmp3website.net/recording/sample.mp3';
$response = $client->request('GET', $url,
[
'headers' => [
'Authorization' => 'bearer ' . env("AUTH_TOKEN"),
'Content-Type' => 'audio/mp3',
],
]);
return response()->download($response);
} catch (Exception $ex) {
return $ex;
}
#Note: this is not a tested answer, I have just provided an example to follow the comments above
<?php
$client = new Client();
try {
$url = 'http://getmp3website.net/recording/sample.mp3';
$resource = \GuzzleHttp\Psr7\Utils::tryFopen('/path/to/file', 'w');
//or you can use $myFile = fopen('/path/to/file', 'w') or die('not working');
$stream = \GuzzleHttp\Psr7\Utils::streamFor($resource);
$client->request('GET', $url , [
'save_to' => $stream,
'headers' => [
'Authorization' => 'bearer ' . env("AUTH_TOKEN"),
'Content-Type' => 'audio/mp3',
],
]
);
/**
* // As `save_to` is deprecated(guzzle wants us to download files as stream I guess), you can use sink as well, sink will automatically stream files for you
$resource = \GuzzleHttp\Psr7\Utils::tryFopen('/path/to/file', 'w');
$client->request('GET', $url, ['sink' => $resource]);
*/
return response()->download($pathsavedfile);
} catch(\GuzzleHttp\Exception\RequestException $e){
// you can catch here 400 response errors and 500 response errors
// You can either use logs here
$error['error'] = $e->getMessage();
$error['request'] = $e->getRequest();
if($e->hasResponse()){
if ($e->getResponse()->getStatusCode() == '400'){
$error['response'] = $e->getResponse();
}
}
Log::info('Error occurred in request.', ['error' => $error]);
}catch (Exception $ex) {
return $ex;
}
I am using this code to establish a new connection on user device.
var socket = new WebSocket("wss://cdsbxtx2xi.execute-api.us-east-2.amazonaws.com/test");
socket.onmessage = function (event) {
json = JSON.parse(event.data);
connectionId = json.connectionId;
document.cookie = "connection_id="+connectionId;
console.info(json);
}
Suppose from this request I get connectionId CLO5bFP1CYcFSbw=
Another user from another device also established a new connection with connectionId Cs42Fs5s5yuSbc=. Now how can I send a message from user 2 device to user 1?
I already tried this. I don't know this is right way or not but still, i am open for any suggestion.
use Aws\Signature\SignatureV4;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Aws\Credentials\Credentials;
$client = new GuzzleHttp\Client();
$credentials = new Credentials("XXXXXXXXXX","XXXXXXXX");
$url = "https://cdsbxtx2xi.execute-api.us-east-2.amazonaws.com/test/#connections/CLO5bFP1CYcFSbw=";
$region = 'us-east-2';
$msg['action'] = 'sendmessage';
$msg['data'] = 'hello world';
$msg = json_encode($msg);
$request = new Request('POST', $url, '["json"=>$msg]');
$s4 = new SignatureV4("execute-api", $region);
$signedrequest = $s4->signRequest($request, $credentials);
$response = $client->send($signedrequest);
echo $response->getBody();
This code keeps on loading and finally throws gateway timeout error.
I expect that user 2 should be able to send message to any specific connectionId over wss or https.
I tried https by signing this request but signing doesn't works. I am getting an error with the signing part
After struggling with this problem for the last 3 days finally I found the solution. None of the previously mentioned solutions on StackOverflow was working for me.
This is the correct solution. I hope this will be helpful to someone.
use Aws\Signature\SignatureV4;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Aws\Credentials\Credentials;
$client = new GuzzleHttp\Client();
$credentials = new Credentials(accessKeyId, secretAccessKey);
$url = "https://xsdsdsd.execute-api.us-east-2.amazonaws.com/test/#connections/CNtBveH2iYcCKrA=";
// CNtBveH2iYcCKrA= is connectionid
$region = 'us-east-2';
$msg['action'] = 'sendmessage';
$msg['data'] = 'hello world';
$msg = json_encode($msg);
$headers = array('Content-Type => application/x-www-form-urlencoded');
$request = new GuzzleHttp\Psr7\Request('POST', $url, ['Content-Type' => 'application/json'], $msg);
$signer = new Aws\Signature\SignatureV4('execute-api', $region);
$request = $signer->signRequest($request, $credentials);
$headers = array('Content-Type => application/x-www-form-urlencoded');
$client = new \GuzzleHttp\Client([ 'headers' => $headers]);
$response = $client->send($request);
$result = $response->getBody();
Hey you can use the Connection URL to send message also.
Connection url : https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/#connections
To find go to : Aws console > Api gateway > api > your_api > dashboard their you will find your connection url.
Use php cURL method because its easy and fast as compare to GuzzleHttp
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/#connections/{YOUR_CONNECTION_ID_OF_USER}',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{"message" : "Hello world"}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
I have an API that I am trying to create a function for to send requests, the docs are here: http://simportal-api.azurewebsites.net/Help
I thought about creating this function in PHP:
function jola_api_request($url, $vars = array(), $type = 'POST') {
$username = '***';
$password = '***';
$url = 'https://simportal-api.azurewebsites.net/api/v1/'.$url;
if($type == 'GET') {
$call_vars = '';
if(!empty($vars)) {
foreach($vars as $name => $val) {
$call_vars.= $name.'='.urlencode($val).'&';
}
$url.= '?'.$call_vars;
}
}
$ch = curl_init($url);
// Specify the username and password using the CURLOPT_USERPWD option.
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
if($type == 'POST') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
// Tell cURL to return the output as a string instead
// of dumping it to the browser.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the cURL request.
$response = curl_exec($ch);
// Check for errors.
if(curl_errno($ch)){
// If an error occured, throw an Exception.
//throw new Exception(curl_error($ch));
$obj = array('success' => false, 'errors' => curl_error($ch));
} else {
$response = json_decode($response);
$obj = array('success' => true, 'response' => $response);
}
return $obj;
}
So this determintes whether its a GET or POST request, but the response being returned on some calls is that GET is not supported or POST is not supported, although I am specifying the correct one for each call.
I think I have the function wrong somehow though and wondered if someone could assist me in the right direction? As I've also noticed, I need to allow for DELETE requests too.
for the easier life, try guzzle.
http://docs.guzzlephp.org/en/stable/
you can make a request like this :
use GuzzleHttp\Client;
$client = new Client();
$myAPI = $client->request('GET', 'Your URL goes here');
$myData = json_decode($myAPI->getBody(), true);
then you can access the data like an array
$myData["Head"][0]
The problem is in $url you try to create for GET request.
Your $url for GET request looks like:
GET https://simportal-api.azurewebsites.net/api/v1/?param1=val1¶m2=val2
but from documentation you can clearly see that you $url should be:
GET https://simportal-api.azurewebsites.net/api/v1/param1/val1/param2
for ex.:
GET https://simportal-api.azurewebsites.net/api/v1/customers/{id}
GuzzleHttp is the standard way to work with web service.
You can use auth parameter to send your authentication detail. Also, you can use Oath or Beer token whatever your convenient method is. If you try to call service via a token method, keep in mind you will need to pass authorization by header instead of auth.
See this GuzzleHttp authentication via token. Also, you can catch exception very quickly. See Handle Guzzle exception and get HTTP body
Try below code got from official site ;)
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type')[0];
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
You can find more about GuzzleHttp request here: http://docs.guzzlephp.org/en/stable/quickstart.html#making-a-request
Hope this what you want!
I think you should try to use Postman Tool to request to that API first. If postman does the job it means problem in your PHP code. But if you already used postman and still can't fetch response, so it may be problem with that API. Like URL block.
Here below i have attached my api request
$apiKey = "XXXX";
$Secret = "XXX";
$endpoint = "https://api.test.hotelbeds.com/hotel-api/1.0/hotels";
$request = new http\Client\Request("POST",
$endpoint,
[ "Api-Key" => $apiKey,
"X-Signature" => $signature,
"Accept" => "application/xml" ]);
try
{ $client = new http\Client;
$client->enqueue($request)->send();
$response = $client->getResponse();
if ($response->getResponseCode() != 200) {
printf("%s returned '%s' (%d)\n",
$response->getTransferInfo("effective_url"),
$response->getInfo(),
$response->getResponseCode()
);
} else {
printf($response->getBody());
}
} catch (Exception $ex) {
printf("Error while sending request, reason: %s\n",$ex->getMessage());
}'
getting following error
Uncaught Error: Class 'http\Client\Request' not found in
You need to add a use statement.
use http\Client\Request;
$request = new Request(blah blah);
Of course I assume you are using Composer autoloader. If not, you will also need to require_once() the file.
You can try using cURL instead of pecl_http. Here is an example:
<?php
// Your API Key and secret
$apiKey = "yourApiKey";
$Secret = "yourSecret";
// Signature is generated by SHA256 (Api-Key + Secret + Timestamp (in seconds))
$signature = hash("sha256", $apiKey.$Secret.time());
$endpoint = "https://api.test.hotelbeds.com/hotel-api/1.0/status";
echo "Your API Key is: " . $apiKey . "<br>";
echo "Your X-Signature is: " . $signature . "<br><br>";
// Example of call to the API
try
{
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $endpoint,
CURLOPT_HTTPHEADER => ['Accept:application/json' , 'Api-key:'.$apiKey.'', 'X-Signature:'.$signature.'']
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Check HTTP status code
if (!curl_errno($curl)) {
switch ($http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
case 200: # OK
echo "Server JSON Response:<br>" . $resp;
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
echo $resp;
}
}
// Close request to clear up some resources
curl_close($curl);
} catch (Exception $ex) {
printf("Error while sending request, reason: %s\n",$ex->getMessage());
}
?>
Just make sure that first you uncomment ;extension=php_curl.dll in your php.ini file and restart your server.
We are planning to update our examples in the developer portal because some are outdated or not well documented.
I'm using Ultimate Hosting package of GoDaddy. The account has a static IP and SSL installed. Now when I'm trying to use an API which needs static IP. But scripts are sending requests from random IPs. Please suggest me an way.
My Script
$soap_exception_occured = false;
$wsdl_path = 'http://vrapi.sslwireless.com/?wsdl';
$response = '';
ini_set('soap.wsdl_cache_enabled', '0'); // disabling WSDL cache
try {
$client = new SoapClient($wsdl_path);
}
catch(SoapFault $exception) {
$soap_exception_occured = true;
$response .= '\nError occoured when connecting to the SMS SOAP Server!';
$response .= '\nSoap Exception: '.$exception;
}
I'm using SOAP. Can IP binding help me ?
Assuming you are using curl of php to connect to that API, you should bind each request to your IP:
curl_setopt($ch, CURLOPT_INTERFACE, $myIP);
To bind CURL to a different outgoing network interface or a different IP address, all that is needed is to set the CURLOPT_INTERFACE to the appropriate value before executing the CURL request:
Try this and let me know what happend
$soap_exception_occured = false;
$ipandport = array(
'socket' => array(
'bindto' => 'xx.xx.xx.xx:port',
),
);
$setip = stream_context_create(ipandport);
$wsdl_path = 'http://vrapi.sslwireless.com/?wsdl';
$response = '';
ini_set('soap.wsdl_cache_enabled', '0'); // disabling WSDL cache
try {
$client = new SoapClient($wsdl_path, array('stream_context' => $setip));
}
catch(SoapFault $exception) {
$soap_exception_occured = true;
$response .= '\nError occoured when connecting to the SMS SOAP Server!';
$response .= '\nSoap Exception: '.$exception;
}
This thread will be a not complete without file_get_contents:
$opts = array(
'socket' => array(
'bindto' => 'xx.xx.xx.xx:0',
)
);
$context = stream_context_create($opts);
echo file_get_contents('http://www.example.com', false, $context);