# Register a web push subscription for the signed-in user

Stores or refreshes the browser subscription by endpoint; an endpoint held by another user is moved to the caller as a new subscription.

`POST /api/v1/public/push/subscribe`

- Sign-in: A signed-in user's session: send the session id in the x-session-id header.
- Rate limit: Up to 500 requests every 3 seconds per IP address; up to 1,000 requests a minute per API key (some requests are not counted).

Stores or refreshes the browser subscription by endpoint; an endpoint held by another user is moved to the caller as a new subscription. A newly created subscription gets a welcome notification when the organization's push is on. Answers 400 for an endpoint host that is not accepted, and 503 when the organization's subscriber ceiling refuses a new subscription.

## Request

Send the body as `application/json`.

| Field            | Type           | Required | Constraints                                            | Description |
| ---------------- | -------------- | -------- | ------------------------------------------------------ | ----------- |
| `endpoint`       | string         | Yes      | 1 to 1024 characters, matches `^https://`              | -           |
| `keys`           | object         | Yes      | -                                                      | -           |
| `keys.p256dh`    | string         | Yes      | 80 to 128 characters, matches `^[A-Za-z0-9_-]+={0,2}$` | -           |
| `keys.auth`      | string         | Yes      | 16 to 64 characters, matches `^[A-Za-z0-9_-]+={0,2}$`  | -           |
| `userAgent`      | string         | No       | at most 512 characters                                 | -           |
| `expirationTime` | number or null | No       | -                                                      | -           |

## Example request

Replace each `YOUR_...` value with your own, and set the credential in the environment variable the sample reads.

```bash title="cURL"
curl -X POST "https://api.console.buildbase.app/api/v1/public/push/subscribe" \
  -H "x-session-id: $BUILDBASE_SESSION_ID" \
  -H "Content-Type: application/json" \
  -d '{
  "endpoint": "string",
  "keys": {
    "p256dh": "string",
    "auth": "string"
  }
}'
```

```ts title="TypeScript"
const response = await fetch(
  'https://api.console.buildbase.app/api/v1/public/push/subscribe',
  {
    method: 'POST',
    headers: {
      'x-session-id': process.env.BUILDBASE_SESSION_ID ?? '',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      endpoint: 'string',
      keys: {
        p256dh: 'string',
        auth: 'string',
      },
    }),
  }
);
if (!response.ok) {
  throw new Error(`${response.status}: ${await response.text()}`);
}
const data = await response.json();
```

```python title="Python"
import os

import requests

response = requests.post(
    "https://api.console.buildbase.app/api/v1/public/push/subscribe",
    headers={
        "x-session-id": os.environ["BUILDBASE_SESSION_ID"],
    },
    json={
        "endpoint": "string",
        "keys": {
            "p256dh": "string",
            "auth": "string",
        },
    },
    timeout=30,
)
response.raise_for_status()
data = response.json()
```

## Responses

### 200 OK

OK

```json title="Example"
{
  "success": true
}
```

### Any other status

Any other answer the handler sends itself (its own refusals). Not described yet.

## Errors

Each refusal, what it means, and what to do. The request changed nothing.

### 400 Bad Request

**What it means:** The request failed a `validate()` schema, or an id in the path is not a valid id. `path` names the field.

**What to do:** Fix the field the body names in `path` (or read `message`) and send the request again. Nothing was changed.

```json title="Example"
{
  "error": true,
  "success": false,
  "path": "string",
  "message": "string"
}
```

### 401 Unauthorized

**What it means:** The credential is missing, expired or not accepted here, or the caller's role has no grant for `x-permission` (refused with 401 too). The body is the plain text `Unauthorized`, or a JSON body with a `code` where the gate says why.

**What to do:** Send the credential this operation asks for (see Sign-in above), or sign in again if it expired. A valid credential is also refused when the role has no grant for the permission above.

```text title="Example"
Unauthorized
```

### 429 Too Many Requests

**What it means:** A rate limit in `x-rateLimit` was reached. `retryAfter` and the `Retry-After` header say how many seconds until the window resets.

**What to do:** Wait the number of seconds in the `Retry-After` header (also `retryAfter` in the body), then retry. Slow down repeated calls.

```json title="Example"
{
  "success": false,
  "message": "string",
  "reason": "rate_limited",
  "retryAfter": 1
}
```

## Related

- [Push guide](/push-notifications/overview): how this part of BuildBase works
- [All Push operations](/http-api/reference/push)
- [API reference](/http-api/reference): every operation, by tag
- [Sign-in and credentials for the HTTP API](/http-api/authentication)
- [How the HTTP API reports errors](/http-api/errors)
- [Make your first call](/http-api/first-call)
- [Error codes](/reference/error-codes): every `code` the API returns
- OpenAPI: operation `push.subscribe.create` in [public-v1.json](https://docs.buildbase.app/openapi/public-v1.json)
