1. Go to this page and download the library: Download four-bytes/four-http-client library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
four-bytes / four-http-client example snippets
use Four\Http\Configuration\ClientConfig;
use Four\Http\Factory\HttpClientFactory;
use Nyholm\Psr7\Factory\Psr17Factory;
// Build a PSR-18 client with middleware stack
$factory = new HttpClientFactory();
$config = ClientConfig::create('https://api.example.com')
->withAuth('bearer', 'your-token')
->withTimeout(30.0)
->build();
$psrClient = $factory->create($config);
// Use PSR-17 request factory to build requests
$requestFactory = new Psr17Factory();
$request = $requestFactory->createRequest('GET', 'https://api.example.com/data');
$response = $psrClient->sendRequest($request);
$data = json_decode((string) $response->getBody(), true);
use Four\Http\Client\ApiClient;
use Four\Http\Configuration\ClientConfig;
use Four\Http\Factory\ApiClientFactory;
class MyApiClient extends ApiClient
{
public function getUser(int $id): array
{
return $this->httpGet('/users/' . $id);
}
public function createUser(array $data): array
{
return $this->httpPost('/users', $data);
}
public function updateUser(int $id, array $data): array
{
return $this->httpPatch('/users/' . $id, $data);
}
public function deleteUser(int $id): void
{
$this->httpDelete('/users/' . $id);
}
}
$config = ClientConfig::create('https://api.example.com')
->withAuth('bearer', 'your-token')
->withTimeout(30.0)
->build();
$factory = new ApiClientFactory();
$client = $factory->create($config, MyApiClient::class);
$user = $client->getUser(42);
$newUser = $client->createUser(['name' => 'John']);
use Psr\Log\NullLogger;
$config = ClientConfig::create('https://api.example.com')
->withLogging(new NullLogger())
// or with custom logger
->withLogging($myPsr3Logger)
->build();
use Four\RateLimit\RateLimiterFactory;
use Four\RateLimit\RateLimitConfiguration;
$config = new RateLimitConfiguration(
algorithm: RateLimitConfiguration::ALGORITHM_TOKEN_BUCKET,
ratePerSecond: 10.0,
burstCapacity: 20,
);
$rateLimiter = (new RateLimiterFactory())->create($config);
$clientConfig = ClientConfig::create('https://api.example.com')
->withRateLimit($rateLimiter)
->build();
use Four\Http\Middleware\MiddlewareInterface;
use Four\Http\Transport\HttpTransportInterface;
class CustomMiddleware implements MiddlewareInterface
{
public function __construct(private LoggerInterface $logger) {}
public function wrap(HttpTransportInterface $transport): HttpTransportInterface
{
return new CustomTransportWrapper($transport, $this->logger);
}
public function getName(): string
{
return 'custom';
}
public function getPriority(): int
{
return 100;
}
}
$config = ClientConfig::create('https://api.example.com')
->withMiddleware(['logging', new CustomMiddleware($logger)])
->build();
use Four\Http\Authentication\TokenProvider;
// Bearer token (default)
$provider = TokenProvider::bearer('your-access-token');
// API key with custom header
$provider = TokenProvider::apiKey('your-api-key', 'X-API-Key');
// Custom header/prefix
$provider = new TokenProvider('your-token', 'X-Custom-Auth', 'Token');
$config = ClientConfig::create('https://api.example.com')
->withAuthentication($provider)
->build();
use Four\Http\Authentication\OAuthProvider;
// OAuth 2.0 with client credentials or refresh token flow
$auth = new OAuthProvider(
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
tokenEndpoint: 'https://api.example.com/oauth/token',
httpClient: $psr18Client,
requestFactory: $requestFactory,
streamFactory: $streamFactory,
refreshToken: 'your-refresh-token', // optional
scopes: ['read', 'write'], // optional
);
use Four\Http\Authentication\OAuth1aProvider;
// OAuth 1.0a signature-based authentication
$auth = new OAuth1aProvider(
consumerKey: 'your-consumer-key',
consumerSecret: 'your-consumer-secret',
accessToken: 'your-access-token',
tokenSecret: 'your-token-secret',
);
use Four\Http\Transport\HttpTransportInterface;
use Four\Http\Transport\HttpResponseInterface;
class MyCustomTransport implements HttpTransportInterface
{
public function request(
string $method,
string $url,
array $headers = [],
?string $body = null
): HttpResponseInterface {
// Your HTTP implementation
return new MyCustomResponse($statusCode, $headers, $body);
}
}
$transport = new MyCustomTransport();
$client = new TransportPsr18Adapter($transport);
use Four\Http\Client\ApiClient;
use Four\Http\Exception\HttpClientException;
use Four\Http\Exception\AuthenticationException;
use Four\Http\Exception\NotFoundException;
use Four\Http\Exception\RateLimitException;
use Four\Http\Exception\RetryableException;
class MyApiClient extends ApiClient
{
public function getData(): array
{
try {
return $this->httpGet('/api/data');
} catch (NotFoundException $e) {
// 404 - Resource not found
echo "Not found: " . $e->getMessage();
} catch (AuthenticationException $e) {
// 401/403 - Auth failed
echo "Auth error: " . $e->getMessage();
} catch (RateLimitException $e) {
// 429 - Rate limited
$retryAfter = $e->getRetryAfter();
sleep($retryAfter);
} catch (RetryableException $e) {
// 500, 502, 503, 504 - Server errors, will be retried automatically
echo "Server error: " . $e->getMessage();
} catch (HttpClientException $e) {
// Other HTTP errors
echo "HTTP error: " . $e->getMessage();
}
return [];
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.