<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
daniel-jorg-schuppelius / php-api-toolkit example snippets
class CreatedID extends ID {
protected bool $wrapped = true; // emitted as {"created_id": {"id": 7}}
}
use APIToolkit\Contracts\Abstracts\API\Authentication\BearerAuthentication;
// Create your API client extending ClientAbstract
// Simply pass the base URL - HttpClient is created internally
$apiClient = new MyApiClient('https://api.example.com', $logger);
// Set authentication
$auth = new BearerAuthentication('your-token');
$apiClient->setAuthentication($auth);
// Make requests - auth headers are added automatically
$response = $apiClient->get('/endpoint');
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\HandlerStack;
$stack = HandlerStack::create();
// Add custom middleware...
$httpClient = new HttpClient([
'base_uri' => 'https://api.example.com',
'handler' => $stack,
]);
$apiClient = new MyApiClient('https://api.example.com', $logger, false, $httpClient);
use APIToolkit\Contracts\Abstracts\API\Authentication\BearerAuthentication;
$auth = new BearerAuthentication('your-jwt-token');
$client->setAuthentication($auth);
// Update token later (e.g., after refresh)
$auth->setToken('new-refreshed-token');
use APIToolkit\Contracts\Abstracts\API\Authentication\BasicAuthentication;
$auth = new BasicAuthentication('username', 'password');
$client->setAuthentication($auth);
use APIToolkit\Contracts\Abstracts\API\Authentication\ApiKeyAuthentication;
// Default header: X-API-Key
$auth = new ApiKeyAuthentication('your-api-key');
// Custom header name
$auth = new ApiKeyAuthentication('your-api-key', 'X-Custom-Auth');
$client->setAuthentication($auth);
use APIToolkit\API\Authentication\OAuth2\{OAuth2ClientCredentialsAuthentication, OAuth2ClientCredentialsGrant};
$grant = new OAuth2ClientCredentialsGrant(
'client-id',
'client-secret',
'https://provider.example.com/oauth/token'
);
// Client authentication at the token endpoint:
// default: credentials in the form body (e.g. FedEx)
$grant->setTokenAuthMethod(OAuth2ClientCredentialsGrant::AUTH_METHOD_BASIC); // HTTP Basic header (e.g. UPS)
// Token persistence is pluggable via OAuth2TokenStoreInterface
// (default: in-memory). Inject e.g. an encrypted per-tenant store:
$auth = new OAuth2ClientCredentialsAuthentication($grant, $myTokenStore, ['read', 'write']);
$client->setAuthentication($auth);
$grant = new OAuth2ClientCredentialsGrant('client-id', '', 'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token');
$grant->setPrivateKeyJwt($privateKeyPem, $certificatePem); // certificate adds the x5t/x5t#S256 header
$auth = new OAuth2ClientCredentialsAuthentication($grant, null, ['https://graph.microsoft.com/.default']);
$client->setAuthentication($auth);
use APIToolkit\API\Authentication\OAuth2\{OAuth2PasswordAuthentication, OAuth2PasswordGrant};
$grant = new OAuth2PasswordGrant('client-id', '', 'https://provider.example.com/oauth2/token');
// Provider quirks go into the extra params, e.g. a provider that labels its
// password flow client_credentials: ['grant_type' => 'client_credentials'].
$auth = new OAuth2PasswordAuthentication($grant, $username, $password, $myTokenStore, ['openMasterdata']);
$client->setAuthentication($auth);
use APIToolkit\Contracts\Interfaces\API\AuthenticationInterface;
class OAuth1Authentication implements AuthenticationInterface {
public function getAuthHeaders(): array {
return ['Authorization' => 'OAuth ' . $this->buildOAuthHeader()];
}
public function getType(): string {
return 'OAuth1';
}
public function isValid(): bool {
return !empty($this->consumerKey);
}
}
$client = new MyClient('https://api.openai.com/v1/responses');
$client->buildUrl('/v1/models'); // https://api.openai.com/v1/models
// Gateway prefixes survive: base https://gw.example.com/proxy/v1
// + /v1/models => https://gw.example.com/proxy/v1/models
// Set minimum interval between requests (default: 0.25s, minimum: 0.2s)
$client->setRequestInterval(0.5); // 500ms between requests
try {
$client->post('/v1/responses', ['json' => $payload]);
} catch (TooManyRequestsException $e) {
if ($e->isQuotaExhausted()) {
// top up the plan — waiting will not help
}
}
// Set proxy for enterprise environments
$client->setProxy('http://proxy.company.com:8080');
// With authentication
$client->setProxy('http://user:[email protected]:8080');
// Disable proxy
$client->setProxy(null);
// Disable SSL verification (development only!)
$client->setVerifySSL(false);
// Check status
$client->isSSLVerificationEnabled();
// Trust a custom CA bundle (PEM), e.g. a self-signed certificate of an on-premises API
$client->setCaBundle('/etc/ssl/certs/my-api-ca.pem');
$client->getCaBundle(); // '/etc/ssl/certs/my-api-ca.pem'
$client->setCaBundle(null); // back to the system trust store
use APIToolkit\Contracts\Abstracts\API\Authentication\BearerAuthentication;
// Simple constructor - just base URL
$client = new MyApiClient('https://api.example.com', $logger);
// Timeouts
$client->setTimeout(30.0);
$client->setConnectTimeout(10.0);
// Default headers
$client->setDefaultHeaders([
'Content-Type' => 'application/json;charset=utf-8',
'Accept' => 'application/json;charset=utf-8',
]);
// User-Agent
$client->setUserAgent('MyApp/1.0.0');
// Default query parameters
$client->setDefaultQueryParams(['api_version' => '2']);
// Authentication with additional headers
$auth = new BearerAuthentication($token, [
'X-Client-ID' => $clientId,
]);
$client->setAuthentication($auth);
// Rate limiting
$client->setRequestInterval(0.5);
$client->setMaxRetries(3);
// Enterprise environment (optional)
$client->setProxy('http://proxy:8080');
$client->setVerifySSL(false); // Development only!
use APIToolkit\Exceptions\TooManyRequestsException;
use APIToolkit\Exceptions\UnauthorizedException;
use APIToolkit\Exceptions\NotFoundException;
try {
$response = $client->get('/resource');
} catch (UnauthorizedException $e) {
// 401 - Invalid or expired token
} catch (NotFoundException $e) {
// 404 - Resource not found
} catch (TooManyRequestsException $e) {
// 429 - Rate limited or quota exhausted ($e->isQuotaExhausted())
}