Skip to content

Match the SDK to the Siren API as it is served today - #4

Merged
alexstandiford merged 9 commits into
mainfrom
fix/api-sync-2026-10-19
Oct 19, 2026
Merged

alexstandiford merged 9 commits into
mainfrom
fix/api-sync-2026-10-19

Conversation

@alexstandiford

@alexstandiford alexstandiford commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What changed

The SDK was checked call by call against Siren's origin/main (fd24e0962, 2026-10-18). Five existing calls did not match what the API sends or accepts, and some of them never did. This PR fixes them, brings openapi.yaml and the README in line, adds the API key scopes Siren Cloud shipped in 3.6.259 and 3.6.260 (Novatorius/siren#494 and #495), and prepares the 0.2.0 release.

API keys read the ledger and manage webhooks. Siren Cloud 3.6.259 gives keys six new scopes, and 3.6.260 lets the manage scope send a test delivery.

  • A new siren.ApiKeyScope enum mirrors the PHP SDK's class: ALL_EVENTS, FULL_ACCESS, SALE, REFUND, SITE_VISITED, LEDGER_CONVERSIONS_READ, LEDGER_TRANSACTIONS_READ, LEDGER_OBLIGATIONS_READ, LEDGER_PAYOUTS_READ, WEBHOOK_SUBSCRIPTIONS_READ and WEBHOOK_SUBSCRIPTIONS_MANAGE. siren.LEDGER_READ_SCOPES and siren.event_scope(slug) sit beside it. api_keys.create takes members or strings.
  • The reconciliation readers and webhooks.subscriptions work with a key that holds the matching scope, and the README, docstrings and spec say so. api_keys stays session-only.
  • New error subclasses follow the status hierarchy: ApiKeyNotAcceptedError (401 api_key_not_accepted, subclasses AuthenticationError), MissingScopeError (403 missing_scope, with scope and any_of) and StoreKeyNotAllowedError (403 store_key_not_allowed, with property_id), both subclassing PermissionError. siren.ErrorCode holds the three codes.
  • The readers take property_id, sent as propertyId, to narrow an organization-wide ledger read to one store.
  • openapi.yaml puts the ledger and webhook operations on the apiKey scheme beside the session scheme, with the scopes each one needs, adds the propertyId and X-Siren-Property parameters, lists the new error codes, and adds POST /webhooks/{id}/test on the apiKey scheme with webhook-subscriptions:manage. It passes openapi-spec-validator.

Release 0.2.0. The last commit dates the changelog as ## [0.2.0] - 2026-10-19 under a fresh empty Unreleased, and sets 0.2.0 in pyproject.toml, src/siren/_version.py (which the User-Agent reads) and openapi.yaml. test_version now expects 0.2.0. The changelog links use v tags, so tag it v0.2.0.

Reconciliation readers returned no rows. conversions, transactions, obligations and payouts sent page and perPage. Siren pages with number and offset (PageSizeMiddleware) and ignores the others. Siren also answers these lists with {items, total, page, perPage, totalPages} (ListResponseWrapperInterceptor), and the SDK only read bare arrays. The readers now turn page and per_page into number and offset, cap the page at 200, and read the list body. ListPage gains total_pages.

construct_event parsed real deliveries as empty. It read type, data and deliveryId from the body. Siren's WebhookDeliveryService sends a plain subscription the payload alone, with the type in X-Siren-Event and the event id in X-Siren-Delivery. construct_event now takes event_type and delivery_id from those headers. It also unwraps the versioned envelope a connected site's subscription gets. The envelope check looks for version, because currency.created's payload has a type key of its own.

Error details were always empty. Siren's REST layer sends {"error": {"message", "code"?, "context"}}, and a failed field check is a 400 with context.failedValidations. The SDK only read error.data. It now falls back to context, takes context.type as the code when there is no code, and exposes the messages on BadRequestError.field_errors.

api_keys.create without scopes always failed. Siren answers 400 "At least one scope is required." scopes is now required, and the docstring names the scopes Siren accepts.

Field names. ApiKey and WebhookSubscription read createdAt, but Siren sends dateCreated. Both now read dateCreated and gain property_id. ApiKey also gains revoked_at. api_keys.list and webhooks.subscriptions.list take number and offset, because Siren returns at most 200 rows a request and an org can hold 250 keys.

Two additions follow API changes from October. EventResult now carries http_status, body, status and queued. Siren answers a sale and a site visit with what came of them, and answers 202 with status: queued while an org's processing is paused. When there is no X-Siren-OID header, opportunity_id comes from the body's opportunityId, as the Node SDK does. api_keys.create also takes expires_at and property_id, which Siren accepts. WebhookEventType gains the seven events in Siren's GET /webhooks/events catalog that it lacked: collaborator.updated, collaborator.deactivated, program.created, credit.issued, credit.redeemed, currency.created and currency.deleted.

Tests changed on purpose

Four existing tests encoded behavior Siren does not have, so they were rewritten with comments that name the Siren code they follow. They covered page/perPage on the wire, bare-array list bodies, a {type, data, deliveryId} delivery body, and creating a key with no scopes. The event-type count tests now match Siren's catalog. New tests cover each fix and the new scopes. pytest passes 119 tests.

Related

The PHP SDK fixes the same webhook parsing and ingestion body in Novatorius/siren-php#8, and the Node SDK in Novatorius/siren-node#6. The shapes, scope names and error classes here match both, so the three SDKs stay the same.

🤖 Generated with Claude Code

The reconciliation readers sent page and perPage, which Siren never reads,
and parsed only bare arrays, while Siren answers these lists with
{items, total, page, perPage, totalPages}. Every call returned no rows. The
readers now send number and offset, cap the page at 200, and read the list
body.

construct_event looked for type, data and deliveryId in the body. A plain
subscription's body is the payload alone, with the type in X-Siren-Event and
the event id in X-Siren-Delivery. construct_event now takes both headers and
also unwraps the versioned envelope a connected site's subscription gets.

Errors now read error.context when there is no error.data, so a failed field
check (a 400 from Siren) exposes its messages on BadRequestError.field_errors.

api_keys.create requires scopes, because Siren refuses a key without them
and issues event scopes only. Records read dateCreated, the name Siren uses.
The two management lists take number and offset. EventResult exposes the
outcome body and the queued 202. WebhookEventType gains the seven events in
Siren's catalog that it lacked. openapi.yaml and the README describe the same
behavior, including that API keys only reach the event routes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T12:16:18.249895Z 0e04336 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

The Node SDK reads opportunityId from the ingestion body when the response
carries no X-Siren-OID header, and lets api_keys.create send expiresAt and
propertyId, which Siren's CreateApiKey accepts. This keeps the two SDKs the
same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0e043361e6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread openapi.yaml
LineItem:
type: object
required: [name, quantity, amount]
required: [amount]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Allow sale line items without a name

The updated schema now correctly documents amount as the only required line-item field, but Events.sale() still routes every item through _normalize_line_item(), which treats both name and amount as required and reads item["name"]. Consequently, a server-valid and newly documented call such as items=[{"amount": 10}] raises ValueError locally instead of reaching Siren; update the normalizer to make name optional as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_normalize_line_item now requires only amount and sends name and external_id when they are given, with a test for items=[{"amount": 10}] (4a7b59f).

