Skip to content

Instantly share code, notes, and snippets.

@stevenwadejr
Last active May 3, 2019 20:48
Show Gist options
  • Save stevenwadejr/e3677bcbd0122ff7cb50462a44380a10 to your computer and use it in GitHub Desktop.
Save stevenwadejr/e3677bcbd0122ff7cb50462a44380a10 to your computer and use it in GitHub Desktop.
Guzzle Talk Examples
<?php
$client = new GuzzleHttp\Client;
$response = $client->get('http://example.com/foo');
<?php
require_once 'vendor/autoload.php';
$client = new GuzzleHttp\Client;
echo "Start\n";
$time = -time();
$delays = [5000, 2500, 1000, 500, 0];
foreach ($delays as $delay) {
echo "Making request [delay = $delay]\n";
$client->get('https://mockbin.org/delay/' . $delay);
echo "Response received [delay = $delay]\n";
}
$time += time();
echo "Finished\n";
echo sprintf('Finished in %f seconds', $time);
<?php
require_once 'vendor/autoload.php';
$client = new GuzzleHttp\Client;
echo "Start\n";
$time = -time();
$delays = [5000, 2500, 1000, 500, 0];
$promises = [];
foreach ($delays as $delay) {
echo "Making request [delay = $delay]\n";
$url = 'https://mockbin.org/delay/' . $delay;
$promises[] = $client->getAsync($url)
->then(function() use ($delay) {
echo "Response received [delay = $delay]\n";
});
}
\GuzzleHttp\Promise\unwrap($promises);
$time += time();
echo "Finished\n";
echo sprintf('Finished in %f seconds', $time);
<?php
$baseUrl = 'https://api.followupboss.com/v1';
$headers = [
'Accept: application/json',
'Content-Type: application/json'
];
$payload = json_encode([
'source' => 'longhornphp.com',
'system' => 'LonghornPHP',
'type' => 'General Inquiry',
'person' => [
'firstName' => 'Fox',
'lastName' => 'Mulder',
'source' => 'cURL',
'emails' => [
['value' => 'fox.mulder@fbi.gov'],
['value' => 'spooky@iwanttobelieve.org']
]
]
]);
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $baseUrl . '/events');
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_USERPWD, 'my_api_key:');
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handle, CURLINFO_HEADER_OUT, 1);
curl_setopt($handle, CURLOPT_POST, 1);
curl_setopt($handle, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($handle);
curl_close($handle);
echo $response;
<?php
$baseUrl = 'https://api.followupboss.com/v1/';
$headers = [
'Accept: application/json',
'Content-Type: application/json'
];
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $baseUrl . 'people');
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_USERPWD, 'my_api_key:');
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($handle);
if(curl_errno($handle)){
echo 'Request Error:' . curl_error($handle);
}
$people = json_decode($response, true);
$client = new \GuzzleHttp\Client([
'base_uri' => $baseUrl,
'timeout' => 2.0,
'auth' => ['my_api_key', '']
]);
$request = new \GuzzleHttp\Psr7\Request(
'GET',
'people',
$headers
);
try {
$response = $client->send($request);
$people = json_decode($response->getBody()->getContents(), true);
$response = $client->send($request->withUri(
new \GuzzleHttp\Psr7\Uri('tasks')
));
$tasks = json_decode($response->getBody()->getContents(), true);
} catch (\Exception $e) {
// handle errors
}
<?php
$baseUrl = 'https://api.followupboss.com/v1';
$headers = [
'Accept: application/json',
'Content-Type: application/json'
];
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $baseUrl . '/people');
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_USERPWD, 'my_api_key:');
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
$people = curl_exec($handle);
if(curl_errno($handle)){
echo 'Request Error:' . curl_error($handle);
}
curl_setopt($handle, CURLOPT_URL, $baseUrl . '/tasks');
$tasks = curl_exec($handle);
if(curl_errno($ch)){
echo 'Request Error:' . curl_error($handle);
}
curl_close($handle);
echo $people;
echo PHP_EOL . PHP_EOL;
echo $tasks;
<?php
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../JsonStream.php';
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Promise\coroutine;
$baseUrl = 'https://api.followupboss.com/v1/';
$headers = [
'Accept: application/json',
'Content-Type: application/json'
];
$stack = HandlerStack::create();
$stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
$jsonStream = new JsonStream($response->getBody());
return $response->withBody($jsonStream);
}));
$client = new Client([
'base_uri' => $baseUrl,
'handler' => $stack,
'auth' => ['my_api_key', '']
]);
$endpoints = ['people', 'tasks', 'events', 'calls'];
$promises = [];
foreach ($endpoints as $endpoint) {
$promises[$endpoint] = new Coroutine(
function() use ($client, $endpoint, $headers) {
$request = new Request('GET', $endpoint, $headers);
$response = yield $client->sendAsync($request);
$json = $response->getBody()->json();
yield $json[$endpoint] ?? [];
}
);
}
try {
$results = \GuzzleHttp\Promise\unwrap($promises);
print_r($results);
} catch (\Exception $e) {
echo $e->getMessage();
}
<?php
$apiKey = 'my_api_key:';
$people = file_get_contents('https://' . $apiKey . '@api.followupboss.com/v1/people');
<?php
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../JsonStream.php';
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\ResponseInterface;
$baseUrl = 'https://api.followupboss.com/v1/';
$headers = [
'Accept: application/json',
'Content-Type: application/json'
];
$stack = HandlerStack::create();
$stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
$jsonStream = new JsonStream($response->getBody());
return $response->withBody($jsonStream);
}));
$client = new Client([
'base_uri' => $baseUrl,
'handler' => $stack,
'auth' => ['my_api_key', '']
]);
$endpoints = ['people', 'tasks', 'events', 'calls'];
$promises = [];
foreach ($endpoints as $endpoint) {
$request = new Request('GET', $endpoint, $headers);
$promises[$endpoint] = $client->sendAsync($request)
->then(function (ResponseInterface $response) use ($endpoint) {
$json = $response->getBody()->json();
return $json[$endpoint] ?? [];
});
}
try {
$results = \GuzzleHttp\Promise\unwrap($promises);
print_r($results);
} catch (\Exception $e) {
echo $e->getMessage();
}
<?php
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../JsonStream.php';
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\ResponseInterface;
$baseUrl = 'https://api.followupboss.com/v1/';
$headers = [
'Accept: application/json',
'Content-Type: application/json'
];
$stack = HandlerStack::create();
$stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
$jsonStream = new JsonStream($response->getBody());
return $response->withBody($jsonStream);
}));
$client = new Client([
'base_uri' => $baseUrl,
'handler' => $stack,
'auth' => ['my_api_key', '']
]);
$request = new Request('GET', 'people', $headers);
try {
$response = $client->send($request);
$people = $response->getBody()->json();
$response = $client->send($request->withUri(new Uri('tasks')));
$tasks = $response->getBody()->json();
$response = $client->send($request->withUri(new Uri('events')));
$events = $response->getBody()->json();
$response = $client->send($request->withUri(new Uri('calls')));
$calls = $response->getBody()->json();
print_r($people);
print_r($tasks);
print_r($events);
print_r($calls);
} catch (\Exception $e) {
echo $e->getMessage();
}
<?php
require __DIR__ . '/../vendor/autoload.php';
use GuzzleHttp\Client;
$baseUrl = 'https://api.followupboss.com/v1/';
$headers = [
'Accept: application/json',
'Content-Type: application/json',
'X-System: my_system_name',
'X-System-Key: my_secret_system_key'
];
$client = new Client([
'base_uri' => 'https://api.followupboss.com/v1/',
'auth' => ['my_api_key', '']
]);
$leadData = [
'source' => 'longhornphp.com',
'system' => 'LonghornPHP',
'type' => 'General Inquiry',
'person' => [
'firstName' => 'Dana',
'lastName' => 'Scully',
'source' => 'cURL',
'emails' => [
['value' => 'dana.scully@fbi.gov']
]
]
];
try {
$response = $client->post('events', ['json' => $leadData]);
$lead = json_decode($response->getBody()->getContents(), true);
print_r($lead);
} catch (\Exception $e) {
echo $e->getMessage();
}
<?php
function xrange($start, $limit, $step = 1) {
for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
}
foreach (xrange(1, 9) as $number) {
echo "$number ";
}
<?php
// Waits on all of the provided promises and returns the fulfilled values.
unwrap($promises);
// Returns a promise that is fulfilled when all the items in the array are fulfilled.
all($promises);
// When count amount of promises have been fulfilled, the returned promise is
// fulfilled with an array that contains the fulfillment values of the winners
// in order of resolution.
some($count, $promises);
// Returns a promise that is fulfilled when all of the provided promises have
// been fulfilled or rejected.
settle($promises)
<?php
$promise = $client->sendAsync($request);
$promise->then(
function (ResponseInterface $res) {
echo $res->getStatusCode() . "\n";
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
<?php
require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;
$baseUrl = 'https://api.followupboss.com/v1/';
$headers = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'X-System' => 'Swade-Co',
'X-System-Key' => '178d70520886d8ea56c9cd3de1ad8960'
];
$container = [];
$history = Middleware::history($container);
$mock = new \GuzzleHttp\Handler\MockHandler([
new Response(200, ['X-Foo' => 'Bar'])
]);
$stack = HandlerStack::create($mock);
$stack->push($history);
$client = new Client(['base_uri' => $baseUrl, 'handler' => $stack]);
$client->request('GET', 'people', ['headers' => $headers]);
// Iterate over the requests and responses
foreach ($container as $transaction) {
echo $transaction['request']->getMethod() . PHP_EOL;
echo $transaction['request']->getUri()->getPath() . PHP_EOL;
echo $transaction['request']->getHeader('X-System')[0] . PHP_EOL;
//> GET, HEAD
if ($transaction['response']) {
echo $transaction['response']->getStatusCode();
//> 200, 200
} elseif ($transaction['error']) {
echo $transaction['error'];
//> exception
}
}
<?php
class RequestTest {
public function testRequest() {
$this->assertEquals(
'Swade-Co',
$transaction['request']->getHeader('X-System')[0]
);
}
}
<?php declare(strict_types=1);
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
class JsonStream implements StreamInterface
{
use StreamDecoratorTrait;
public function json(): ?array
{
return json_decode((string) $this->getContents(), true);
}
}
<?php
$logger = new \Monolog\Logger('http');
$logger->pushHandler(
new \Monolog\Handler\StreamHandler(
'path/to/your.log',
\Monolog\Logger::INFO
)
);
$stack = \GuzzleHttp\HandlerStack::create();
$stack->push(\GuzzleHttp\Middleware::log(
$logger,
new \GuzzleHttp\MessageFormatter
));
<?php
\GuzzleHttp\Middleware::tap($before, $after);
\GuzzleHttp\Middleware::retry($decider, $delay);
\GuzzleHttp\Middleware::log($logger, $messageFormatter);
$stack->push(function (callable $handler) {
return function (
RequestInterface $request,
array $options
) use ($handler) {
// do stuff
return $handler($request, $options);
};
});
<?php
// Create a mock and queue two responses.
$mock = new \GuzzleHttp\Handler\MockHandler([
new Response(200, ['X-Foo' => 'Bar']),
new Response(202, ['Content-Length' => 0]),
new RequestException("Error Communicating with Server", new Request('GET', 'test'))
]);
$handler = \GuzzleHttp\HandlerStack::create($mock);
$client = new \GuzzleHttp\Client(['handler' => $handler]);
// The first request is intercepted with the first response.
echo $client->request('GET', '/')->getStatusCode(); //> 200
// The second request is intercepted with the second response.
echo $client->request('GET', '/')->getStatusCode(); //> 202
<?php
use GuzzleHttp\HandlerStack;
use Psr\Http\Message\RequestInterface;
$stack = HandlerStack::create();
$stack->push(function (callable $handler) use ($accessToken, $oauthProvider) {
return new OAuthTokenMiddleware(
$accessToken,
$oauthProvider,
$handler
);
});
class OAuthTokenMiddleware {
public function __construct(
AccessToken $accessToken,
OAuthProvider $provider,
callable $nextHandler
) {
$this->accessToken = $accessToken;
$this->provider = $provider;
$this->nextHandler = $nextHandler;
}
public function __invoke(RequestInterface $request, array $options) {
if ($this->accessToken->hasExpired()) {
$this->accessToken = $this->provider->refreshToken(
$this->accessToken
);
}
$request = $request->withHeader(
'Authentication',
'Bearer ' . (string) $this->accessToken
);
return $this->nextHandler($request, $options);
}
}
<?php
$stack = \GuzzleHttp\HandlerStack::create();
$stack->push(\GuzzleHttp\Middleware::retry(
function ($retries, RequestInterface $request, ResponseInterface $response) {
return $response->getStatusCode() >= 400 && $retries < 4;
},
function ($retries) {
return $retries * 1000;
}
));
$client = new \GuzzleHttp\Client(['handler' => $stack]);
$request = new Request('GET', 'http://localhost:8888');
$response = $client->send($request);
echo $response->getBody()->getContents();
class RetryMiddleware {
public function __construct(AccessToken $accessToken) {
$this->accessToken = $accessToken;
}
public function shouldRetry(int $retries, RequestInterface $request, ResponseInterface $response): bool {
// normal checks go here
$body = json_encode($response->getBody()->getContents(), true);
$error = $body['error'] ?? null;
if ($response->getStatusCode() === 400 && $error === 'expired_token') {
$this->accessToken->expiresAt = 0;
$this->accessToken->save();
return true;
}
return false;
}
public function getDelay(int $retries): int {
return $retries * 1000;
}
}
$retryMiddleware = new RetryMiddleware($accessToken);
$stack->push(Middleware::retry(
[$retryMiddleware, 'shouldRetry'],
[$retryMiddleware, 'getDelay']
));
<?php
use League\StatsD\Client as StatsD;
$stack = \GuzzleHttp\HandlerStack::create();
$stack->setHandler(\GuzzleHttp\choose_handler());
$statsd = new StatsD;
$statsd->configure([...]);
$stack->push(\GuzzleHttp\Middleware::tap(function () use ($statsd) {
$statsd->increment('apikey.usage');
}));
$stack->push(Middleware::tap(function (RequestInterface $request) use ($statsd) {
$authHeader = $request->getHeader('Authorization');
$encoded = str_replace('Basic ', '', $authHeader[0]);
$auth = base64_decode($encoded);
[$username] = explode(':', $auth);
$statsd->increment('apikey.usage.username.' . $username);
}));
$stack->push(Middleware::tap(app()->make(ApiKeyUsage::class)));
class ApiKeyUsage {
private $statsd;
public function __construct(StatsD $statsd) {
$this->statsd = $statsd;
}
public function __invoke(RequestInterface $request, array $options) {
$this->statsd->increment('apikey.usage');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment