Create loyalty points export
Request a CSV or JSON file of recorded loyalty history for a date range.
- Method
- POST
- Path
https://api.returning.ai / v1/ loyalty-exports - Permission
- customerSuccess
- Retries
- Retry uncertain requests with the same API key, Idempotency-Key and body.
When to use this
- Load daily coin, XP or premium-currency history into your reporting system.
- Extract a historical period across all customers or selected customer identifiers.
Authentication#
- Header
Authorization: Bearer <API_KEY>- Permission
- customerSuccessShown in the dashboard as Customer Success.
Use a Community API key with customerSuccess, shown as Customer Success in the dashboard. Keep the key on your backend and send Authorization: Bearer <API_KEY>. The key selects the community; do not send a community ID. Personal API keys are not supported.
All three calls use https://api.returning.ai and return Cache-Control: no-store. They accept no query parameters. A valid community key with the required permission can read that community's export jobs, including jobs created by another key in the same community.
Successful responses contain meta, message and data. Read job state from data.status. An HTTP 200 means the status request succeeded, even when the job is failed. Errors put their machine-readable code in meta.code; do not branch on message.
Behaviour#
Request export -> save export_id -> poll status -> get download link -> download the file.
This creates a report job and does not change balances. Version 1 remains the default and exports ordinary reward coins. Version 2 adds currency selection, source classification and transaction metadata. It is not a store-orders feed, current-balance snapshot or pre-calculated BI totals.
Start here: a daily export
You need a backend process, a Community API key with Customer Success permission, and somewhere private to store the downloaded file. The examples on this page use synthetic dates and identifiers; choose a completed period that contains your own activity.
| Step | Call | Save or check |
|---|---|---|
| 1. Request the file | POST /v1/loyalty-exports | Save your request body and idempotency key before sending. Save data.export_id from the response. |
| 2. Wait for completion | GET /v1/loyalty-exports/{exportId} | Continue only for queued or processing. Download only after completed. |
| 3. Get a temporary link | GET /v1/loyalty-exports/{exportId}/download | Use data.url promptly. Do not log it. |
| 4. Download and import | HTTPS GET to data.url | Send no API key. Check row count and byte size against status, then import. |
The three API calls need your key. The file download uses the temporary URL instead. There is no webhook, list-jobs or public cancel call in this three-endpoint workflow, so retain the export ID yourself and poll status.
Choose the date window
The filter uses when each history entry was recorded, not when its original trade or activity happened. start_at is included and end_at is excluded. Both must be UTC timestamps ending in Z, with at most three fractional-second digits.
| Reporting day | start_at | end_at |
|---|---|---|
| 1 September in UTC | 2026-09-01T00:00:00.000Z | 2026-09-02T00:00:00.000Z |
| 1 September in a UTC+08:00 business timezone | 2026-08-31T16:00:00.000Z | 2026-09-01T16:00:00.000Z |
For a timezone that observes daylight saving, convert each local midnight separately; a local day can be 23 or 25 hours. The API does not accept a timezone parameter. Run your daily process after the interval closes: an end time in the future is rejected.
Adjacent days share one boundary. A record exactly at 2026-09-02T00:00:00.000Z belongs to the next UTC day, not both. Historical backfills can use wider intervals, but use sequential windows for easier recovery. There is no maximum range duration in the request validator and no promised completion time or unlimited file size.
Copy-and-run CSV example
Download the complete Python example. It requires Python 3.10 or newer and no third-party packages. Supply your API key through your backend's environment or secret manager as RETURNING_API_KEY.
python3 export-loyalty-points.py \
--start '2026-09-01T00:00:00.000Z' \
--end '2026-09-02T00:00:00.000Z' \
--schema-version 2 --currency coins --currency xp --currency premium \
--state export-2026-09-01.state.json \
--out points-2026-09-01.csv
Omit --schema-version and --currency for the unchanged version 1 CSV. With --schema-version 2, omit --currency for coins only. Keep these choices unchanged on resume.
Omit --client-ref to include all customers. To select customers, add --client-ref '000101' --client-ref '000102'. For a single date range, use the same selection on every resume.
The example persists an idempotency key before creation, saves the export ID, polls with backoff, downloads without forwarding the API key, and checks the CSV header, row count and byte size. It streams CSV to a temporary file and replaces the output only after those checks pass. An empty report still produces a valid header-only CSV.
If it times out, rerun the same command with the same state file and API key. The default ten-minute polling budget is a client choice, not an API guarantee. --max-wait 1200 changes that budget. If a request is accepted but the response is lost, the saved key lets the next run recover the original job.
Use one process per state file and serialize exports for each community. Keep state and CSV files private. Use a distinct state file for each deliberately new report; deleting state or changing API keys after an uncertain request can create a different job. The example is a starting point for a backend process, not a scheduler or warehouse importer. It replaces the chosen output file after verification, so choose an export-specific output path.
Manual status and download calls
After the create request shown below returns an export ID, use it in both follow-up URLs:
curl --fail-with-body \
'https://api.returning.ai/v1/loyalty-exports/66f000000000000000000701' \
--header 'Authorization: Bearer <API_KEY>'
Wait until data.status is completed, then request the link:
curl --fail-with-body \
'https://api.returning.ai/v1/loyalty-exports/66f000000000000000000701/download' \
--header 'Authorization: Bearer <API_KEY>'
curl --fail --output points.csv '<TEMPORARY_DOWNLOAD_URL>'
Replace the synthetic export ID with your returned ID and the final URL with data.url. Copy the full URL, including its query string, and keep it quoted. The last command has no Authorization header.
Request#
Headers#
RuleBearer <API_KEY>
Rule1-128 characters; first ASCII letter, digit, _ or -; remaining characters may also include . and :
Eg9b629318-5c67-4799-8135-27a64f1fc529
Ruleapplication/json
Body#
The body must be JSON and at most 1 MiB. Unknown body fields are rejected. An empty client_refs array is invalid; it does not mean all customers.
Choose the file version
The endpoint path stays /v1/loyalty-exports for both file versions. Send schema_version: 2 for version 2. Omit it for version 1; schema_version: 1 is not accepted. Version 1 keeps its existing columns and excludes XP and premium currency.
For version 2, currencies accepts one to three unique values: coins, xp, premium. Omit it for coins only. An empty array, duplicate values, unsupported values, or currencies without schema_version: 2 returns 400 VALIDATION_ERROR.
To select customers and request a version 2 JSON file containing all three currencies, use:
{
"dataset": "points_transactions",
"format": "json",
"schema_version": 2,
"currencies": ["coins", "xp", "premium"],
"start_at": "2026-09-01T00:00:00.000Z",
"end_at": "2026-09-02T00:00:00.000Z",
"client_refs": ["000101", "000102"]
}
References use your community's active customer identifier. Do not assume this is the Returning.AI user ID. Text identifiers preserve case, spaces and leading zeroes. Numeric identifiers use canonical numeric text: 000101 does not match a numeric identifier stored as 101.
Selection is resolved during processing. An unknown or ambiguous selected identifier fails the job rather than returning a partial selection. Without a selection, unresolved identifiers can appear as null in JSON or blank in CSV. Identifier values are resolved when the report runs, not as they were at the historical event time.
Rulepoints_transactions
Rulecsv or json
Eg"csv"
RuleOptional; only 2 is accepted
Eg2
Rule1-3 unique values; requires schema_version 2; empty or duplicate values are rejected
Eg["coins", "xp", "premium"]
RuleAt most three fractional-second digits
Eg"2026-09-01T00:00:00.000Z"
RuleNo maximum range duration
Eg"2026-09-02T00:00:00.000Z"
Rule1-1,000 unique nonblank strings, each at most 1,024 characters; no control characters
curl --request POST \
--url https://api.returning.ai/v1/loyalty-exports \
--header 'Authorization: Bearer <API_KEY>' \
--header 'Idempotency-Key: 9b629318-5c67-4799-8135-27a64f1fc529' \
--header 'Content-Type: application/json' \
--data '{
"dataset": "points_transactions",
"format": "csv",
"schema_version": 2,
"currencies": ["coins", "xp", "premium"],
"start_at": "2026-09-01T00:00:00.000Z",
"end_at": "2026-09-02T00:00:00.000Z"
}'
Response#
New jobs return 202. An exact replay returns 200 with the original job's current state. Save data.export_id; acceptance does not mean the file is ready. There is no success meta.code or returned polling interval.
Version 2 CSV columns
CSV is UTF-8 with these 12 columns in this order. Null values are blank cells. Import identifiers and amounts as text, then parse amounts with a decimal-aware reader.
| Column | Meaning |
|---|---|
client_ref | Your configured customer identifier; blank if unresolved. Preserves text identifiers such as leading zeroes. |
event_id | Stable identifier for this recorded event and currency. Treat it as opaque and use it for upserts across overlapping exports. |
recorded_at_utc | UTC recording timestamp used by the date filter, not the original trade or activity time. |
currency | coins, xp or premium, restricted to your request's selection. |
operation | increase, decrease, overwrite, expiry or unknown; see the interpretation rules below. |
amount | Signed stored numeric amount as text, or blank if invalid. An overwrite's amount is the assigned balance. |
channel | Recorded source category from the channel table below. It does not certify the business reason. |
label | Recorded name for a bulk update, integration, booster, milestone, store item or leaderboard; blank when unavailable. Free text, not a stable category or ID. |
source_type | Type of source reference supported by this row, or blank. See the source table below. |
source_id | Reference for source_type, or blank. Not a guaranteed trade or order ID. |
quality_notes | Row-specific notes separated by semicolons, in the order listed below; blank when none apply. |
metadata | JSON object encoded in a CSV cell, or blank when absent. Parse the CSV first, then parse this cell as JSON. |
Rows are newest first by recording time with stable tie ordering. Ordinary zero-movement rows are excluded, but overwrites to zero are kept. A single recorded award carrying both coin and premium amounts can produce two rows with different event IDs; XP has its own event IDs. Coin event IDs are compatible with version 1. Do not deduplicate different currencies by source_id.
Text cells beginning with a spreadsheet formula marker after optional whitespace are prefixed with an apostrophe for spreadsheet safety. Signed amount cells are exempt. JSON retains the original text, so prefer JSON when exact text matching matters.
Version 2 JSON fields
JSON is one array of objects, not JSONL. It includes all 12 CSV fields: client_ref, label, source_type and source_id are strings or null; amount is a string or null; event_id, recorded_at_utc, currency, operation and channel are strings. quality_notes is an array of strings, and metadata is an object of string values or null. JSON includes these additional fields:
| JSON field | Type | Meaning |
|---|---|---|
schema_version | integer | Always 2. |
community_id | string | Community selected by the API key. |
returning_user_id | string | Returning.AI user ID; distinct from your configured client_ref. |
occurred_at_utc | null | Original activity time is not recorded here. Use recorded_at_utc for extraction. |
premium_currency_id | string or null | Recorded premium-currency identifier on premium rows when available; null on other currencies. CSV does not include this identifier. |
absolute_balance | string or null | Assigned balance for an overwrite, equal to amount; otherwise null. |
raw_action | string | JSON-encoded recorded action data, not a nested JSON array. |
source_reference | string or null | Original correlation reference. It can differ from the normalized source_id and is not a guaranteed trade or order ID. |
A nonempty metadata value looks like {"business_line_id":"line-001"} after parsing. The export does not return a manifest or checksum through these three endpoints.
Channels and labels
Classification uses the recorded action structure, not words in the label. A label containing "trade" does not establish a trade category. Missing, malformed or unrecognized actions become other.
channel | Recorded origin |
|---|---|
api | Direct API award or adjustment. |
admin_or_unattributed | Adjustment without a more specific recognized origin. |
booster | Booster reward. |
bulk_update | User bulk update, including rewards written by a data workflow's Users Bulk Update step. |
daily_visit | Visit reward. |
expiry | Coin expiry. |
integration | Connected data integration award. |
leaderboard | Leaderboard award. |
milestone | Milestone stage or group reward. |
mini_game | Spin result, raffle ticket purchase/refund, or match prediction entry/payout/refund. |
other | Missing, malformed or unrecognized origin. |
referral | Referral or referral-condition reward. |
social | Social reward. |
store | Reward redemption or product refund; not an order record. |
streak | Visit-streak reward. |
tier | Level or tier change. |
workflow | Direct workflow action marked as such, distinct from a Users Bulk Update award. |
label is copied as recorded, including spaces, for the supported origins listed in the CSV table. It is null or blank for other origins, including direct workflow actions. Labels can change and are not evidence of a trade ID.
Source references
source_type | Meaning of source_id |
|---|---|
milestone_stage | Milestone stage identifier. |
milestone_group | Milestone group identifier. |
spin_result | Spin result reference. |
raffle | Raffle reference for a ticket purchase or refund. |
match_prediction | Match prediction reference for an entry, payout or refund. |
coin_expiry_policy | Coin-expiry policy reference. |
booster | Booster reference. |
leaderboard | Leaderboard reference. |
history_group | Correlation reference on a bulk-update award; may link coin, XP and premium rows written together. It is not a business transaction ID. |
Source fields are populated only when the recorded action and reference support the mapping. Milestone references are normalized to the stage/group ID; premium reference suffixes are removed. Store rows deliberately leave both source fields empty even if JSON has a source_reference. A missing reference leaves source fields empty. A milestone reference that remains nonempty after normalization but cannot be parsed also adds source_unparsed.
Transaction metadata
metadata contains the transaction metadata columns configured on a data workflow's Users Bulk Update step and saved on that award. For example, map a feed's business line ID column to business_line_id to carry it alongside a trade reward. Metadata does not determine channel and does not turn a reward into a verified trade record.
Keys are configured names; values are strings with surrounding whitespace removed. Blank input cells do not create keys. Metadata keys are sorted in the exported object. Missing or empty metadata is null in JSON and blank in CSV, including older awards without saved metadata or awards whose selected cells were all blank. The export reads saved values; it does not look up missing values in your current feed or fill historical gaps.
Interpreting points correctly
operation | How to read amount |
|---|---|
increase | Positive recorded movement. Keep the sign. |
decrease | Negative recorded movement. Keep the sign. |
overwrite | Assigned absolute balance, not points earned or a delta. An overwrite to zero is retained. |
expiry | Recorded expiry, distinct from an ordinary decrease; review any unexpected positive sign. |
unknown | Invalid or missing amount, represented as null in JSON or blank in CSV. Keep for review. |
The operation decoder also recognizes zero, but those ordinary zero rows are excluded from the file. Overwrite detection takes precedence over the amount's sign. For example, an overwrite from 100 to 40 exports amount: "40"; its -60 effect cannot be calculated without a trustworthy prior balance. JSON also has absolute_balance: "40".
Amounts use ordinary numeric precision and may use scientific notation. Text does not certify arbitrary-precision accounting. Premium deductions marked requested_amount_may_exceed_applied can describe the requested deduction rather than the applied wallet change. Keep overwrites, invalid values and these deductions out of a simple earned-points total.
Quality notes
The first eight notes below can appear in both formats. CSV joins them with ; in this order and omits the three background notes shown as JSON only. JSON retains the full array.
| Quality note | Meaning |
|---|---|
requested_amount_may_exceed_applied | A premium bulk deduction may record more than the wallet actually lost because the applied balance is floored at zero. |
dual_amount_document | One recorded event carries both coin and premium amounts. Present even when your currency selection exports only one side. |
absolute_overwrite_not_an_earn | Assigned balance; exclude from a simple earned-points sum. |
points_amount_invalid | Amount is unknown, not zero. An overwrite can still be classified as an overwrite while its amount is null. |
expiry_sign_unexpected | Expiry has a positive amount; review before aggregating. |
client_ref_unresolved | No configured customer identifier could be resolved for this row. |
source_unparsed | A recorded milestone reference could not be parsed into its supported source fields. |
reversal | Recorded action marks a reversal. Preserve its signed amount and do not count it as another earn. |
original_event_time_not_recorded | JSON only, on every row. Original activity time is unavailable. |
business_reason_not_verified | JSON only, on every row. Channel classification does not verify the business reason. |
legacy_number_precision_unverified | JSON only, when the amount was recorded as an ordinary numeric value; precision is not certified. |
Retain unrecognized quality notes instead of rejecting the whole file.
Version 1 compatibility
Omitting schema_version keeps the unchanged version 1 coin-only export. Its CSV still has five columns: client_ref, event_id, recorded_at_utc, operation, points_delta. points_delta is the stored signed amount as text, or blank when invalid; for overwrites it is the assigned balance.
Version 1 JSON includes those five fields plus schema_version (1), community_id, returning_user_id, occurred_at_utc (null), currency_type (reward), absolute_balance (overwrite only, otherwise null), raw_action (JSON-encoded text), source_reference (string or null) and quality_notes (array). It has no version 2 channel, label, typed source or metadata fields. Version 2 uses amount instead of points_delta and currency instead of currency_type; update your importer before opting in.
Reconcile one feed
- Configure a stable business line ID as transaction metadata on your feed's Users Bulk Update step before awards are written. Retain the feed's customer identifier, expected currency and expected amount.
- Request version 2 for a closed recording-time window with the currencies that feed awards. Download after completion and check
total_rowsandfile_size_bytes. - Parse the CSV, then its nonblank
metadatacells, or read JSON directly. Selectchannel: bulk_updateand your configured metadata key. Useclient_refand the business line ID to match your feed. Keep missing metadata in a separate unmatched set. - Upsert exported rows by
event_id. Compare signedamountby business line and currency, keeping reversals signed and handling overwrites and quality notes separately.source_idcan correlate sibling awards but does not replace your business line ID. Use JSON if you also needpremium_currency_id. - Investigate unmatched and qualified rows before declaring reconciliation complete. Re-export overlapping windows deliberately for late recordings, with new idempotency keys, and upsert again. The export does not certify applied balances or financial completeness.
Daily loads
Request consecutive UTC recording-time windows. Use event_id to avoid duplicate rows when intentionally repeating or overlapping windows. A new request rereads history; an idempotent replay returns the same job.
The export is not a transactional snapshot or a guaranteed change feed. Late records and historical edits can make a fresh export differ. Deleted historical events are not supplied as deletion records. coverage: observed_history_only means recorded history, not certified financial completeness. The export does not reconstruct every historical balance.
For current balance summaries, use Get loyalty overview. For order details and fulfilment state, use List redemption orders by community.
Make a daily import reliable
- Choose the closed recording-time window and persist the request body, API key identity, idempotency key and eventual export ID in your own job record.
- Run only one active export for the community. On an uncertain create response, retry exactly; do not advance to the next window.
- After completion, download the file promptly, check its row count and byte size, and store it privately. A byte-size check detects an incomplete transfer; the API does not supply a cryptographic checksum.
- Upsert by
event_idin your reporting store. Preserveclient_refas text, retain null/unknown values and quality notes, and handle overwrite rows separately. - Advance your own import checkpoint only after the entire file has been imported successfully. If an import partially fails, reuse the saved file or download it again while available, and repeat the upsert.
- If your business needs reconciliation, deliberately re-export overlapping closed windows with new idempotency keys and deduplicate by
event_id. Choose the overlap from your own source delays; the API does not promise a maximum lateness interval or a deletion feed.
This avoids checking each event against your database before requesting the API: the date filter selects the period and your import's upsert handles replayed rows. It does not add date filtering to the separate store-orders API.
Common questions
| Question | Answer |
|---|---|
| Can I request yesterday only? | Yes. Send yesterday's UTC recording-time boundaries, or convert the boundaries of your business timezone to UTC. |
| Does it return one row per customer with their balance? | No. It returns recorded history events for the requested version and currencies. Use Get loyalty overview for current balance summaries. |
| Does it return store orders or ready-made BI totals? | No. Use the order endpoints for orders and aggregate the exported history in your reporting system with the interpretation rules above. |
| Can I export all customers without paging? | Yes. Omit client_refs; one job creates one file for the matching history. These endpoints have no page or cursor parameter. |
| Why is a successful file empty? | No included history matched the requested interval and selection. Current balances alone do not imply activity in that interval. |
| Does retrying refresh old data? | An idempotent replay returns the original job. Use a new key for a deliberately fresh extraction. |
| Can I recover a lost export ID? | Retry the original body with the original key and API key. This family has no list-jobs endpoint, so save the ID yourself. |
| Can I use the file after its link expires? | If the file is still available, get a new link. After the 24-hour file window expires, request a new export. |
Eg{ ... }
Rulesuccess
Eg200
Eg"example-request"
Eg"Loyalty export accepted success."
Eg{ ... }
Eg"66f000000000000000000701"
Rulequeued, processing, completed, failed, cancelled or expired
Eg"queued"
Rulepoints_transactions
Rulecsv or json
Eg"csv"
Eg"2026-09-03T01:00:00.000Z"
Ruleobserved_history_only
{
"meta": {
"status": "success",
"statusCode": 200,
"requestId": "example-request"
},
"message": "Loyalty export accepted success.",
"data": {
"export_id": "66f000000000000000000701",
"status": "queued",
"dataset": "points_transactions",
"format": "csv",
"created_at": "2026-09-03T01:00:00.000Z",
"coverage": "observed_history_only"
}
}
Errors#
Fix the request13
VALIDATION_ERRORFix the requestAUTHENTICATION_REQUIREDFix the requestAPI_KEY_PERMISSION_DENIEDFix the requestCOMMUNITY_ACCESS_DENIEDFix the requestINVALID_JSONFix the requestIDEMPOTENCY_CONFLICTFix the requestREQUEST_TOO_LARGEFix the requestUNSUPPORTED_MEDIA_TYPEFix the requestFix the data02
COMMUNITY_NOT_FOUNDFix the dataRetry with backoff05
EXPORTS_UNAVAILABLERetry with backoffAUTHENTICATION_FAILEDRetry with backoffEXPORT_IN_PROGRESSRetry with backoffRetries
Idempotency is scoped to the community, API key ID and Idempotency-Key. Use the same API key, header and body after a timeout or uncertain response. Switching API keys does not replay the original request.
Dates are normalized to UTC millisecond strings and selected identifiers are sorted before comparison. Reordering the same selection is a replay. In version 2, currency order is also normalized: ["coins", "xp"] and ["xp", "coins"] replay the same request. Duplicate currencies are rejected before comparison. Omitting currencies and explicitly sending ["coins"] are different requests even though both export coins; do not add or remove the field on a retry. Changing the currency set or adding schema_version: 2 to a version 1 request is also a different request. Reusing a key with different input returns 409 IDEMPOTENCY_CONFLICT. Omitted selection and an explicit selection are different requests.
A replay returns the original job; it does not restart it, refresh its file or extend retention. There is no documented minimum idempotency-retention guarantee. Use a new key only for an intentional new extraction.
Only one export may be active per community. 429 EXPORT_IN_PROGRESS includes Retry-After: 30. Wait at least that long before retrying. If a known job remains queued for an unusually long time, contact support with its export ID and request ID. Changing the date range or creating new idempotency keys will not unblock it.
{
"meta": {
"status": "error",
"statusCode": 400,
"code": "VALIDATION_ERROR",
"requestId": "req_example"
},
"message": "Loyalty export request error.",
"detail": "Invalid request or unsupported query parameters."
}