Use PHP SDKs generated in Postman

View as Markdown

This guide provides instructions for using PHP SDKs generated by Postman SDK Generator. It covers how to import the SDK into your project, run example code, and best practices for using the SDK effectively in your applications.

SDK structure

The PHP SDK includes the following key files:

  • src/Client.php — The main SDK client, instantiated with named constructor arguments.
  • src/Services/ — Service classes with methods for each API endpoint.
  • src/Models/ — Data models (plain PHP classes with typed properties, enums, and fromArray/jsonSerialize support).
  • src/Exceptions/ — Exception classes (ApiException and typed error model exceptions).
  • src/Environment.php — Environment constants with base URL values.
  • src/Retry.php — Guzzle retry middleware.
  • composer.json — Package manifest and autoloading configuration.

The following is an example of the typical structure of a generated PHP SDK:

your-sdk
README.md
composer.json
.gitignore
.devcontainer
devcontainer.json
example
index.php
src
Client.php
Environment.php
Retry.php
Services
BaseService.php
[ServiceName].php
Models
[ModelName].php
Exceptions
ApiException.php
[ModelName]Exception.php
OAuth
OAuthToken.php
TokenManager.php
Utils
Serializer.php
LineDecoder.php
docs
services
[ServiceName].md
models
[ModelName].md

Example usage

Each generated SDK includes an example/ directory with a working script demonstrating SDK usage.

The example includes the following features:

  • SDK initialization with named arguments
  • Calling an API endpoint
  • Constructing nested model inputs
  • Exception handling

example/index.php

Import the PHP SDK locally

You can import the generated SDK using Composer from a local path or from Packagist. Below are instructions for each method.

Import using a local path

To import an SDK that hasn’t yet been published to Packagist, add a path repository to your project’s composer.json:

1{
2 "repositories": [
3 {
4 "type": "path",
5 "url": "../path/to/your-sdk"
6 }
7 ],
8 "require": {
9 "your-vendor/your-sdk": "*"
10 }
11}

Then run:

$composer install

Import using Packagist

Once your SDK is published to Packagist, add it as a standard dependency:

$composer require your-vendor/your-sdk

Or add it manually to your composer.json:

1{
2 "require": {
3 "your-vendor/your-sdk": "^1.0"
4 }
5}

Then run composer install.

Publish to Packagist

To share your generated PHP SDK with the community, you can publish it to Packagist. This allows other developers to install it using composer require.

Prerequisites

To publish your SDK to Packagist, you need the following:

  • A public Git repository (for example, GitHub or GitLab).
  • A Packagist account.
  • A valid composer.json with a name field in vendor/package format.

Initial setup

  1. Push your SDK to a public repository.

  2. Log in to Packagist and click Submit.

  3. Enter your repository URL and submit. Packagist validates your composer.json and creates the package listing.

  4. Configure a GitHub webhook so Packagist automatically picks up new versions. In your repository settings, follow the instructions shown on your Packagist package page under Set up GitHub Hook.

Configure composer.json

Your SDK’s composer.json should include the following fields for a proper Packagist listing:

1{
2 "name": "your-vendor/your-sdk",
3 "description": "SDK for Your API",
4 "type": "library",
5 "license": "MIT",
6 "authors": [
7 {
8 "name": "Your Name",
9 "email": "your@email.com"
10 }
11 ],
12 "require": {
13 "php": "^8.0",
14 "guzzlehttp/guzzle": "^7.0",
15 "symfony/serializer": "^7.0",
16 "symfony/property-info": "^7.0",
17 "symfony/property-access": "^7.0",
18 "phpdocumentor/reflection-docblock": "^5.4"
19 },
20 "autoload": {
21 "psr-4": {
22 "YourSdk\\": "src/"
23 }
24 }
25}

Publish your PHP SDK to Packagist

To publish your SDK, do the following:

  1. Tag a release using semantic versioning.

    $git tag v1.0.0
    $git push origin v1.0.0
  2. Packagist picks up the tag automatically if the webhook is configured. Otherwise, trigger a manual update from your package page.

  3. Verify the publication at https://packagist.org/packages/your-vendor/your-sdk.

Publish updates

To publish updates to your SDK, do the following:

$# Tag a new version
$git tag v1.0.1
$git push origin v1.0.1

Best practices for publishing PHP SDKs

Use the following best practices when publishing your PHP SDK to Packagist:

  • Use semantic versioning.
  • Include a comprehensive README.md with installation and usage instructions.
  • Tag releases in Git rather than relying on branch-based version constraints.
  • Declare a specific PHP version constraint in composer.json (for example, "php": "^8.1").
  • Run your test suite before tagging a release.

Advanced usage

You can further customize the SDK by modifying the generated code, adding new features, or integrating it with your existing codebase. Here are some advanced topics to explore.

Authentication

The SDK supports various authentication methods. Configure authentication when instantiating the SDK client using named constructor arguments.

The SDK includes authentication support based on the security schemes defined in your API specification. The following examples show the possible authentication methods.

1use YourSdk\Client;
2
3$sdk = new Client(
4 apiKey: 'your-api-key',
5 apiKeyHeader: 'X-API-KEY', // configurable; defaults to 'X-API-KEY'
6);

To update credentials after initialization, use the corresponding setter methods. The setApiKey, setAccessToken, setBasicAuth, setClientId, and setClientSecret methods are each only generated when the corresponding auth type is in the specification.

1$sdk->setApiKey('new-api-key');
2$sdk->setAccessToken('new-token');
3$sdk->setBasicAuth('new-username', 'new-password');
4$sdk->setClientId('new-client-id');
5$sdk->setClientSecret('new-client-secret');

Error handling

The SDK raises ApiException for API errors, which includes details about the status code, response body, and headers. You can catch this exception to handle errors gracefully in your application.

To handle errors, do the following:

1use YourSdk\Exceptions\ApiException;
2
3try {
4 $user = $sdk->users->getUser('123');
5 echo $user->name;
6} catch (ApiException $e) {
7 echo "Status: " . $e->statusCode . "\n";
8 echo "Message: " . $e->getMessage() . "\n";
9 echo "Body: " . $e->responseBody . "\n";
10 print_r($e->responseHeaders);
11
12 // Attempt to decode the response body as JSON
13 $decoded = $e->getDecodedBody(); // returns array|null
14}

To handle specific status codes, do the following:

1try {
2 $sdk->users->deleteUser('123');
3} catch (ApiException $e) {
4 match ($e->statusCode) {
5 404 => print("User not found\n"),
6 403 => print("Permission denied\n"),
7 default => print("API error: " . $e->getMessage() . "\n"),
8 };
9}

When the API specification defines error response models, the SDK generates typed exception classes (for example, ValidationErrorException) that extend ApiException and include the deserialized error model. Access the model using getError().

1use YourSdk\Exceptions\ApiException;
2use YourSdk\Exceptions\ValidationErrorException;
3
4try {
5 $sdk->users->createUser($newUser);
6} catch (ValidationErrorException $e) {
7 $error = $e->getError(); // Returns a typed ValidationError model instance
8 echo "Validation message: " . $error->message . "\n";
9 echo "Field: " . $error->field . "\n";
10} catch (ApiException $e) {
11 // Fallback for all other HTTP errors
12 echo "API error: " . $e->statusCode . "\n";
13}

Environment management

The SDK supports multiple environments (for example, production, staging) with different base URLs.

1use YourSdk\Client;
2use YourSdk\Environment;
3
4// Use an environment constant defined in the spec
5$sdk = new Client(
6 accessToken: 'your-token',
7 environment: Environment::Production,
8);
9
10// Or set a fully custom base URL at any time
11$sdk->setBaseUrl('https://staging.api.example.com');

Available environment constants are defined in src/Environment.php.

Hierarchical configuration

PHP supports four levels of configuration: SDK (through the constructor or setBaseUrl()), service, method, and request. Each level overrides the previous, with request being most specific.

1use YourSdk\Client;
2use YourSdk\Environment;
3
4// 1. SDK level — default for everything
5$sdk = new Client(
6 accessToken: 'your-token',
7 timeout: 10000,
8 environment: Environment::Default,
9);
10
11// 2. Service level — override for all methods in usersService
12$sdk->users->setConfig([
13 'timeout' => 15000,
14 'accessToken' => 'service-scoped-token',
15]);
16
17// 3. Method level — override for getUser only
18$sdk->users->setGetUserConfig([
19 'baseUrl' => 'https://legacy-api.example.com',
20 'timeout' => 20000,
21]);
22
23// 4. Request level — override for this single call
24$user = $sdk->users->getUser('123', requestConfig: [
25 'timeout' => 30000,
26 'accessToken' => 'request-scoped-token',
27]);

Supported configuration keys depend on the auth type defined in the specification:

KeyTypeDescription
baseUrlstringOverride base URL.
timeoutfloatRequest timeout, in milliseconds.
accessTokenstringBearer token override.
apiKeystringAPI key override.
username / passwordstringBasic auth override.
retryConfigarrayRetry settings override.

Timeouts and retries

To set a global timeout, do the following:

1$sdk = new Client(
2 accessToken: 'your-token',
3 timeout: 10000, // 10 seconds in milliseconds (default: 10000)
4);

To configure retries, pass a retryConfig array to the constructor:

1$sdk = new Client(
2 accessToken: 'your-token',
3 retryConfig: [
4 'isEnabled' => true,
5 'maxRetries' => 3,
6 'baseDelayMs' => 150, // initial delay in milliseconds (default: 150)
7 'maxDelayMs' => 5000, // max delay cap in milliseconds (default: 5000)
8 'delayJitter' => 50, // random jitter in milliseconds (default: 50)
9 'delayMultiplier' => 2.0, // exponential backoff multiplier (default: 2.0)
10 'retryableStatuses' => [408, 429, 500, 502, 503, 504],
11 'retryableMethods' => ['GET', 'PUT'],
12 ],
13);

To turn off retries entirely:

1$sdk = new Client(
2 accessToken: 'your-token',
3 retryConfig: ['isEnabled' => false],
4);

Optional and nullable field handling

The SDK uses PHP’s native nullable type syntax (?Type) to represent optional and nullable fields. Optional fields default to null in model constructors.

1use YourSdk\Models\Pet;
2
3// Required fields must be provided; optional fields default to null
4$pet = new Pet(
5 id: 123,
6 name: 'Fido',
7 tag: 'dog', // optional field — omit to leave as null
8);
9
10// Optional fields omitted entirely
11$minimalPet = new Pet(
12 id: 456,
13 name: 'Whiskers',
14 // tag is null — omitted from the JSON payload sent to the API
15);

PHP 8.1 native backed enums are used for fields with a fixed set of allowed values:

1use YourSdk\Models\StatusEnum;
2
3// Create using the enum case
4$pet = new Pet(id: 1, name: 'Rex', status: StatusEnum::Available);
5
6// Enums are deserialized automatically from API responses
7$pet = $sdk->pets->getPetById(1);
8echo $pet->status->value; // "available"

Additional resources

Consider the following resources for using and customizing your PHP SDK:

  • SDK documentation — Check the docs/ directory in your SDK for per-service and per-model reference pages.
  • Example usage — Refer to the example/ directory for a working script demonstrating basic SDK usage.
  • Dependencies — The SDK uses the following dependencies: