# Push notifications API overview

> How a browser or mobile app registers for Releva push notifications: the web SDK setup, the two registration endpoints, authentication with the access token, errors and limits.

There is no public API to create or send a push notification. Notifications are created in the admin under **Marketing Channels › Push Notifications** and sent by campaigns and workflows. The public API only registers the devices that can receive them:

| Endpoint                                | Purpose                                                                                     |
| --------------------------------------- | ------------------------------------------------------------------------------------------- |
| `POST /appPush/tokens`                  | Register a mobile app push token (Android FCM token, or iOS APNs token)                     |
| `POST /pushSubscriptions/{accessToken}` | Register a browser’s Web Push subscription. The JS SDK calls it for you                     |
| `POST /push/{accessToken}`              | The regular SDK call. Its response carries the VAPID public key the browser subscribes with |

Base URL: `https://releva.ai/api/v0`. For what happens after registration, read [How push notifications work](https://releva.ai/documentation/learn/push-notifications/how-push-notifications-work/).

## When to use it

* **Web push with the Releva JS SDK**: you do not call anything. Host the service worker, pass `serviceWorkerUrl` to `Releva.push`, and the SDK registers the subscription. See [Web push setup](https://releva.ai/documentation/reference/push-notifications/overview/#web-push-setup).
* **Mobile apps**: the Releva React Native and Swift SDKs call `POST /appPush/tokens` for you (`client.registerPushToken(...)`). Call it yourself only from a custom app stack.
* **Your own web push opt-in** (own service worker and `pushManager.subscribe`): call `POST /pushSubscriptions/{accessToken}` with the subscription and the VAPID key from the `Releva.push` response.

## Authentication

Both registration endpoints use the shop’s **access token**, the public key your website and apps already use, not the secret key. Find both under **Settings › Shop & Integration**; see [Find your API keys](https://releva.ai/documentation/guides/shop-settings/find-your-api-keys/).

```plaintext
authorization: Bearer $RELEVA_ACCESS_TOKEN
```

For `/pushSubscriptions` the token can instead be the last path segment, which is what the JS SDK does to avoid a CORS pre-flight. If both are sent, the header wins and the path segment is not checked.

Authentication failures answer **`400`**, not `401`:

| Problem                                                      | Message                                                                                                              |
| ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
| No header and no path token                                  | `Authorization header is missing, and accessToken url parameters is also missing. At least one of them is required.` |
| Header is not `Bearer <token>`                               | ``Authorization header is malformed. It should look like `Bearer <string>`.``                                        |
| Token is not a UUID                                          | `The access token you provided is invalid.`                                                                          |
| No shop has this token (including the secret key by mistake) | `Domain with the provided access token cannot be found.`                                                             |

A shop that has been switched off answers `402` with `Domain is disabled. Please reach out to support@releva.ai to enable it.`

## Request format

* HTTPS only.
* Send JSON with `content-type: application/json`. With no body or another content type you get `400 {"message":"The '' field is required."}`.
* `/pushSubscriptions` also accepts `application/x-www-form-urlencoded` with one field, `formPayload`, holding `base64(encodeURIComponent(JSON))`. That is the SDK’s format; without the field: `400 {"message":"formPayload is missing from request body"}`.
* Bodies are limited to 800 KB (JSON).
* Unknown fields are ignored, not rejected.

## Responses

Both endpoints answer **`202 Accepted`** with `{}`. Storage is asynchronous; the device is targetable a few seconds later. Errors have one shape, `{ "message": "..." }`; several validation errors are joined with a space.

| Status | When                                                                                                            |
| ------ | --------------------------------------------------------------------------------------------------------------- |
| `202`  | Accepted and queued                                                                                             |
| `400`  | Authentication failed, validation failed, the body could not be parsed, or the APNs token could not be imported |
| `402`  | The shop is disabled                                                                                            |
| `413`  | Body too large                                                                                                  |
| `500`  | Unexpected error, `{"message":"An internal error occurred."}`. Retry later                                      |

## Limits

* No rate limit on these endpoints.
* Every call writes a **Push Notification Subscribe** event on the profile, even for the same device. A workflow triggered on that event fires on every call, so register once per token change, not on every app start.
* There is no endpoint to remove a token or subscription. Releva deletes it when the push service rejects it at send time.

## Web push setup

1. Copy Releva’s service worker file (`service-worker.js` from the Releva JS SDK) to your site and serve it from the same origin, for example `https://demo-store.example.com/releva-sw.js`. It shows a notification only for payloads with `source: "releva"` and opens the notification’s link on click.

2. Pass its URL to the SDK:

   ```plaintext
   Releva.push(accessToken, context, { serviceWorkerUrl: '/releva-sw.js' });
   ```

3. On each response the SDK reads `push.vapidPublicKey`. If the browser supports service workers and notifications and the permission is not denied, it asks for permission, registers the worker and subscribes with `userVisibleOnly: true`. An existing subscription made with another key is replaced.

4. The SDK posts the subscription to `/pushSubscriptions/{accessToken}` with the device id and the profile from the context.

Without `serviceWorkerUrl` the SDK never asks for permission and no browser can be reached.

## Endpoints

### Register a mobile app push token

`POST /api/v0/appPush/tokens`

| Field               | Type                                | Required    | Notes                                                                                                                               |
| ------------------- | ----------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `profileId`         | string                              | yes         | Your customer id for the profile. `null` is rejected. If the profile does not exist yet, a placeholder profile is created           |
| `deviceId`          | string                              | yes         | Stable id of the app install. One token per profile and device                                                                      |
| `deviceType`        | `android`, `ios`, `huawei`, `other` | no          | Stored as the token’s platform. **Only `android` and `ios` tokens receive pushes**: always send it                                  |
| `pushToken`         | string                              | yes         | FCM registration token, or a raw APNs device token with `tokenType: "apns"`                                                         |
| `tokenType`         | `fcm` (default), `apns`             | no          | `apns`: Releva exchanges the APNs token for an FCM token through the shop’s iOS Firebase project and stores the device as `ios`     |
| `bundleId`          | string                              | with `apns` | The app’s iOS bundle identifier                                                                                                     |
| `notificationStyle` | `data` (default), `notification`    | no          | `notification`: Android draws the push natively from an FCM notification block (used by the Expo adapter). `data`: the SDK draws it |

```plaintext
curl -X POST 'https://releva.ai/api/v0/appPush/tokens' \
  -H "authorization: Bearer $RELEVA_ACCESS_TOKEN" \
  -H 'content-type: application/json' \
  -d '{
    "profileId": "DEMO-CUSTOMER-1001",
    "deviceId": "demo-device-android-0001",
    "deviceType": "android",
    "pushToken": "<FCM registration token>"
  }'
```

iOS with a raw APNs token (Expo):

```plaintext
curl -X POST 'https://releva.ai/api/v0/appPush/tokens' \
  -H "authorization: Bearer $RELEVA_ACCESS_TOKEN" \
  -H 'content-type: application/json' \
  -d '{
    "profileId": "DEMO-CUSTOMER-1001",
    "deviceId": "demo-device-ios-0001",
    "deviceType": "ios",
    "pushToken": "<64-character APNs device token>",
    "tokenType": "apns",
    "bundleId": "com.example.shop"
  }'
```

Response: `202` `{}`.

| Cause                                                | Message                                                                                                                                                                                                                                                                                   |
| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Empty body `{}`                                      | `The 'profileId' field is required. The 'deviceId' field is required. The 'pushToken' field is required.`                                                                                                                                                                                 |
| `profileId: null` (SDK called before `setProfileId`) | `The 'profileId' field is required.`                                                                                                                                                                                                                                                      |
| `deviceType: "web"`                                  | `The 'deviceType' field does not match any of the allowed values.`                                                                                                                                                                                                                        |
| `tokenType: "hms"`                                   | `The 'tokenType' field does not match any of the allowed values.`                                                                                                                                                                                                                         |
| `notificationStyle: "banner"`                        | `The 'notificationStyle' field does not match any of the allowed values.`                                                                                                                                                                                                                 |
| 64-hex APNs token without `tokenType: "apns"`        | `pushToken looks like a raw APNs device token. Send tokenType "apns" with bundleId so it can be exchanged for an FCM registration token.`                                                                                                                                                 |
| `apns` without `bundleId`                            | `bundleId is required when tokenType is apns.`                                                                                                                                                                                                                                            |
| `apns` on a shop without an iOS Firebase account     | `No iOS Firebase account is configured for this domain.`                                                                                                                                                                                                                                  |
| Firebase rejected the APNs token                     | `APNs token could not be imported into FCM. Status: <STATUS>.` where STATUS is `INVALID_ARGUMENT`, `UNAUTHENTICATED`, `PERMISSION_DENIED`, `INTERNAL`, `TOO_MANY_REGISTRATIONS` or `UNKNOWN`. A development build has a sandbox token: set **iOS APNs environment** to **Sandbox** for it |

### Register a browser push subscription

`POST /api/v0/pushSubscriptions/{accessToken}`

Body: `context` and `subscription`.

| Field                                                | Type             | Required | Notes                                                                                   |
| ---------------------------------------------------- | ---------------- | -------- | --------------------------------------------------------------------------------------- |
| `context.deviceId`                                   | string           | no       | The browser device id (the SDK’s `rlv_p` cookie). The subscription is stored per device |
| `context.profile.id`                                 | string           | no       | Your customer id; links the device to that profile                                      |
| `context.profile.email`                              | e-mail           | no       | Upserted onto the profile                                                               |
| `context.profile.phoneNumber`                        | string           | no       | International format with `+` and country code                                          |
| `context.group`                                      | 0 to 9999        | no       | Control-group bucket; default 9999                                                      |
| `subscription`                                       | object           | yes      | The browser’s `PushSubscription.toJSON()`                                               |
| `subscription.endpoint`                              | URL              | yes      |                                                                                         |
| `subscription.expirationTime`                        | string or `null` | no       | A number is rejected, see errors                                                        |
| `subscription.keys.p256dh`, `subscription.keys.auth` | string           | yes      |                                                                                         |

```plaintext
curl -X POST "https://releva.ai/api/v0/pushSubscriptions/$RELEVA_ACCESS_TOKEN" \
  -H 'content-type: application/json' \
  -d '{
    "context": {
      "deviceId": "demo-browser-device-0001",
      "profile": { "id": "DEMO-CUSTOMER-1001", "email": "maria@example.com" }
    },
    "subscription": {
      "endpoint": "https://push.example.com/send/demo-subscription-0001",
      "expirationTime": null,
      "keys": { "p256dh": "<p256dh key>", "auth": "<auth secret>" }
    }
  }'
```

Response: `202` `{}`.

| Cause                             | Message                                                                                                                          |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| No `context`                      | `context is missing from request body`                                                                                           |
| No `subscription`                 | `The 'subscription' field is required.`                                                                                          |
| `endpoint` not a URL              | `The 'subscription.endpoint' field must be a valid URL.`                                                                         |
| Missing key                       | `The 'subscription.keys.auth' field is required.`                                                                                |
| `expirationTime` sent as a number | `The 'subscription.expirationTime' field must be a string.` Send `null` or a string                                              |
| Bad e-mail                        | `The 'context.profile.email' field must be a valid e-mail.`                                                                      |
| `phoneNumber: "abc"`              | `context.profile.phoneNumber must be a valid telephone number starting with + and international code, e.g. +1. Got abc instead.` |
| `group: 10000`                    | `The 'context.group' field must be less than or equal to 9999.`                                                                  |
| Path token not a UUID             | `The access token you provided is invalid.`                                                                                      |
| No path segment at all            | `404` (route not found)                                                                                                          |

### Where the VAPID key comes from

`POST /api/v0/push/{accessToken}` is the SDK’s regular call, documented in the [Events API overview](https://releva.ai/documentation/reference/events/send-events-from-the-browser/). Every `200` response includes:

```plaintext
{ "push": { "vapidPublicKey": "<base64url VAPID public key>" } }
```

Use it as `applicationServerKey` when you subscribe a browser yourself. The key is the same for every shop on a Releva environment.

## What a delivered push contains

For reference when you build your own service worker or app handler. All text and URL fields are rendered per profile (merge tags, trigger event, product for recommender pushes, dynamic coupons).

* **Web** (Web Push, JSON payload): `source: "releva"`, `title`, `body`, `icon`, `image`, `badge`, `actions` (the one button), `tag`, `requireInteraction`, `renotify`, `silent`, `timestamp`, `id` and `data.url`, the link wrapped in a click-tracking redirect. TTL is **Message Expire Time** in seconds.
* **Android and iOS** (FCM data message): `title`, `body`, optional `imageUrl` and `button`, `target` (`screen` with `navigate_to_screen` and `navigate_to_parameters`, `url` with `navigate_to_url`, or `inbox`), `callbackUrl` for click tracking, and `inbox_sync`. Android TTL is **Message Expire Time** in hours with priority `high` (`normal` when **Silent**); APNs expiration is now plus **Message Expire Time**.

## Versioning

All endpoints are under `/api/v0`. For how versions and changes are handled, see [Authentication, errors and limits](https://releva.ai/documentation/reference/get-started/authentication-errors-and-limits/#versioning).

## Next steps

* [How push notifications work](https://releva.ai/documentation/learn/push-notifications/how-push-notifications-work/): Learn which channels a notification reaches, how devices opt in and what the statistics count.
* [Create a web push notification](https://releva.ai/documentation/guides/push-notifications/create-a-web-push-notification/): Write the notification your registered browsers receive.
* [Events API overview](https://releva.ai/documentation/reference/events/overview/): Send custom events from your own systems, with a working request for each endpoint.
* [Profiles API overview](https://releva.ai/documentation/reference/profiles/overview/): Create and update the profiles your push subscriptions belong to.