Comment thread src/siren/webhooks.py Outdated
Comment on lines +222 to +225
return (
"version" in payload
and isinstance(payload.get("type"), str)
and isinstance(payload.get("data"), dict)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid mistaking ordinary versioned payloads for envelopes

For a plain subscription whose event payload contains the common version/type/data shape (for example, a custom event payload), this predicate classifies the payload as a connected-site envelope. construct_event() then replaces the header event type with the payload's own type, unwraps only data, and drops the rest of the payload. Presence of any version key is not a sufficient discriminator; validate the connected-site envelope's additional required fields or otherwise distinguish its delivery format before unwrapping.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A body is now read as an envelope only when its id equals the delivery_id and its type equals the event_type, which is how Siren builds every envelope, or when neither is passed. Any other delivery keeps its whole body and the header type, and new tests cover a custom payload shaped like {version, type, data} (ed7f74b).

Comment thread openapi.yaml Outdated
Comment on lines +450 to +452
externalId:
type: string
description: Your order/transaction id; used to match refunds later.
description: Your order/transaction id; used to match refunds later. A number is accepted too.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Represent numeric sale external IDs in the schema

The new description says that externalId may be a number, but its schema remains type: string. OpenAPI validators and generated clients will therefore reject numeric IDs even though this revision explicitly documents them as accepted by Siren; express the field as a string-or-number union so the machine-readable contract matches the stated API behavior.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

externalId is now typed [string, number] on the sale and refund schemas, and a line item takes a number for externalId and name, in all three SDK specs (e3d3001).

Comment thread src/siren/api_keys.py Outdated
def create(
self, *, label: str, scopes: Optional[Sequence[str]] = None
) -> ApiKey:
def create(self, *, label: str, scopes: Sequence[str]) -> ApiKey:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Permit API-key creation without a label

The revised ApiKeyCreate contract makes only scopes required, but the SDK method still requires the keyword-only label argument and always sends it. When callers want to use the API's valid unlabeled-key form, Python raises TypeError before making the request. Make label optional and omit it from the payload when absent so this SDK surface matches the updated API contract.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

label is now an optional keyword and is left out of the request when not given, with a test for that case (4a7b59f).

alexstandiford and others added 7 commits October 19, 2026 08:39
Siren puts a 400's broken rules in error.context.failedValidations as a
list, one {field, message, type, context} entry per rule. PHPNomad's
ValidationMiddleware merges each field's failures into that list, and
Siren's SaveCollaboratorTrackingAlias builds the same shape by hand.
BadRequestError.field_errors looked for an object keyed by field, so it
returned an empty dict for every real validation failure. Its test
pinned the object shape Siren never sends.

field_errors now returns the list of entries, as BadRequestError's
fieldErrors does in the Node SDK, and the test uses Siren's shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A subscription made through POST /webhooks receives the event payload
alone, and Siren names the event only in the X-Siren-Event header. The
construct_event() call from 0.1.0, which passes no headers, turned every
such delivery into an event with an empty type, which no handler matched
and nothing reported. construct_event() now raises
SignatureVerificationError when a bare payload comes without event_type,
so an unchanged caller fails loudly and Siren retries the delivery. The
versioned envelope still needs no headers.

The CHANGELOG lists the changes that break 0.1.0 callers and names 0.2.0
as the next release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A connected site's subscription receives an envelope, but Siren sends it
with the same X-Siren-Event and X-Siren-Delivery headers as an ordinary
delivery. construct_event knew the envelope by a version key beside type
and data, so a custom event's payload with those keys had its type
replace the header's and lost everything outside data.

Siren writes the delivery id into the envelope's id and the event type
into its type. construct_event now reads a body as an envelope only when
both match the event_type and delivery_id it was given, or when it was
given neither. This is the rule the PHP and Node SDKs use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SaleEventFactory requires only amount on a line item, but the SDK raised
ValueError for a line item without name. It now sends name and
external_id when they are given. A sale's and a refund's external_id may
be a number, which Siren stores as text.

Siren's CreateApiKey reads label as optional. api_keys.create took it as
a required keyword. It is now optional and left out of the request when
not given.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The spec applied the API key scheme to every route, so generated clients
sent an API key to the webhook, API key and reconciliation routes, which
answer 401 to one. It now defines dashboardSession and connectorToken
beside apiKey and sets security on each operation. The event routes and
the new GET /ping take an API key. The API key and webhook routes take a
dashboard session only. The reconciliation routes take a dashboard
session or a connected site's token. The PHP and Node specs match.

externalId takes a string or a number in every schema, and a line item's
name does too. The page size schemas drop maximum: 200, because Siren
lowers a larger size to 200 rather than refusing it. The webhooks tag
says how an envelope is told apart from a plain payload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Siren Cloud 3.6.259 gives API keys six new scopes. The ledger scopes open
the conversion, transaction, obligation and payout reads, and the webhook
scopes open webhook subscription management. Since 3.6.260 the manage scope
also sends a test delivery. ApiKeyScope names the scopes, mirroring the PHP
SDK, and the docstrings, README and openapi.yaml say which key each call
takes. The key management routes stay session-only.

Siren's new refusals get their own errors: ApiKeyNotAcceptedError for
api_key_not_accepted, MissingScopeError with scope and any_of, and
StoreKeyNotAllowedError for store_key_not_allowed. The reconciliation
readers take property_id to narrow an organization-wide read to one store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Dates the unreleased changelog as 0.2.0 and sets the version in
pyproject.toml, _version.py (which the User-Agent reads) and the OpenAPI
file, so the release tag matches what the SDK reports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alexstandiford
alexstandiford merged commit 5df87db into main Oct 19, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant