gpibarra / n8n-sdk-php
Framework-agnostic PHP SDK for the n8n public REST API (v1), built on Saloon.
Requires
- php: ^8.5
- saloonphp/saloon: ^4.5
Requires (Dev)
- laravel/pint: ^1.0
- pestphp/pest: ^5.0
- phpstan/phpstan: ^2.1
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Framework-agnostic PHP SDK for the n8n public REST API v1, built on Saloon v4.
- Every one of the 168 operations of n8n's own OpenAPI spec (taken from n8n 2.43.8) has a request class and a named resource method; a test parses the vendored spec and fails if any operation is missing (see OpenAPI source).
- Core entities come back as readonly DTOs (
Workflow,WorkflowVersion,Execution,Credential,Tag,Variable,User,Project,Folder,DataTable,DataTableColumn,DataTableRow), each keeping the untouched payload in$raw; the admin and enterprise endpoints return decoded arrays. - Cursor-paginated listings return
CursorPage<T>(data,nextCursor), and the main ones have alazy*()generator that walks every page on demand. - Errors are typed by status: authentication, forbidden, not found, validation and conflict.
Installation
composer require gpibarra/n8n-sdk-php
Requires PHP 8.5+. No framework dependency.
Quick start
use GPIbarra\N8nSdk\N8nConnector; $n8n = new N8nConnector('http://n8n:5678', 'your-api-key'); foreach ($n8n->workflows()->lazy(active: true) as $workflow) { echo $workflow->id, ' ', $workflow->name, PHP_EOL; } $workflow = $n8n->workflows()->create('Hello', nodes: [ [ 'name' => 'Manual trigger', 'type' => 'n8n-nodes-base.manualTrigger', 'typeVersion' => 1, 'position' => [0, 0], 'parameters' => [], ], ], settings: ['executionOrder' => 'v1']); $tag = $n8n->tags()->create('production'); $n8n->workflows()->setTags($workflow->id, [$tag->id]); $n8n->workflows()->publish($workflow->id); $failed = $n8n->executions()->list(status: 'error', workflowId: $workflow->id, limit: 20); foreach ($failed->data as $execution) { $n8n->executions()->retry($execution->id); }
Connector
new N8nConnector(string $baseUrl, string $apiKey). $baseUrl is the installation root (http://n8n:5678); the connector appends /api/v1 (a URL that already ends in /api/v1 is accepted as is). The key is sent in the X-N8N-API-KEY header; create one under Settings → n8n API in the editor. Its scopes, and the instance's license, decide which endpoints answer instead of returning 403.
Being a Saloon connector, it supports everything Saloon offers: withMockClient() for tests, middleware, retries, and sending request objects directly with $n8n->send(new SomeRequest(...)).
Conventions
- Common fields are explicit parameters; null optional arguments are not sent. Write methods with many optional fields take an
array $extra = [](or anarray $attributes) for the rest; explicit parameters win over$extraon key conflicts. - Booleans in the query string are sent as the literal
true/falsestrings n8n's validators expect. - Filters and field selections that n8n reads as JSON strings (
filter,select) accept a PHP array and are JSON-encoded for you; an already encoded string is passed through. - Empty JSON objects stay objects on the wire:
connections,settingsand rowdataare sent as{}when empty, and an optional body left empty is sent as{}rather than[]. - Path parameters are URL-encoded, so community package names such as
@scope/n8n-nodes-xand role slugs such asproject:editorare safe. - DTO mappers are tolerant: n8n omits keys depending on the endpoint and on flags such as
includeRoleorincludeData, so missing keys become null,'',falseor[]instead of errors. - Methods for endpoints that n8n marks as deprecated (
activate,deactivateand the short/workflows/{id}/{versionId}route) are kept and marked@deprecated.
Pagination
Cursor-paginated endpoints take limit (n8n default 100, maximum 250) and cursor, and return GPIbarra\N8nSdk\Data\CursorPage<T>:
$page = $n8n->executions()->list(limit: 100); while (true) { foreach ($page->data as $execution) { // ... } if (! $page->hasMore()) { break; } $page = $n8n->executions()->list(limit: 100, cursor: $page->nextCursor); } // Or let the generator request the next page only when it is needed: foreach ($n8n->executions()->lazy(status: 'success') as $execution) { // ... }
The lazy*() helpers exist for workflows, workflow history, executions, credentials, tags, variables, users, projects, project members, data tables and data table rows. Any other cursor listing can be walked with GPIbarra\N8nSdk\Support\Paginator::lazy(fn (?string $cursor) => ...). Folders are the exception: they paginate with skip / take and return a FolderList (count, data).
Resource index
| Accessor | Methods |
|---|---|
workflows() |
list(?bool $active, array|string|null $tags, ?string $name, ?string $projectId, ?bool $excludePinnedData, ?int $limit, ?string $cursor, array $query): CursorPage<Workflow>, lazy(...), get(string $id, ?bool $excludePinnedData): Workflow, create(string $name, array $nodes, array $connections, array $settings, ?string $projectId, array $extra): Workflow, update(string $id, Workflow|array $workflow, ?bool $publishIfActive): Workflow, delete(string $id): Workflow, publish(string $id, ?string $versionId, ?string $name, ?string $description): Workflow, unpublish, activate (deprecated), deactivate (deprecated), archive, unarchive, transfer(string $id, string $destinationProjectId): void, tags(string $id): list<Tag>, setTags(string $id, list<string> $tagIds): list<Tag>, history(string $id, ?int $limit, ?string $cursor): CursorPage<WorkflowVersion>, lazyHistory, version(string $id, string $versionId): WorkflowVersion, versionByPath (deprecated) |
executions() |
list(?string $status, ?string $workflowId, ?string $projectId, ?bool $includeData, ?string $startedAfter, ?string $startedBefore, ?int $limit, ?string $cursor, array $query): CursorPage<Execution>, lazy(...), get(string $id, ?bool $includeData, array $query): Execution, delete(string $id): Execution, retry(string $id, ?bool $loadWorkflow): Execution, stop(string $id): array, stopMany(list<string> $statuses, ?string $workflowId, ?string $startedAfter, ?string $startedBefore): int, tags(string $id): list<Tag>, setTags(string $id, list<string> $tagIds): list<Tag> |
credentials() |
list(?int $limit, ?string $cursor): CursorPage<Credential>, lazy, get(string $id): Credential, create(string $name, string $type, array $data, ?string $projectId, ?string $description, array $extra): Credential, update(string $id, array $attributes): Credential, delete(string $id): Credential, schema(string $credentialTypeName): array, transfer(string $id, string $destinationProjectId): void, test(string $id): array |
tags() |
list(?int $limit, ?string $cursor): CursorPage<Tag>, lazy, get(string $id): Tag, create(string $name): Tag, update(string $id, string $name): Tag, delete(string $id): Tag |
variables() |
list(?string $projectId, ?string $state, ?int $limit, ?string $cursor): CursorPage<Variable>, lazy, create(string $key, string $value, ?string $projectId): void, update(string $id, string $key, string $value, ?string $projectId): void, delete(string $id): void |
users() |
list(?bool $includeRole, ?string $projectId, ?int $limit, ?string $cursor): CursorPage<User>, lazy, get(string $idOrEmail, ?bool $includeRole): User, create(list<array{email, role?}> $users): list<array>, delete(string $idOrEmail, ?string $transferId): void, changeRole(string $idOrEmail, string $newRoleName): void |
projects() |
list(?int $limit, ?string $cursor): CursorPage<Project>, lazy, create(string $name, array $extra): Project, update(string $id, string $name): void, delete(string $id): void, users(string $id, ?int $limit, ?string $cursor): CursorPage<User>, lazyUsers, addUsers(string $id, list<array{userId, role}> $relations): void, changeUserRole(string $id, string $userId, string $role): void, removeUser(string $id, string $userId): void |
folders() |
list(string $projectId, array|string|null $filter, array|string|null $select, ?string $sortBy, ?int $skip, ?int $take): FolderList, get(string $projectId, string $folderId): Folder, create(string $projectId, string $name, ?string $parentFolderId): Folder, update(string $projectId, string $folderId, array $attributes): Folder, delete(string $projectId, string $folderId, ?string $transferToFolderId): void |
dataTables() |
list(array|string|null $filter, ?string $sortBy, ?int $limit, ?string $cursor): CursorPage<DataTable>, lazy, get, create(string $name, list<array{name, type}> $columns, ?string $projectId, array $extra): DataTable, update(string $id, string $name): DataTable, delete, columns(string $id): list<DataTableColumn>, addColumn(string $id, string $name, string $type, ?int $index): DataTableColumn, updateColumn(string $id, string $columnId, array $attributes), deleteColumn, rows(string $id, array|string|null $filter, ?string $sortBy, ?string $search, ?int $limit, ?string $cursor): CursorPage<DataTableRow>, lazyRows, insertRows(string $id, list<array> $rows, ?string $returnType): int|list<DataTableRow>, upsertRow(string $id, array $filter, array $data, ?bool $returnData, ?bool $dryRun): bool|list<DataTableRow>, updateRows(...), deleteRows(string $id, array|string $filter, ?bool $returnData, ?bool $dryRun), clearRows(string $id): int |
sourceControl() |
status(string $direction): list<array>, pull(?bool $force, ?string $autoPublish): list<array>, push(string $commitMessage, list<array{id, type}> $fileNames, ?bool $force): list<array> |
audit() |
generate(?array $categories, ?int $daysAbandonedWorkflow): array |
discover() |
get(?string $include, ?string $resource, ?string $operation): array |
insights() |
summary(?string $startDate, ?string $endDate, ?string $projectId): array |
communityPackages() |
list(): list<array>, install(string $name, ?string $version): array, update(string $name, ?string $version): array, uninstall(string $name): void |
n8nPackages() (beta) |
export(array $options): ExportedPackage, import(mixed $package, string $workflowConflictPolicy, array $fields, string $filename): array, importSelection(mixed $package, string $selectedProjectId, list<string> $selectedWorkflowIds, array $fields, string $filename): array |
evaluation() |
testRuns(string $workflowId, ?string $status, ?int $limit, ?string $cursor): CursorPage<array>, createTestRun(string $workflowId): array, testRun(string $workflowId, string $runId): array, testCases(string $workflowId, string $runId, ...): CursorPage<array>, cancelTestRun(string $workflowId, string $runId): array |
logStreaming() |
list(): list<array>, create(array $destination): array, get(string $id): array, update(string $id, array $destination): array, delete(string $id): array, test(string $id): bool, eventTypes(): list<string> |
ldap() |
get(): array, update(array $configuration): array, syncs(?int $limit, ?string $cursor): CursorPage<array>, sync(string $type = 'dry'): array |
otel() |
get(): array, update(array $settings): array, testTrace(array $settings): array |
ssoOidc(), ssoSaml() |
get(): array, update(array $configuration): array |
securityPolicy() |
get(): array, update(array $policy): array |
roles() |
list(?bool $withUsageCount): array, create(string $displayName, string $roleType, list<string> $scopes, ?string $description): array, get(string $slug, ?bool $withUsageCount): array, update(string $slug, string $displayName, list<string> $scopes, ?string $description): array, delete(string $slug, ?string $reassignRoleSlug): array |
roleMappingRules() |
list(?string $type, ?int $limit, ?string $cursor): CursorPage<array>, create(string $expression, string $role, string $type, ?int $order, ?array $projectIds): array, update(string $id, array $attributes): array, delete(string $id): array, move(string $id, int $targetIndex): array |
credentialTypePolicies(), nodeTypePolicies() |
instancePolicy(): array, replaceInstancePolicy(array $rules, string $defaultAction, int $version): array, projectPolicy(string $projectId): array, replaceProjectPolicy(string $projectId, array $rules, string $defaultAction, int $version): array, documents(?int $limit, ?string $cursor): CursorPage<array>, createDocument(array $rules): array, document(string $policyId): array, updateDocument(string $policyId, array $rules, int $version): array, deleteDocument(string $policyId): void, replaceAttachments(string $scopeId, array $attachments): array |
promotions() |
providers, createProvider(string $name, array $auth, string $type = 'git'), provider, updateProvider, deleteProvider, connections(?string $scope, ?string $providerId, ...), createConnection(string $name, string $scope, string $providerId, array $target, ?array $configs), connection, updateConnection, deleteConnection, upsertApplyConfig(string $id, array $settings, ?string $name), upsertPromoteConfig, deleteConfig(string $id, string $direction), cloneCheckout(string $id, string $direction), disconnectCheckout, connectionProjects(string $id): list<string>, addProject(string $id, string $projectId), removeProject, promote(string $id, string $commitMessage, ?bool $force), apply(string $id, ?array $expectedSource), continueApply(string $id, array $expectedSource), changes(string $projectId, string $direction, ?string $search, ?string $sort, ?string $order), promoteProject(string $projectId, list<string> $workflowIds, ?string $commitMessage), applyProject(string $projectId, list<string> $workflowIds, ?array $expectedSource), continueApplyProject(...) |
Examples
// Edit a workflow in place: update() also accepts the fetched DTO and sends only its writable fields $workflow = $n8n->workflows()->get('VzqKEW0ShTXA5vPj'); $settings = ['timezone' => 'Europe/Madrid'] + $workflow->settings; $n8n->workflows()->update($workflow->id, ['settings' => $settings] + $workflow->toPayload(), publishIfActive: false); // Credentials: look up a type's fields, then create one $schema = $n8n->credentials()->schema('githubApi'); $credential = $n8n->credentials()->create('GitHub bot', 'githubApi', ['accessToken' => '...'], projectId: 'VmwOO9HeTEj20kxM'); // Projects, members and folders $project = $n8n->projects()->create('Marketing', ['description' => 'Campaign automations']); $n8n->projects()->addUsers($project->id, [['userId' => $userId, 'role' => 'project:editor']]); $folder = $n8n->folders()->create($project->id, 'Campaigns'); $tree = $n8n->folders()->list($project->id, filter: ['parentFolderId' => $folder->id], select: ['id', 'name', 'path']); // Data tables $table = $n8n->dataTables()->create('orders', [['name' => 'status', 'type' => 'string'], ['name' => 'amount', 'type' => 'number']]); $n8n->dataTables()->insertRows($table->id, [['status' => 'new', 'amount' => 10]]); $filter = ['type' => 'and', 'filters' => [['columnName' => 'status', 'condition' => 'eq', 'value' => 'new']]]; foreach ($n8n->dataTables()->lazyRows($table->id, $filter) as $row) { echo $row->id, ' ', $row->values['amount'], PHP_EOL; } $preview = $n8n->dataTables()->updateRows($table->id, $filter, ['status' => 'paid'], dryRun: true); // Move a project between instances as an n8n package $export = $source->n8nPackages()->export(['projectIds' => ['VmwOO9HeTEj20kxM']]); file_put_contents($export->filename ?? 'export.n8np', $export->contents); $result = $target->n8nPackages()->import($export->contents, 'new-version', ['projectId' => 'Ab12Cd34Ef56Gh78']);
Error handling
Every non-2xx response throws GPIbarra\N8nSdk\Exceptions\N8nException (a Saloon RequestException, so getResponse(), getStatus() and getPendingRequest() are available), or one of its subclasses:
| Exception | Status |
|---|---|
AuthenticationException |
401 (missing, wrong or expired API key) |
ForbiddenException |
403 (missing scope or role, or an unlicensed feature); extends AuthenticationException |
NotFoundException |
404 |
ValidationException |
400, 422 |
ConflictException |
409 (duplicate name, ID in use, stale policy version) |
N8nException |
anything else |
n8n renders errors as {"message": "...", "code"?: "...", "description"?: "..."}:
use GPIbarra\N8nSdk\Exceptions\ConflictException; use GPIbarra\N8nSdk\Exceptions\N8nException; use GPIbarra\N8nSdk\Exceptions\ValidationException; try { $n8n->tags()->create('production'); } catch (ConflictException $e) { // the tag already exists } catch (ValidationException $e) { $e->getErrorMessage(); // "request/body must have required property 'name'" } catch (N8nException $e) { $e->getStatus(); $e->getErrorCode(); $e->getDescription(); $e->getBody(); // decoded error body }
A successful response whose body does not have the expected shape throws UnexpectedResponseException.
Spec notes
The vendored spec is followed as written. These are the defects and oddities found in it, and how the SDK deals with them:
- Ten operations have no
operationId, only n8n's internalx-eov-operation-id: the six log streaming destination endpoints, the three n8n package endpoints andGET /workflows/{id}/{versionId}. The latter reuses the internal IDgetWorkflowVersionofGET /workflows/{workflowId}/versions/{workflowVersionId}. GET /workflows/{id}/{versionId}(deprecated) overlaps the other two-segment routes:GET /workflows/{workflowId}/tags,/historyand/test-runsalso match its template. The SDK keeps it asversionByPath(); useversion()instead.DELETE /executions/{executionId}documentsidas a number, while every other execution response renders it as a string.Execution::$idis normalised to a string.- No error response documents a body, although the spec defines an
errorschema (code,message,description); the exceptions read that shape. POST /n8n-packages/importsays in its description that the defaultworkflowIdPolicyisnew, while the field's schema declares the defaultsource. The SDK sends neither unless you pass one.- The
nodeschema types a node'scustomTelemetryTagsas an object with atagarray, while workflow settings typecustomTelemetryTagsas a plain array of{key, value}pairs. activateWorkflowhas the same summary aspublishWorkflow("Publish a workflow"); it is the deprecated alias of publish.GET /workflowsdocuments bothoffsetandcursorpagination parameters; only the cursor is an argument (offsetcan go through$query).- The LDAP configuration types its numeric fields as
integerin the request andnumberin the response. - Several components are declared twice with different casing (
Error/error,Workflow/workflow,Tag/tag,NotFound/notFound, ...), the capitalised ones being plain$refaliases.
OpenAPI source
resources/openapi/n8n-public-api-v1.yml is the spec served by n8n 2.43.8 (dist/public-api/v1/openapi.yml inside the installation; its info.version reads 1.1.1), vendored unmodified. It is reference material only and is excluded from the Composer dist archive. tests/Unit/SpecCoverageTest.php parses it and asserts that each of its 168 operations maps to exactly one request class, that no request class falls outside the spec, and that every request class is reachable from a resource method. After replacing the file with a newer one, the test lists what drifted.
Testing
composer install composer test # Pest composer analyse # PHPStan level 8 composer format:check # Pint
Unit tests use Saloon's MockClient and assert the method, path, query and JSON (or multipart) body of every endpoint plus the DTO mapping; fixtures live in tests/Fixtures and are built from the response schemas of the vendored spec, reusing its property examples.
An optional integration suite (tests/Integration) runs against a real n8n when these variables are set, and is skipped otherwise. It only reads, or creates temporary resources named sdk-it-* and deletes them before finishing; features the license or the key's scopes forbid are skipped:
N8N_TEST_URL=http://localhost:5678 N8N_TEST_API_KEY=... composer test
License
MIT. See LICENSE.