PHP code example of daniel-jorg-schuppelius / php-api-toolkit

1. Go to this page and download the library: Download daniel-jorg-schuppelius/php-api-toolkit 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/ */

    

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

// Configure retry behavior for 429, 502, 503, 504 and connect errors
$client->setMaxRetries(5);
$client->setBaseRetryDelay(2); // seconds
$client->setExponentialBackoff(true); // delays: 2s, 4s, 8s, 16s...

$response = $client->request('PROPFIND', '/calendars/user/', [
    'headers' => ['Depth' => '1'],
    'body'    => $propfindXml,
]);
$client->request('MKCOL', '/dav/new-folder/');
$client->request('REPORT', '/calendars/user/', ['body' => $calendarQuery]);

try {
    $client->post('/v1/responses', ['json' => $payload]);
} catch (TooManyRequestsException $e) {
    if ($e->isQuotaExhausted()) {
        // top up the plan — waiting will not help
    }
}

// Request timeout (default: 30s)
$client->setTimeout(60.0);

// Connection timeout (default: 10s)
$client->setConnectTimeout(5.0);

// Set headers faultHeaders([
    'Content-Type' => 'application/json;charset=utf-8',
    'Accept' => 'application/json;charset=utf-8',
]);

// Add/remove individual headers
$client->addDefaultHeader('X-Custom-Header', 'value');
$client->removeDefaultHeader('X-Custom-Header');

// Set query parameters yParams([
    'api_version' => '2.0',
    'format' => 'json',
]);

// Add/remove individual parameters
$client->addDefaultQueryParam('locale', 'de_DE');
$client->removeDefaultQueryParam('format');

$client->setUserAgent('MyApp/1.0.0 (PHP 8.2)');

// 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())
}

$client = (new APIToolkit\Testing\MockApiClient())
    ->addResponse('GET', 'article/90', 200, '{"id":90}')
    ->addResponse('*', 'invoice/*', 204, '');

$article = (new ArticlesEndpoint($client))->get(new ID(90));
$client->getLastRequest(); // ['method' => 'GET', 'uri' => 'article/90', 'options' => []]
bash
composer