A PHP SDK for the GetStream API.
Install via Composer:
composer require getstream/getstream-phpSee v12 → v13. HTTP JSON is unchanged. getActivity, campaign responses, and the new enum constants changed. Property types stay string.
If you are currently using stream-chat-php, we have a detailed migration guide with side-by-side code examples for common Chat use cases. See the Migration Guide.
Copy .env.example to .env and configure:
cp .env.example .envRequired environment variables:
STREAM_API_KEY=your_api_key_here
STREAM_API_SECRET=your_api_secret_here
STREAM_BASE_URL=https://chat.stream-io-api.com$client = (new GetStream\ClientBuilder())
->apiKey($apiKey)
->apiSecret($apiSecret)
->maxConnsPerHost(100) // default 100 (per-host concurrency cap, see runtime caveats)
->idleTimeout(55) // default 55s (per-connection lifetime cap, see runtime caveats)
->connectTimeout(10) // default 10s
->requestTimeout(30) // default 30s
->build();Per-call timeout override:
$response = $client->getHttpClient()->request(
'GET', $url, $headers, null, ['timeout' => 2]
);Per-call curl overrides replace (do not merge with) the client-level curl options, since Guzzle unions options shallowly. Only ['timeout' => N] is documented for per-call use.
Runtime caveats. maxConnsPerHost and idleTimeout are enforced via libcurl's persistent multi-handle pool (CURLMOPT_MAX_HOST_CONNECTIONS and CURLOPT_MAXLIFETIME_CONN). They take effect only when the SDK client is reused across requests within a single PHP process: long-running runtimes such as Swoole, RoadRunner, ReactPHP, and CLI daemons. Instantiate the SDK client once and reuse it. Under PHP-FPM (and one-shot CLI scripts) the PHP process exits at the end of each request, so there is no cross-request pool to size; the per-call request and connect timeouts still apply. idleTimeout requires libcurl 7.80.0 (Nov 2021) or later; pooling still works without it on older builds, just without active lifetime cycling.
Escape hatch: Passing your own client via ->httpClient($mine) skips all 4 knobs; your client is used as-is.
Auto-retry is off by default: the client makes exactly one attempt and surfaces errors unchanged. Enable it with ->retry(new RetryConfig(...)):
$client = GetStream\ClientBuilder::fromEnv()
->retry(new RetryConfig(enabled: true, maxAttempts: 3, maxBackoff: 30.0))
->build();When enabled, a failed attempt is retried only if all of the following hold: the method is GET or HEAD; the failure is an HTTP 429 (and not marked unrecoverable) or a transport error (StreamTransportException); and fewer than maxAttempts attempts have been made. Writes (POST/PUT/PATCH/DELETE) and any other 4xx/5xx status are never retried.
Backoff honors a parsed Retry-After header when present (capped at maxBackoff, no jitter); otherwise it uses exponential backoff with full jitter, also capped at maxBackoff. On exhaustion, the last attempt's error is thrown unchanged.
Breaking change from earlier versions: this SDK previously retried HTTP 429 responses on every request automatically (maxRetries, default 3). That always-on behavior is gone; retries are now opt-in via RetryConfig and apply only to GET/HEAD.
The SDK emits structured events through a PSR-3 Psr\Log\LoggerInterface. No logger is injected by default (Psr\Log\NullLogger, a no-op); pass your own via ->logger(...):
$client = (new GetStream\ClientBuilder())
->apiKey($apiKey)
->apiSecret($apiSecret)
->logger($myPsr3Logger)
->build();Events emitted:
| Event | Level | When |
|---|---|---|
client.initialized |
INFO | Once, at construction |
http.request.sent |
DEBUG | Before each HTTP attempt |
http.response.received |
DEBUG | After any HTTP response, including 4xx/5xx (status codes are data, not a failure) |
http.request.failed |
ERROR | Transport failure that surfaces to the caller unchanged (connection reset, timeout, DNS failure, TLS handshake failure) — no HTTP response was received |
http.request.failed |
DEBUG | Also emitted, with a retry.attempt field, right before each retry backoff sleep (see Retries) |
The SDK never sets the logger's minimum level; that's the caller's responsibility.
Bodies are not logged by default. Enable with ->logBodies(true); this emits one WARN at construction and adds (key-redacted) http.request.body / http.response.body fields to the DEBUG events. Query values for api_key, api_secret, token and top-level JSON body keys api_secret, token, password are always redacted (case-insensitive for query values), whether or not body logging is on. No headers are ever logged.
$client = (new GetStream\ClientBuilder())
->apiKey($apiKey)
->apiSecret($apiSecret)
->logger($myPsr3Logger)
->logBodies(true)
->build();Generate API methods from OpenAPI spec:
./generate.shRun tests:
# Run all tests
make test
# Run unit tests only
make test-unit
# Run integration tests (requires API credentials)
make test-integrationA test in the integration group talks to a live Stream app and needs credentials. make test-unit excludes that group and needs none; make test-integration runs only that group. Both select by group, so every test lands in exactly one lane.
CI follows the same split:
| When | What runs | Gates |
|---|---|---|
| Pull request | make lint and make test-unit on PHP 8.1 to 8.3 |
yes, 🧪 Tests |
| Daily at 12:00 UTC | make test-integration |
no, a red run opens an issue |
| Release PR merged | nothing on the default branch, the unit lane on N.x |
N.x only |
<?php
require_once 'vendor/autoload.php';
use GetStream\ClientBuilder;
$client = ClientBuilder::fromEnv()->build();
$feed = $client->feed('user', 'john-doe');use GetStream\GeneratedModels\AddActivityRequest;
// Create an activity
$activity = new AddActivityRequest(
actor: 'user:john',
verb: 'post',
object: 'message:123',
text: 'Hello World!'
);
$response = $client->addActivity($activity);
// Access response data directly
$createdActivity = $response->activity;
echo "Activity ID: " . $createdActivity->id;
// Or access HTTP metadata
echo "Status: " . $response->getStatusCode();
echo "Duration: " . $response->duration;Note: When constructing models directly, always use named arguments (e.g.
new Message(text: 'hello')). Positional argument usage is not supported and may break across SDK updates as parameter order is not guaranteed.
Generated models automatically handle JSON parsing and serialization:
// Models parse JSON based on constructor types
$response = $client->addActivity($request);
$activity = $response->activity; // Fully typed objectOverride field names using the JsonKey attribute:
use GetStream\GeneratedModels\JsonKey;
class CustomModel extends BaseModel {
public function __construct(
#[JsonKey('fids')]
public ?array $feedIds = null, // Maps to "fids" instead of "feed_ids"
) {}
}$response = $client->addActivity($request);
// Direct access
$activity = $response->activity;
// HTTP metadata
$statusCode = $response->getStatusCode();
$duration = $response->duration;The client regenerates itself on every chat production release:
- chat attaches its
openapigenerator to the release and publishes the matchingopenapi-vXspec release in protocol. - protocol notifies this repo, and the Regenerate workflow opens one PR from
regen/auto, titledfeat: regenerate client from openapi-vX. ItsBEGIN_COMMIT_OVERRIDEblock lists the changelog lines. - Once the required checks pass and the Regen integration run passes on the PR's head commit, the PR merges itself, and release-please adds those lines to the Release PR. Merging the Release PR ships, as described below.
A regen PR waits for a human when its changelog carries a BREAKING CHANGE: footer, when the Breaking changes check finds an approved breaking change in the new spec, or when a required check fails. For each approved breaking change with wire lines, the regen writes BREAKING CHANGE: footers from the lines chat allowlisted and titles the PR feat!:, so the check passes and the PR only waits for a human to merge it. A ticket chat approved for getstream-go only has no PHP lines, so the check fails until a human names it in the PR body, also on a feat!: PR. Because PHP callers pass arguments by position or by name, the regen also compares the generated methods before and after, and writes a footer for each removed method and each method whose arguments were renamed or moved, even when the spec did not change them. Only getstream-sdk-bot can push to regen/**.
- Regenerate now: run Regenerate from the Actions tab with an
openapi-vXtag, or leave it empty for the latest. Locally,SPEC_TAG=openapi-vX ./generate.shdoes the same with the generator built from a../chatcheckout at that tag. - A breaking change that breaks this SDK: when the regen titled the PR
feat!:, review its footers. It moves on to each newer spec until you rename the PR or edit its body, which keeps it on the spec you judged. Otherwise add!to the PR title, and beforeEND_COMMIT_OVERRIDEadd a blank line andBREAKING CHANGE: <what breaks for customers>. Then merge it yourself in a breaking-change window, with aMIGRATION_vX_to_vY.mdguide. - An approved breaking change that does not break this SDK: label the PR
sdk-not-breakingand name each ticket the check lists in the PR body. When the regen titled itfeat!:, also drop the!and delete the entries that carry aBREAKING CHANGE:footer. The next Regenerate run merges it, daily at 06:23 UTC or when you start one. - Failed integration tests: the tests share their Stream app with other SDKs' CI, so the Regenerate run reruns a red or cancelled Regen integration run once by itself, and merges the PR when the rerun passes. If the rerun is red too, fix the cause or rerun it again; a pass merges the PR. If no run started for the PR's head commit, start Regen integration on
regen/autofrom the Actions tab. - Rewrite a changelog line: edit the
BEGIN_COMMIT_OVERRIDEblock in the merged PR's body, then run the Release workflow to rebuild the Release PR. Keep ticket IDs out of PR titles, because a title becomes a changelog line.
Releases are driven by release-please.
- Merge PRs to
masterwith conventional-commit titles, using Squash and merge. The title becomes the commit subject and decides the next version:feat:is a minor,fix:andperf:are a patch,feat!:or<type>(scope)!:is a major. Other types (chore,ci,docs,test,refactor) ship nothing. Keep the ticket prefix after the type, as infeat: [FEEDS-1350] add feed retention endpoint. - release-please keeps a Release PR open with the version bump in
composer.json,src/Constant.phpandCHANGELOG.md. Never edit those versions by hand; the// x-release-please-versioncomment insrc/Constant.phpis what the updater anchors on. - Its runs are created held at
action_requireduntil someone clicks Approve and run, because release-please opens the PR withGITHUB_TOKEN. The unit lane then reportsskippedand🧪 Testsgoes green without running a test. The skip only applies while the diff is nothing but what release-please writes, down to the version line in each version file, so a code or dependency change pushed onto a Release PR by hand runs the unit lane like any other PR. - Merging the Release PR creates the tag and the GitHub Release on that merge commit and announces the tag to Packagist, with no further test run: the Release PR adds only the version bump and changelog to an already-tested
master. A hotfix release fromN.xruns the unit lane first, since its commits were pushed without a PR. A tag and a GitHub Release cannot be withdrawn.
Packagist reads the tags itself, so the announce step only asks it to look now rather
than on its own schedule. If it fails or the credentials are unset, the release still
lands and Packagist catches up. To prompt it by hand, dispatch Release with
resync_packagist checked; the API takes a repository rather than a tag, so it recrawls
everything it can see.
To force a specific version, type Release-As: X.Y.Z in the commit message box of the
squash dialog when merging a PR; the PR description is not copied there. To hotfix while
master carries unreleased work, branch N.x from the last tag, cherry-pick the fix,
and merge the Release PR that release-please opens against that branch.
# Run all available linting checks
make lint
# Run PHPStan static analysis only
make phpstan
# Fix code style issues (requires php-cs-fixer)
make cs-fix
# Run comprehensive quality checks (lint + tests)
make quality# Run all tests
make test
# Run unit tests only
make test-unit
# Run integration tests
make test-integration