I am trying to get search results as per the api documentation
Here is what I wrote in PHP
require_once 'HTTP/Request2.php';
$api_key = 'my_bing_search_api_key';
$url_encoded_keyword = urlencode('animation concepts and tutorials');
$request = new \Http_Request2('https://api.cognitive.microsoft.com/bing/v5.0/search');
$headers = [
'Ocp-Apim-Subscription-Key' => $api_key
];
$request->setHeader($headers);
$url = $request->getUrl();
$parameters = [
'q' => $url_encoded_keyword,
'count' => '10',
'offset' => '0',
'safesearch' => 'Strict',
);
$url->setQueryVariables($parameters);
$request->setMethod(\HTTP_Request2::METHOD_GET);
$request->setBody("{body}");
$search_result = null;
try {
$response = $request->send();
$search_results = json_decode($response->getBody(), true);
return $search_results;
} catch (HttpException $ex) {
return [];
}
I am getting response but it is not having webPages property. It has _type, rankingResponse, relatedSearches and videos properties only.
I tested the same request in the api console. There I am getting the webPages property in the json response.
Any ideas what could have been the reason why I am not getting the webPages in PHP but works on microsoft's api tester site?
From the code snippet, you are passing the keyword to Bing web search API after encoding it.
$url_encoded_keyword = urlencode('animation concepts and tutorials');
$parameters = [
'q' => $url_encoded_keyword,
'count' => '10',
'offset' => '0',
'safesearch' => 'Strict',
);
Try without encoding the keyword. From their API testing console, HTTP request for the same keyword would appear as
https://api.cognitive.microsoft.com/bing/v5.0/search?q=animation
concepts and tutorials&count=10&offset=0&mkt=en-us&safesearch=Moderate
Related
Using Laravel 5 and trying to send some data from my site to another one, which provides me with the REST API. But they use cookies as a authorization. For this moment, I've passed auth successfully. And stuck on how should I send this cookie to API interface via POST method? Here is my listing.
Thanx in advance.
P.S. All things are going on inside the controller.
if (Cookie::get('amoauth') !== null) {
//COOKIE IS HERE
$client = new Client();
$newlead = $client->post('https://domain.amocrm.ru/private/api/v2/json/leads/set', [
'add' => [
'add/name' => 'TEST LEAD',
'add/date_create' => time(),
'add/last_modified' => time(),
'add/status_id' => '1',
'add/price' => 5000
]
]);
} else {
$client = new Client();
$auth = $client->post('https://domain.amocrm.ru/private/api/auth.php',[
'USER_LOGIN' => 'login',
'USER_HASH' => 'hash',
'type' => 'json'
]);
$auth = $auth->getHeaders('Set-Cookie');
Cookie::queue('amoauth', $auth, 15);
return redirect('/test');
}
Now it returns me the following:
Client error: `POST https://domain.amocrm.ru/private/api/v2/json/leads/set` resulted in a `401 Unauthorized` response.
Found the solution: switched to ixudra/curl.
I'm trying to get the latest changes from my documentlist in Sharepoint using PHP and GetListItemChangesSinceToken. I'm using phpSPO as a SDK since there aren't any official Sharepoint SDK's for PHP.
So far I have this:
$payload = array(
'query' => array(
'__metadata' => array('type' => 'SP.ChangeLogItemQuery'),
'ViewName' => '',
'QueryOptions'=> '<QueryOptions><Folder>Shared Documents</Folder></QueryOptions>'
)
);
$headers = array();
$headers["X-HTTP-Method"] = "MERGE";
$changes = $this->request->executeQueryDirect($this->settings->URL . "/_api/web/Lists/GetByTitle('Documents')/GetListItemChangesSinceToken", $headers, $payload);
Which returns: {"error":{"code":"-2147467261, System.ArgumentNullException","message":{"lang":"en-US","value":"Value cannot be null.\r\nParameter name: query"}}}
I've tried changing the X-HTTP-Method and changing the array to fit the documented JSON/XML request (XML in JSON objects, come on Microsoft)
First approach
The following example demonstrates how to utilize GetListItemChangesSinceToken method:
$listTitle = "Documents";
$payload = array(
'query' => array(
'__metadata' => array('type' => 'SP.ChangeLogItemQuery'),
'ViewName' => '',
'QueryOptions'=> '<QueryOptions><Folder>Shared Documents</Folder></QueryOptions>'
)
);
$request = new ClientRequest($webUrl,$authCtx);
$options = array(
'url' => $webUrl . "/_api/web/Lists/GetByTitle('$listTitle')/GetListItemChangesSinceToken",
'data' => json_encode($payload),
'method' => 'POST'
);
$response = $request->executeQueryDirect($options);
//process results
$xml = simplexml_load_string($response);
$xml->registerXPathNamespace('z', '#RowsetSchema');
$rows = $xml->xpath("//z:row");
foreach($rows as $row) {
print (string)$row->attributes()["ows_FileLeafRef"] . "\n";
}
Second approach
Since SharePoint REST Client SDK for PHP now supports GetListItemChangesSinceToken method, the previous example could be invoked like this:
$list = $ctx->getWeb()->getLists()->getByTitle($listTitle);
$query = new ChangeLogItemQuery();
//to request all the items set ChangeToken property to null
$query->ChangeToken = "1;3;e49a3225-13f6-47d4-a146-30d9caa05362;635969955256400000;10637059";
$items = $list->getListItemChangesSinceToken($query);
$ctx->executeQuery();
foreach ($items->getData() as $item) {
print "[List Item] $item->Title\r\n";
}
More examples could be found here under phpSPO repository.
I'm trying to access a webservice. I'm already using this webservice from an android app but now I need to access some functions from a php document. If I use chromes advanced rest client application for testing it works fine if I select the POST option and application/x-www-form-urlencode as content-type. But when I try to access the webservice from my PHP file I get the response from the server that it can't find the value "tag". This is the code:
$data = array( 'tag' => 'something');
$options = array('http' => array(
'method' => 'POST',
'content' => $data,
'header' => "Content-Type: application/x-www-form-urlencode")
);
$context = stream_context_create($options);
$url = 'myurl';
$result = file_get_contents($url,false,$context);
$response = json_decode($result);
What is wrong with this code?
Thanks for any help!
Try this:
$data = http_build_query( array( 'tag' => 'something') );
As defined here, "Content" value must be a string: http_build_query generate the URL-encoded query string you need.
I'm trying to test a Laravel API endpoint and want to call it in code.
$request = Request::create( $path, $method );
$response = Route::dispatch( $request );
This snippet works fine for GET but I need to be able to set up POST calls too. Setting the $method to POST works as well, but I can't find documentation detailing how to attach post data.
Any advice?
As you mentioned in the comments, you could use $this->call() but you can actually do it with your current code too. If you take a look at the signature of the Request::create() function you can see that it takes $parameters as third argument:
public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
And the docblock says: The query (GET) or request (POST) parameters
So you can simply add the data to Request::create()
$data = array('foo' => 'bar');
$request = Request::create( $path, $method, $data );
$response = Route::dispatch( $request );
I've spent nearly a day trying to get this working myself for social authentication with passport and Angular front-end.
When I use the Restlet API Client to make the request I always get a successful response.
Restlet Client Request
Restlet client response
However using the following method of making internal requests always gave me an error.
$request = Request::create(
'/oauth/token',
'POST',
[
'grant_type' => 'social',
'client_id' => 'your_oauth_client_id',
'client_secret' => 'your_oauth_client_secret',
'provider' => 'social_auth_provider', // e.g facebook, google
'access_token' => 'access_token', // access token issued by specified provider
]
);
$response = Route::dispatch($request);
$content = json_decode($response->getContent(), true);
if (! $response->isSuccessful()) {
return response()->json($content, 401);
}
return response()->json([
'content' => $content,
'access_token' => $content['access_token'],
'refresh_token' => $content['refresh_token'],
'token_type' => $content['token_type'],
'expires_at' => Carbon::parse(
$content['expires_in']
)->toDateTimeString()
]);
This specific error:
{
error: "unsupported_grant_type",
error_description: "The authorization grant type is not supported by the
authorization server.",
hint: "Check that all required parameters have been provided",
message: "The authorization grant type is not supported by the authorization server."
}
I had the feeling it has to do with the way the form data is sent in the request, so while searching for a proper way to make such internal requests in laravel I came across this sample project with a working implementation: passport-social-grant-example.
In summary here's how to do it:
$proxy = Request::create(
'/oauth/token',
'POST',
[
'grant_type' => 'social',
'client_id' => 'your_oauth_client_id',
'client_secret' => 'your_oauth_client_secret',
'provider' => 'social_auth_provider', // e.g facebook, google
'access_token' => 'access_token', // access token issued by specified provider
]
);
return app()->handle($proxy);
Hope this helps.
I try to make google url shortener with wp_remote_post()
but I got error result,
I know how to use CURL, but CURL not allowed in WordPress!
This resource for API with WordPress:
http://codex.wordpress.org/Function_Reference/wp_remote_post
http://codex.wordpress.org/Function_Reference/wp_remote_retrieve_body
http://codex.wordpress.org/HTTP_API#Other_Arguments
http://codex.wordpress.org/Function_Reference/wp_remote_post#Related
This google url shortener API docs:
https://developers.google.com/url-shortener/v1/getting_started#shorten
This is my code:
function google_url_shrt{
$url = 'http://example-long-url.com/example-long-url'; // long url to short it
$args = array(
"headers" => array( "Content-type:application/json" ),
"body" => array( "longUrl" => $url )
);
$short = wp_remote_post("https://www.googleapis.com/urlshortener/v1/url", $args);
$retrieve = wp_remote_retrieve_body( $short );
$response = json_decode($retrieve, true);
echo '<pre>';
print_r($response);
echo '</pre>';
}
The WordPress API requires that the headers array contain an element content-type if you want to change the content type of a POST request.
Also, it looks like the body of your HTTP request is being passed as a PHP array, not as a JSON string as the Google Shortener API requires.
Wrap the array definition for body in a json_encode statement, and make the headers field a sub-array, and give it a shot:
$args = array(
'headers' => array('content-type' => 'application/json'),
'body' => json_encode(array('longUrl' => $url)),
);
Alternative, you could just write the JSON format yourself as it is fairly simple:
$args = array(
'headers' => array('content-type' => 'application/json'),
'body' => '{"longUrl":"' . $url . '"}',
);