Skip to content

PHP SDK

shoofai/shoofai wraps the REST API for PHP 8.1 and later, over the curl extension, with no other dependencies.

Terminal window
composer require shoofai/shoofai

It has two clients:

  • ShoofAI\ShoofClient, for searching, with a search key (shf_pub_…) or a secured key.
  • ShoofAI\ShoofAdminClient, for indexing and settings, with an admin key (shf_adm_…).

Request fields keep the API’s own names, such as hitsPerPage and filters, so the API reference applies as written. Responses are the API’s JSON, as associative arrays.

use ShoofAI\ShoofClient;
$client = new ShoofClient('my-store', 'shf_pub_…');
$res = $client->search('running shoes', [
'lang' => 'en',
'filters' => ['brand' => ['Nike', 'Asics'], 'price' => ['lte' => 150]],
'facets' => ['brand', 'categories', 'price'],
'hitsPerPage' => 24,
]);
foreach ($res['hits'] as $hit) {
echo $hit['title'], "\n";
}

When you search for a visitor from your server, see Searching from your server for the key and headers to use. Pass extra headers in the headers option.

The third argument of either client is an array of options:

Option Default Does
host https://api.shoofai.com The API host.
userToken a random anon-… ID The visitor’s ID, sent with searches and events.
timeout 10 Seconds to wait for a response. Streaming answers have none. The admin client’s default is 120.
maxRetries 2 How many times to retry. See Retries.
headers Extra headers on every request.
send curl Your own HTTP function, for tests or proxies.
Method Returns API
search($q, $params) array Search
multiSearch($requests) list of arrays Multi-search
autocomplete($q, ['lang', 'hits', 'filters', 'analytics']) array Autocomplete
searchFacetValues($field, $params) array Search facet values
answer($q, $params, $onDelta) ['text', 'sources', 'mode', 'queryId', 'query'] Answer
answerStream($q, $params, $onEvent) Answer
related($id, ['lang', 'limit']) list Related items
trending(['limit', 'lang', 'type', 'filters']) list Trending items
trendingQueries(['limit', 'lang']) list Trending queries
boughtTogether($id, ['limit', 'lang']) list Bought together
config() array Config
sendEvents($events, $idempotencyKey) Events
$result = $client->answer('what is your return policy?', ['lang' => 'en'], function (string $text) {
echo $text;
flush();
});
echo $result['mode'];

answerStream() calls you with each event (sources, delta, done, error) and its data as it arrives, if you’d rather handle them yourself.

use ShoofAI\ShoofAdminClient;
$admin = new ShoofAdminClient('my-store', getenv('SHOOF_ADMIN_KEY'));
$result = $admin->upsertAll($records, [
'onProgress' => fn (int $done, int $total) => print("$done/$total\n"),
]);
echo $result['indexed'];
Method Does
batch(['upserts', 'deletes', 'reindexId'], $refresh) Upserts up to 500 and deletes up to 1,000 records. Records
upsertAll($records, ['reindexId', 'batchSize', 'onProgress']) Sends any number of records in batches.
getRecord($id) / deleteRecord($id) Reads or deletes one record.
clear() Deletes every record.
startReindex(['copy', 'restart']) / reindexStatus() / commitReindex($id) / cancelReindex() A full resync.
status() Record counts, embeddings and any resync.
getSettings() / setSettings($s) / patchSettings($s) Read, replace or update settings.
applyPreset('store' or 'blog', $ifUnchanged) Sets the facets for a kind of site.
fieldCoverage() How many records have each field.
getSynonyms() / setSynonyms($list) Read or replace synonyms.
getRules() / setRules($list) Read or replace rules.

A full resync:

$reindexId = $admin->startReindex()['reindexId'];
$admin->upsertAll($allRecords, ['reindexId' => $reindexId]);
$admin->commitReindex($reindexId); // removes the records that weren't re-sent

Both clients retry a failed request up to maxRetries times, waiting longer each time. A 429 is retried after its Retry-After, if that’s a minute or less. A 502, 503, 504 or a request that got no response is retried for reads, and for writes that carry an idempotency key. sendEvents() and the admin client’s batch(), clear(), startReindex(), commitReindex() and applyPreset() send a new key with each call. Pass your own as their last argument to make a write safe to repeat across processes.

use ShoofAI\ShoofApiError;
use ShoofAI\ShoofConnectionError;
try {
$client->search('shoes', ['hitsPerPage' => 500]);
} catch (ShoofApiError $e) {
echo $e->status, ' ', $e->errorCode, ' ', $e->getMessage();
// $e->details, and on a 429, $e->retryAfter
} catch (ShoofConnectionError $e) {
echo "The API couldn't be reached";
}

Both implement ShoofAI\ShoofException. See Errors for every code.