PHP SDK
The official PHP package for interacting with the Container API.
The recommended way to interact with the Container API in PHP connectors is the official SDK. It wraps the HTTP endpoints into typed interfaces: ContainerApiInterface, plus ContainerApiStream for whole-file streams.
Installation
composer require productsupcom/container-api-clientThe package is hosted on GitHub. Add the repository to your composer.json if you haven't already:
"repositories": [
{ "type": "vcs", "url": "https://github.com/productsupcom/container-api-client" }
]Setup with Symfony
Wire the Container API client using factory classes and Symfony's DI container.
Factory classes — create these to instantiate the Container API client:
<?php
namespace App\ContainerApi;
use GuzzleHttp\Client as HttpClient;
use Productsup\CDE\ContainerApi\BaseClient\Client;
class ContainerApiClientFactory
{
public static function create(): Client
{
return Client::create(new HttpClient(['base_uri' => 'http://cde-container-api']));
}
}<?php
namespace App\ContainerApi;
use Productsup\CDE\ContainerApi\BaseClient\Client;
use Productsup\CDE\ContainerApi\ContainerApi;
class ContainerApiFactory
{
public static function create(Client $client): ContainerApi
{
return new ContainerApi($client);
}
}Service definitions — register the factories in a config file:
services:
container.api.client:
class: Productsup\CDE\ContainerApi\BaseClient\Client
factory: ['App\ContainerApi\ContainerApiClientFactory', 'create']
container.api:
class: Productsup\CDE\ContainerApi\ContainerApi
factory: ['App\ContainerApi\ContainerApiFactory', 'create']
arguments:
- '@container.api.client'DI binding — bind the interface so it can be injected anywhere:
services:
_defaults:
autowire: true
autoconfigure: true
bind:
Productsup\CDE\ContainerApi\ContainerApiInterface $containerApi: '@container.api'Now you can inject ContainerApiInterface into any service:
public function __construct(
private ContainerApiInterface $containerApi,
) {}Key methods
Writing output (data source connectors)
| Method | Description |
|---|---|
appendToOutputFile(array $item) | Write a single product |
appendManyToOutputFile(array $items) | Write a batch of products (auto-chunks large batches) |
streamToFile('output', \Generator $items) | Write all products from a generator in one request (see Whole-file streams) |
Reading input (export connectors)
| Method | Description |
|---|---|
yieldFromInputFile() | Iterate all products one by one |
yieldBatchFromInputFile(int $size) | Iterate products in batches |
countItemsFromInputFile() | Get total item count |
streamFromFile('input', array $queryParameters = []) | Iterate all products from a single request (see Whole-file streams) |
Reading delta input (export-delta connectors)
| Method | Description |
|---|---|
yieldFromNewFile() | Products added since last run |
yieldFromModifiedFile() | Products changed since last run |
yieldFromUnchangedFile() | Products with no changes |
yieldFromDeletedFile() | Products removed since last run |
Batch and count variants are also available: yieldBatchFromNewFile(int $size), countItemsFromNewFile(), etc.
To read one of these files in one request, call streamFromFile() with new, modified, unchanged, or deleted. See Whole-file streams.
Category specific attributes
The new, modified, and unchanged yield methods accept an optional array $options as their last argument. Pass ['classification-id' => $id] to filter by a CSA classification:
$this->containerApi->yieldFromNewFile(['classification-id' => $classification->id()]);
$this->containerApi->yieldBatchFromNewFile(100, ['classification-id' => $classification->id()]);yieldFromDeletedFile(), yieldBatchFromDeletedFile(), and streamFromFile('deleted', …) reject classification-id with 404 Not Found. The deleted stream is channel-wide — read it once, without the option.
Use listClassifications() to retrieve all classifications configured for the current channel:
| Method | Description |
|---|---|
listClassifications() | Return all Classification objects for the current channel. Each exposes id() and path(). |
Writing feedback (export connectors)
| Method | Description |
|---|---|
appendToFeedbackFile(array $item) | Write a single feedback entry |
appendManyToFeedbackFile(array $items) | Write a batch of feedback entries |
streamToFile('feedback', \Generator $items) | Write all feedback entries from a generator in one request (see Whole-file streams) |
Logging
| Method | Description |
|---|---|
info(string $message) | Log an info message |
warning(string $message) | Log a warning |
error(string $message) | Log an error |
debug(string $message) | Log a debug message |
Metadata
| Method | Description |
|---|---|
showHeaders(string $type) | Get column names of an input file |
countItemsFromInputFile() | Get item count |
Whole-file streams
streamFromFile() reads a whole file in one request, and streamToFile() writes a whole file in one request. Both need SDK 1.5.0+ and are declared on Productsup\CDE\ContainerApi\ContainerApiStream, which ContainerApi implements alongside ContainerApiInterface.
| Method | Files |
|---|---|
streamFromFile(string $file, array $queryParameters = []): \Generator | input, new, modified, unchanged, deleted |
streamToFile(string $file, \Generator $items): void | output, feedback |
Set up the streaming client
Guzzle downloads a whole response body before it returns, so without the GuzzleLazyFileStream middleware, streamFromFile() yields its first item only after the whole file has arrived. With the middleware, Guzzle sends that request through PHP's stream wrapper instead of cURL, and streamFromFile() yields items as they arrive. Add a second client with the middleware for the services that stream files, and keep container.api for everything else.
<?php
namespace App\ContainerApi;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\HandlerStack;
use Productsup\CDE\ContainerApi\BaseClient\Client;
use Productsup\CDE\ContainerApi\Stream\GuzzleLazyFileStream;
class StreamingContainerApiClientFactory
{
public static function create(): Client
{
$handlerStack = HandlerStack::create();
$handlerStack->push(GuzzleLazyFileStream::middleware());
return Client::create(new HttpClient([
'base_uri' => 'http://cde-container-api',
'handler' => $handlerStack,
'timeout' => 3600,
'connect_timeout' => 3,
]));
}
}Register it next to container.api:
services:
container.api.stream.client:
class: Productsup\CDE\ContainerApi\BaseClient\Client
factory: ['App\ContainerApi\StreamingContainerApiClientFactory', 'create']
container.api.stream:
class: Productsup\CDE\ContainerApi\ContainerApi
factory: ['App\ContainerApi\ContainerApiFactory', 'create']
arguments:
- '@container.api.stream.client'In each service that streams files, type the dependency ContainerApiInterface&ContainerApiStream:
<?php
namespace App\Service;
use Productsup\CDE\ContainerApi\ContainerApiInterface;
use Productsup\CDE\ContainerApi\ContainerApiStream;
readonly class ProductStreamService
{
public function __construct(
private ContainerApiInterface&ContainerApiStream $containerApi,
) {}
}The bind in config/services.yaml matches only parameters typed ContainerApiInterface, so wire container.api.stream into the service as an explicit argument:
services:
App\Service\ProductStreamService:
arguments:
$containerApi: '@container.api.stream'Timeouts and requirements
For streamFromFile(), the Container API sends the response headers only after it has downloaded the input file and run the first query. timeout bounds that wait. Without it, PHP's default_socket_timeout does (60 seconds unless configured).
Under cURL, the same timeout limits the whole transfer of every other request, streamToFile() included. streamToFile() keeps its one request open for as long as the generator yields, so size timeout for your longest write.
- The middleware needs
allow_url_fopen, which PHP enables by default. With it off, the middleware has no effect and Guzzle buffers the whole file. streamToFile()needsext-curl. Without it, Guzzle reads the whole request body into memory before it sends it.
Read a file
foreach ($this->containerApi->streamFromFile('input') as $product) {
// process $product
}The optional second argument takes query parameters, for example streamFromFile('input', ['show-hidden' => true]):
| Parameter | Type | Description |
|---|---|---|
show-hidden | bool | Adds the columns whose names start with ___ |
classification-id | int | Classification ID, for the CSA export-delta files new, modified, and unchanged |
The client rejects values of other types.
Write a file
$this->containerApi->streamToFile('output', (static function (): \Generator {
yield ['id' => '1', 'name' => 'Product A', 'price' => '9.99'];
yield ['id' => '2', 'name' => 'Product B', 'price' => '19.99'];
})());A generator that yields nothing sends no request.
Read, process, and write in one loop
$this->containerApi->streamToFile('output', (function (): \Generator {
foreach ($this->containerApi->streamFromFile('input') as $product) {
$product['processed_at'] = \date('c');
yield $product;
}
})());The write request sends each product as the generator yields it, and the streaming client reads the input as it arrives. The connector starts on the first product and never holds the whole file.
Complete streaming service
The complete ProductStreamService reads the input with streamFromFile(), adds processed_at to each product, and writes the result with streamToFile(). After the write succeeds, it logs how many products it processed. Wire it with container.api.stream as in Set up the streaming client, and call run() from your connector's CLI command.
<?php
namespace App\Service;
use Productsup\CDE\ContainerApi\ContainerApiInterface;
use Productsup\CDE\ContainerApi\ContainerApiStream;
readonly class ProductStreamService
{
public function __construct(
private ContainerApiInterface&ContainerApiStream $containerApi,
) {}
public function run(): void
{
$products = $this->processedProducts();
$this->containerApi->streamToFile('output', $products);
$this->containerApi->info('Processed ' . $products->getReturn() . ' products.');
}
private function processedProducts(): \Generator
{
$productCount = 0;
foreach ($this->containerApi->streamFromFile('input') as $product) {
$product['processed_at'] = \date('c');
yield $product;
$productCount++;
}
return $productCount;
}
}streamFromFile() and streamToFile() come from ContainerApiStream, and info() from ContainerApiInterface, which is why the dependency is typed with both. streamToFile() runs the generator to its end before it returns, so getReturn() holds the count, and a rejected write throws before anything is logged.
Set processed_at by key rather than spreading the product into a new array: spreading renumbers integer keys, so a numeric column name such as 2024 would come out as 0.
Errors
The exception classes are in the Productsup\CDE\ContainerApi\Exception namespace.
| Exception | Thrown by | When |
|---|---|---|
FileNotFoundException | streamFromFile() | The file is not provided for this connector: the Container API answered 404 Not Found. |
FileStreamRejected | streamFromFile(), streamToFile() | The Container API answered with a 4xx or 5xx status: it refused a read before the first item, or rejected a write. status() returns the status and serverMessage() the reason. |
FileStreamTruncated | streamFromFile(), streamToFile() | The stream stopped early: it ended before its end frame, the transfer failed or timed out, or the Container API rejected a write mid-upload. |
FileStreamFailed | streamFromFile() | The Container API failed while sending the file. serverMessage() returns its message. |
FileStreamCorrupted | streamFromFile() | The response does not follow the stream format. |
The four FileStream* exceptions extend ApiFailureException.
Items written before a write is rejected stay in the file, so let a rejected write fail the run: log the rejection and rethrow it.
use Productsup\CDE\ContainerApi\Exception\FileStreamRejected;
$products = (static function (): \Generator {
yield ['id' => '1', 'name' => 'Product A', 'price' => '9.99'];
})();
try {
$this->containerApi->streamToFile('output', $products);
} catch (FileStreamRejected $rejection) {
$this->containerApi->error(\sprintf('The Container API rejected the stream (%d): %s', $rejection->status(), $rejection->serverMessage()));
throw $rejection;
}Upload files to the transport server
The transport server, transport.productsup.io, is the Productsup file server that serves files at public links. A connector of any type can upload a file there when a channel or another system needs to fetch it by URL, for example a product catalog that a marketing platform imports from a link. uploadToTransport() and listOnTransport() are declared on ContainerApiInterface and need SDK 1.4.0+.
Upload a file to the transport server
To upload a file to the transport server, write it into the exchange folder, /data/productsup/exchange, then call uploadToTransport() with the file's path relative to that folder and the path the file gets on the transport server:
use Productsup\CDE\ContainerApi\Exception\UploadToTransportFailed;
// Example names: replace the file name and the transport path with your own.
$fileName = 'example-catalog.csv';
\file_put_contents('/data/productsup/exchange/' . $fileName, $catalogCsv);
try {
$response = $this->containerApi->uploadToTransport($fileName, 'example-folder/example-catalog.csv');
} catch (UploadToTransportFailed $exception) {
$this->containerApi->error(\sprintf('Uploading %s to the transport server failed (%d).', $fileName, $exception->getCode()));
throw $exception;
}
$link = $response->getData()?->getPath();The first argument of uploadToTransport() is the file's path relative to the exchange folder, such as example-catalog.csv, not its absolute path. The Container API shares the exchange folder with your connector and reads the file from there, so it does not find a file saved anywhere else, such as /tmp.
The second argument is the file's path on the transport server. It may contain only letters, digits, and the characters - _ . / ? = & @ : ,. It must not end with / or contain a .. segment. Build it from fixed names: a path built from a feed name with a space or an accented letter is rejected.
A missing file or a rejected transport path fails the upload with UploadToTransportFailed, and its getCode() returns 400. That exception is in the Productsup\CDE\ContainerApi\Exception namespace and does not extend ApiFailureException, so catch it by name.
Links to files on the transport server
uploadToTransport() returns a response whose getData()->getPath() is the uploaded file's public link on the transport server, in this shape:
https://transport.productsup.io/<site folder>/channel/<channel ID>/<transport path><site folder>is a 20-character folder name derived from your site's ID.channel/<channel ID>appears only when the run belongs to an export channel, as export and export delta runs do.<transport path>is the second argument passed touploadToTransport(), without a leading slash.
getData()->getKey() returns the same location without the host. Container API versions before 1.19.0 return no link, and getData() is then null. The link is public: anyone who has it can download the file without logging in, so share it only with the system that needs the file. Productsup removes files older than 12 months from the transport server; see Transport Server Data Retention Policy.
List files on the transport server
listOnTransport() returns the files in your site's folder on the transport server. Each entry is an array with the file's key, its location without the host, and its path, the public link. Called without arguments, it returns every file in the site folder, across all of its channels.
To list only one channel's files, pass the channel's ID as site_channel_id:
// Example ID: replace it with the ID of the channel whose files you need.
$channelId = 123;
$files = $this->containerApi->listOnTransport(['site_channel_id' => (string) $channelId]);
$links = \array_column($files, 'path');The filter matches the whole channel ID, so 123 does not return the files of channel 1234. It also leaves out files outside the channel folders, such as those uploaded by a run without a channel. For a channel without files, listOnTransport() returns an empty array. A site_channel_id of 0 sets no filter and returns the files of every channel.
Pass the ID as a string. The SDK rejects an integer before it sends the request. The Container API rejects a negative ID and a string that is not an integer, such as abc, with 400. In all of these cases, and whenever the Container API answers with an error status, listOnTransport() throws ApiFailureException.
Keeping up to date
Keep the SDK updated to get the latest methods and bug fixes:
composer update productsupcom/container-api-clientFrom SDK 1.5.0, appendToOutputFile(), appendManyToOutputFile(), appendToFeedbackFile(), and appendManyToFeedbackFile() throw ApiFailureException when the Container API rejects a write; its getCode() returns the HTTP status. Earlier versions ignore the rejection, and the run finishes without those items.
How is this guide?