I am new to guzzle and I'm testing its api, when I want to run the sample code in guzzle site, a blank page was shown in the browser. What is the problem?
Thanks.
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
require_once "vendor/autoload.php";
try {
$client = new Client();
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$response = $client->send($request, [
'timeout' => 30,
]);
echo $response->getBody();
} catch (RequestException $e) {
echo $e->getRequest();
if ($e->hasResponse()) {
echo $e->getResponse();
}}
Related
Hi i want to consume a service and i use laravel 5.x with guzzle with this code i can send request and i use the correct api-key but i always obtain 403 forbidden....
public function searchP(Request $request) {
$targa = request('targa');
$client = new \GuzzleHttp\Client();
$url = 'https://xxx.it/api/xxx/xxx-number/'.$targa.'/xxx-xxxx';
$api_key ='xxxxxcheepohxxxx';
try {
$response = $client->request(
'GET',
$url,
['auth' => [null, $api_key]]);
} catch (RequestException $e) {
var_dump($e->getResponse()->getBody()->getContent());
}
// Get JSON
$result = $response->json();
}
Why? I cannot understand
In postman i write in the AUTHORIZATION label this
key : x-apikey
value: xxxxxcheepohxxxx
Add to header
and it works.
i also tried this
.... try {
$response = $client->request('GET',$url,[
'headers' => [
'x-apikey', $api_key
]
]);
} catch .....
but doesn't work
Thx
it should be this, you have a typo
.... try {
$response = $client->request('GET',$url,[
'headers' => [
'x-apikey'=> $api_key
]
]);
} catch .....
index.php
require "vendor/autoload.php";
require "routes.php";
routes.php
<?php
require "vendor/autoload.php";
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
try {
$form_add_route = new Route(
'/blog/add',
array(
'controller' => '\HAPBlog\Controller\EntityAddController',
'method'=>'load'
)
);
$routes = new RouteCollection();
$routes->add('blog_add', $form_add_route);
// Init RequestContext object
$context = new RequestContext();
$context->fromRequest(Request::createFromGlobals());
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match($context->getPathInfo());
// How to generate a SEO URL
$generator = new UrlGenerator($routes, $context);
$url = $generator->generate('blog_add');
echo $url;
}
catch (Exception $e) {
echo '<pre>';
print_r($e->getMessage());
}
src/Controller/EntityAddController.php
<?php
namespace HAPBlog\Controller;
use Symfony\Component\HttpFoundation\Response;
class EntityAddController {
public function load() {
return new Response('ENTERS');
}
}
I am referring to the tutorial given below:
https://code.tutsplus.com/tutorials/set-up-routing-in-php-applications-using-the-symfony-routing-component--cms-31231
But when I try to access the site http://example.com/routes.php/blog/add
It gives a blank page.
Debugging via PHPStorm shows that it does not enter "EntityAddController" Class
What is incorrect in the above code ?
There is no magic behind this process, once you get the route information, you will have to call the configured controller and send the response content.
Take a complete example here:
// controllers.php
class BlogController
{
public static function add(Request $request)
{
return new Response('Add page!');
}
}
// routes.php
$routes = new RouteCollection();
$routes->add('blog_add', new Route('/blog/add', [
'controller' => 'BlogController::add',
]));
// index.php
$request = Request::createFromGlobals();
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);
try {
$attributes = $matcher->match($request->getPathInfo());
$response = $attributes['controller']($request);
} catch (ResourceNotFoundException $exception) {
$response = new Response('Not Found', 404);
} catch (Exception $exception) {
$response = new Response('An error occurred', 500);
}
$response->send();
I'm trying to execute a Google Cloud Function through PHP, but failing to authenticate when all I have is the service_account json file.
I'm using GuzzleHttp as the function returns a Promise.
What I did so far:
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
use Psr\Http\Message\ResponseInterface;
$scopes = [
'https://www.googleapis.com/auth/cloud-platform',
];
$credentials = new ServiceAccountCredentials($scopes, [
'client_email' => "<email>",
'client_id' => "<client_id">,
'private_key' => "<private_key>",
]);
$googleAuthTokenMiddleware = new AuthTokenMiddleware($credentials);
$stack = HandlerStack::create();
$stack->push($googleAuthTokenMiddleware);
$config = array('handler' => $stack,'auth' => 'google_auth');
$httpClient = new Client($config);
$promise = $httpClient->requestAsync("POST", "<function_url>", ['json' => ['data' => ""]]);
$promise->then(
function (ResponseInterface $res) {
echo "<pre>";
print_r($res->getBody());
echo "</pre>";
},
function (RequestException $e) {
echo "<pre>";
print_r($e->getRequest()->getHeaders());
echo "</pre>";
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
$promise->wait();
References:
ServiceAccountCredentials: From namespace Google\Auth\Credentials;
AuthTokenMiddleware: From namespace Google\Auth\Middleware;
HandlerStack: From GuzzleHttp
Client: From GuzzleHttp
Http Response From Above Code
`401 Unauthorized` response: {"error":{"status":"UNAUTHENTICATED","message":"Unauthenticated"}} POST
My Cloud Function
My Cloud Function checks for authentication as follow:
exports.testFunction = functions.https.onCall((data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
'while authenticated.');
}
return "Hooraaay!";
});
What am I doing wrong? How can I successfully authenticate?
I am trying to recreate the following Tesco API code using Symfony\Component\HttpFoundation:
<?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://dev.tescolabs.com/grocery/products/?query={query}&offset={offset}&limit={limit}');
$url = $request->getUrl();
$headers = array(
// Request headers
'Ocp-Apim-Subscription-Key' => '{subscription key}',
);
$request->setHeader($headers);
$parameters = array(
// Request parameters
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_GET);
// Request body
$request->setBody("{body}");
try
{
$response = $request->send();
echo $response->getBody();
}
catch (HttpException $ex)
{
echo $ex;
}
?>
I am new to php in general and I am undertaking my first Symfony project. Could somebody please help me will recreating the above code using Symfony HttpFoundation instead?
I have tried the following code, and I return nothing:
$req2 = Request::create('https://dev.tescolabs.com/grocery/products/?query={query}&offset={offset}&limit={limit}', 'GET');
$req2->headers->set('Ocp-Apim-Subscription-Key', 'my_api_key');
$params = array(
'query' => 'walkers',
'offset' => '0',
'limit' => '10',
);
$req2->query->add($params);
try
{
$response = new Response();
var_dump($response);die;
}
catch (HttpException $ex)
{
die ('EX: '.$ex);
}
Symfony's Request class is used for an incoming request to Symfony. Maybe you should have a look at Guzzle to use an object-oriented approach to create a request or cURL like proposed in Symfony2 - How to perform an external Request
I'm using laravel and I have setup the abstract class method to get response from the various APIs I'm calling. But if the API url is unreachable then it throws an exception. I know I'm missing something. Any help would be great for me.
$offers = [];
try {
$appUrl = parse_url($this->apiUrl);
// Call Api using Guzzle
$client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);
if ($appUrl['scheme'] == 'https') //If https then disable ssl certificate
$client->setDefaultOption('verify', false);
$request = $client->get('?' . $appUrl['query']);
$response = $request->send();
if ($response->getStatusCode() == 200) {
$offers = json_decode($response->getBody(), true);
}
} catch (ClientErrorResponseException $e) {
Log::info("Client error :" . $e->getResponse()->getBody(true));
} catch (ServerErrorResponseException $e) {
Log::info("Server error" . $e->getResponse()->getBody(true));
} catch (BadResponseException $e) {
Log::info("BadResponse error" . $e->getResponse()->getBody(true));
} catch (\Exception $e) {
Log::info("Err" . $e->getMessage());
}
return $offers;
you should set the guzzehttp client with option 'http_errors' => false,
the example code should be like this, document:guzzlehttp client http-error option explain
Set to false to disable throwing exceptions on an HTTP protocol errors (i.e., 4xx and 5xx responses). Exceptions are thrown by default when HTTP protocol errors are encountered.
$client->request('GET', '/status/500');
// Throws a GuzzleHttp\Exception\ServerException
$res = $client->request('GET', '/status/500', ['http_errors' => false]);
echo $res->getStatusCode();
// 500
$this->client = new Client([
'cookies' => true,
'headers' => $header_params,
'base_uri' => $this->base_url,
'http_errors' => false
]);
$response = $this->client->request('GET', '/');
if ($code = $response->getStatusCode() == 200) {
try {
// do danger dom things in here
}catch (/Exception $e){
//catch
}
}
These exceptions are not defined in guzzle officially.
These Exceptions are defined in AWS SDK for PHP.
For official Guzzle you may just do following.
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ClientException;
....
try {
$response = $this->client->request($method, $url, [
'headers' => $headers,
'form_params' => $form_parameters,
]);
$body = (string)$response->getBody();
} catch (ClientException $e) {
// Do some thing here...
} catch (RequestException $e) {
// Do some thing here...
} catch (\Exception $e) {
// Do some thing here...
}
you could create your own exception
class CustomException extends Exception
{
}
next you throws your own exception from abstract class guzzle exception
catch(ConnectException $ConnectException)
{
throw new CustomException("Api excception ConnectException",1001);
}
and then handdle in in global exception handdler render methos
if($exception instanceof CustomException)
{
dd($exception);
}
Not sure how you declared those exceptions and which Guzzle version are you using but in official documentation those exceptions don't exist.
In your case you are probally missing GuzzleHttp\Exception\ConnectException.