---
source_url: https://www.pubnub.com/docs/sdks/dart/api-reference/data-sync
title: DataSync API for Dart SDK
updated_at: 2026-10-07T12:20:12.000Z
sdk_name: PubNub Dart SDK
sdk_version: 9.0.0
---

# DataSync API for Dart SDK

PubNub Dart SDK, use the latest version: 9.0.0

Install:

```bash
dart pub add pubnub@9.0.0
```

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

[DataSync](https://www.pubnub.com/docs/data-storage/structured-data/overview.md) is PubNub's data layer for storing application state (users, channels, memberships, and any custom object type) and keeping every connected client current through real-time events. Use it to model the objects your application works with and to react the moment they change.

DataSync is the successor to [App Context](https://www.pubnub.com/docs/sdks/dart/api-reference/objects.md).

:::note DataSync entities and SDK entities are different things
This page is about **DataSync entities**, the records the service stores and treats as the source of truth for your application state. They are created and read through the `pubnub.dataSync.*` methods documented here.
The Dart SDK has no DataSync SDK entities that carry stored state, but it does provide real-time handles for subscribing. `pubnub.dataSyncUser()`, `pubnub.dataSyncChannel()`, and `pubnub.dataSyncEntity()` take an object `id` and return a handle whose `subscription()` method builds the data channel name for you. Listen on the `dataSync` stream of the returned `Subscription`, as described in [Real-time updates](#real-time-updates).
:::

The classes that your objects conform to (their types and schemas) are defined through the Admin API or the [Admin Portal](https://admin.pubnub.com/), not through this SDK:

* Entity classes, which back users, channels, and custom entities: [list](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), [read](https://www.pubnub.com/docs/admin-api/get-entity-class-by-id.md), [create](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md), [replace](https://www.pubnub.com/docs/admin-api/update-entity-class-with-complete-resource-replacement.md), and [delete](https://www.pubnub.com/docs/admin-api/delete-entity-class-by-id.md). Partial updates aren't implemented; replace the complete class version instead.
* Relationship classes, which back memberships and custom relationships: [list](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md), [read](https://www.pubnub.com/docs/admin-api/get-relationship-class-by-name-and-version.md), [create](https://www.pubnub.com/docs/admin-api/create-a-new-relationship-class.md), [replace](https://www.pubnub.com/docs/admin-api/update-relationship-class-with-complete-resource-replacement.md), and [delete](https://www.pubnub.com/docs/admin-api/delete-relationship-class-by-name-and-version.md).

`User` and `Channel` entity classes and the `Membership` relationship class are predefined on every keyset, so you only need to define classes for your own custom entities and relationships.

A class definition is what decides, for every object of that class, which `payload` fields are filterable and sortable, which [projection](https://www.pubnub.com/docs/sdks/dart/api-reference/access-manager.md#grant-token) each field belongs to, and how long the object lives before it expires. Refer to [managing classes](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#managing-classes) for more information.

Every method returns a `Future` of a typed result. The single-object results hold the record in a named getter: `user`, `channel`, `membership`, `entity`, or `relationship`. The list results hold a list of records in `users`, `channels`, `memberships`, `entities`, or `relationships`, describe the pagination in `page`, `nextCursor`, and `hasNext`, and can carry the HATEOAS `links` (`self`, and `next` where it applies) the service adds to a list response. The `removeUser`, `removeChannel`, `removeMembership`, `removeEntity`, and `removeRelationship` methods return a result that carries no data. The `status` key in each Response block below stands for the HTTP status code, which the result doesn't expose, a failed request throws instead. A stored object carries its free-form `status` and its `expiresAt` auto-deletion timestamp (ISO 8601) whenever those are set on it, and the timestamps stay ISO 8601 strings rather than becoming `DateTime` objects.

### Authorization

Every DataSync request must be [authorized](https://www.pubnub.com/docs/data-storage/structured-data/access-control.md#authorizing-requests) with a token or signature. A request with no credential fails with a `401`; an invalid credential or a credential that doesn't permit the operation fails with a `403`.

A client that holds a secret key signs its requests. A client without one calls `pubnub.setToken` with a token from [Grant token](https://www.pubnub.com/docs/sdks/dart/api-reference/access-manager.md#grant-token) first.

### Pagination

DataSync pagination is **forward-only**. There is no previous-page cursor, and `DataSyncPage` exposes no previous cursor or `hasPrev`. To revisit an earlier page, page from the start again.

All list methods (`getUsers`, `getChannels`, `getMemberships`, `getEntities`, and `getRelationships`) accept `cursor` and `limit` (default `20`, max `100`) and can return a `DataSyncPage` in `page` with `hasNext`, `nextCursor`, and `limit`. The `page` is optional, so guard the access when you read it, for example `result.page?.nextCursor`. The result also offers `nextCursor` and `hasNext` directly, and `hasNext` is `false` when the service sends no page.

To page forward, pass the returned `nextCursor` back as `cursor` on the next call, and stop when `hasNext` is `false`. `nextCursor` is `null` on the last page. Refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination) for details.

### Filtering and sorting

All list methods accept two mutually exclusive filter parameters, `filterFast` and `filter`. The SDK sends whatever you pass, so a call that carries both reaches the server and fails there with a `400`.

| Parameter | Consistency | Properties it can read | Expression complexity |
| --- | --- | --- | --- |
| `filterFast` | Strongly consistent, reflects the latest writes | Filtering mode `simple` or `full` | Up to 10 conditions by default (raisable per keyset) |
| `filter` | Eventually consistent, results can briefly lag writes | Filtering mode `full` only | Full expression language |

Reach for `filterFast` when the query has to see an object you just wrote, and for `filter` when you need the full expression language over a `full`-indexed property.

:::warning danger
filter
is not the strongly consistent one
The two names read the wrong way round if you assume `filter` is the basic option. `filterFast` is the strongly consistent, limited one. `filter` is the richer, eventually consistent one.
:::

Both parameters share the same expression language, a string built from a property name, an operator, and a value:

| Operators |  |
| --- | --- |
| Comparison | `==`, `!=`, `<`, `>`, `<=`, `>=` |
| Pattern matching | `LIKE` (case-insensitive), `SLIKE` (case-sensitive), `ILIKE` (case-insensitive, same as `LIKE`) |
| Logical | `&&`, `||`, `!`, and parentheses for grouping |

Values are quoted strings, numbers, `true`, `false`, or `null`. Pattern operators (`LIKE`, `SLIKE`, `ILIKE`) apply to string properties only, and `null` is only valid with `==` and `!=`. Reference a property by its `name`, not its declared `path`, and only properties declared on the class are filterable. To reach a nested `payload` property, declare it as a class property first, then filter by that property's `name`, for example `'price < 100'` for a `product` class that declares `price`.

Some examples:

```dart
filterFast: 'price < 100',                                // strongly consistent, single condition
filterFast: '(price < 100 && stock > 0) || price > 500',  // strongly consistent, grouped conditions
filter: 'name LIKE "*sneaker*"',                          // eventually consistent, needs filtering mode "full"
filter: '!(status == "discontinued")',                    // eventually consistent, negated condition
```

Both parameters only work over properties declared on the class, plus the built-in `id`, `createdAt`, `updatedAt`, and `status` fields, which are always filterable and sortable without being declared. `eTag` and `expiresAt` are neither. The `status` exception does not hold if the class redeclares `/status` scoped to projections your token cannot fully reach. Refer to [filtering](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#filtering) for the two filtering tiers, and [property definitions](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#property-definitions) for how properties are declared.

Use `sort` to order results. Its value is a comma-separated list of fields, each a property name optionally suffixed with `:asc` or `:desc`. A bare name sorts ascending:

```dart
sort: 'price:desc',       // single field, descending
sort: 'type,price:desc',  // type ascending, then price descending
sort: 'createdAt:asc',    // explicit ascending
```

The `+field` and `-field` prefixes are **not** accepted. A leading `-` is read as part of the property name, so `'-price'` fails with a `400`. Only properties declared on the class with a filtering mode other than `none` can be sorted on when sorting alone or alongside `filterFast`. Sorting alongside `filter` additionally requires the field to be declared `full`. The built-in fields `id`, `createdAt`, `updatedAt`, and `status` are always sortable without declaring them on the class.

The SDK doesn't validate `filterFast`, `filter`, `sort`, or `limit` locally, it passes them through as-is. An invalid expression, an unsortable field, or an out-of-range `limit` only surfaces as an error response from the server, not as a client-side exception. The one thing the SDK does is drop an empty `filterFast`, `filter`, `sort`, or `cursor` string instead of sending it.

### Concurrency (ETag)

Every stored object carries an `eTag`. To guard against concurrent writes, pass the `eTag` you read earlier as `ifMatchesEtag` on `set*`, `update*`, and `remove*` calls. The SDK sends it as the `If-Match` request header.

If the server-side value has changed in the meantime, the operation fails with a `412`, and you should re-read the object and retry. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for details.

The `412` arrives as a `DataSyncException` whose `statusCode` is `412`.

### Partial updates

The `update*` methods apply a partial update using JSON Patch (RFC 6902). They accept `add`, `replace`, and `test` (JSON Pointer to value maps), `remove` (a list of JSON Pointers), and `move` and `copy` (lists of `JsonPointerPair`, each with a `from` and a `path`).

Each path is a full JSON Pointer (RFC 6901) and is sent as you write it. The SDK does **not** add a `/payload` prefix. To target a field inside `payload`, include the prefix yourself, for example `/payload/price`, not `/price`. A bare `/price` targets a top-level field named `price`, which doesn't exist. Top-level fields like `/status` can be patched directly. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for details.

Correct patch forms:

```dart
add: {'/payload/tags': ['sale']},                                    // adds a value inside payload.tags
replace: {'/payload/price': 79.99},                                  // replaces payload.price
remove: ['/payload/tempFlag'],                                       // removes payload.tempFlag
move: [JsonPointerPair(from: '/payload/oldTag', path: '/payload/tag')],
copy: [JsonPointerPair(from: '/payload/price', path: '/payload/msrp')],
test: {'/status': 'active'},                                         // fails the patch if the current value doesn't match
```

`move` and `copy` take the source pointer in `from` and the target pointer in `path`, instead of a value. `test` fails the entire patch if the current value at its path doesn't match, use it to guard the rest of the operations against a stale read.

Paths address the object's stored property names, the same keys that come back in responses. The class version is `entityClassVersion` on users, channels, and entities, and `relationshipClassVersion` on memberships and relationships. The fields set at creation cannot be patched: `entityClass` and `entityClassLevel` on users, channels, and entities, `relationshipClass`, `entityAId`, and `entityBId` on relationships, and `userId` and `channelId` on memberships.

All operations in the call apply together or not at all.

The order you write the arguments in does not matter, the SDK always sends the operations in the same order: `add`, `replace`, `remove`, `move`, `copy`, and `test` last. Keys and items keep their insertion order within each group.

At least one of `add`, `replace`, `remove`, `move`, `copy`, or `test` must be provided, and it must be non-empty. An empty map or list does not count. The SDK checks this before it sends anything and throws an `InvariantException` if nothing is provided.

### Expiry (TTL)

An object's `expiresAt` is computed once when the object is created, and updates never refresh it. The value is the creation time plus the class TTL, rounded up to the start of the next whole UTC day, so it rarely lands exactly one TTL from the moment you wrote the object.

Entity classes you create default to a 31-day TTL, while the built-in Global `User` and `Channel` classes use 30 days. TTL cannot be disabled. A relationship expires at the earlier expiry time of the two entities it links, fixed when the relationship is created.

Refer to [data expiry](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#data-expiry-ttl) for details.

:::note Futures, and how errors surface
Every DataSync method is asynchronous and returns a `Future`, so `await` it. The samples do. An argument the SDK can check locally, such as an empty id, an empty class name, or a missing patch operation, throws an `InvariantException` before anything is sent. When the service rejects a request, the `Future` completes with a `DataSyncException` that carries the machine-readable `errorCode` (for example `DS-0300`), the human-readable `errorMessage`, the `path` of the offending input when there is one, and the HTTP `statusCode`. When the service reports several errors, `errors` lists all of them. Branch on `errorCode`, not on `errorMessage`, because the message can change between releases. An Access Manager denial without DataSync error details throws a `ForbiddenException` instead.
:::

:::note Requires Access Manager
DataSync requires that the *Access Manager* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

## Users

Users are built-in objects. There are no top-level `name` or `email` fields, all application data lives in the free-form `payload`. Refer to [users](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#users) for the concept.

A user is an entity of the built-in `User` [entity class](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), which the service provides at the `Global` class level. To give your users their own declared, filterable properties, define a subclass of `User` with [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) and pass its name as `className`.

### Create user

Creates a user. Supply an `id` to control the identifier, or omit it to let the server generate one.

#### Method(s)

```dart
pubnub.dataSync.createUser(
  UserInput user, {
  Keyset? keyset,
  String? using,
}) // Future<CreateUserResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| user | UserInput | Yes |  | The user to create. |
| > id | string | Optional | `server-generated` | User identifier. Omit to let the server generate a UUID. Max 255 characters. |
| > className | string | Optional | `User` | Name of the entity class this user belongs to. Must be `User` or one of its subclasses. Defaults to `User` on the server if omitted. Set at creation and immutable afterward. Sent to the service as `entityClass`. |
| > classVersion | int | Yes |  | Version of the user class schema. Sent to the service as `entityClassVersion`. |
| > classLevel | ClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `ClassLevel.global` for a class the service provides or `ClassLevel.subKey` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| > status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| > payload | Map<String, dynamic> | Optional |  | Free-form JSON object holding your application data. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> createUser() async {
  var result = await pubnub.dataSync.createUser(UserInput(
    id: 'user-alice',
    classVersion: 1,
    payload: {'name': 'Alice', 'type': 'shopper'},
  ));

  print('Created ${result.user.id} with eTag ${result.user.eTag}');
}
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T09:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Get user

Returns a single user by `userId`.

#### Method(s)

```dart
pubnub.dataSync.getUser(
  String userId, {
  Keyset? keyset,
  String? using,
}) // Future<GetUserResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | string | Yes |  | User identifier. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> getUser() async {
  var result = await pubnub.dataSync.getUser('user-alice');

  print('Fetched ${result.user.id}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T09:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Get all users

Returns a paginated list of users. All parameters are optional, so you can call `getUsers` with no arguments. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```dart
pubnub.dataSync.getUsers({
  String? className,
  int? classVersion,
  ClassLevel? classLevel,
  String? cursor,
  int? limit,
  String? filterFast,
  String? filter,
  String? sort,
  Keyset? keyset,
  String? using,
}) // Future<GetUsersResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | string | Optional | `all user classes` | User class to list. Omit to list the Global `User` class and all of its subclasses. |
| classVersion | int | Optional | `latest version` | User class version to list. Omit to use the latest version of the class. |
| classLevel | ClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `ClassLevel.global` for a class the service provides or `ClassLevel.subKey` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| cursor | string | Optional |  | Opaque pagination cursor. Omit for the first page. |
| limit | int | Optional | `20` | Maximum number of users per page. Max `100`. |
| filterFast | string | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | string | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | string | Optional |  | Order results. Pass a comma-separated list of fields each optionally suffixed with `:asc` or `:desc`, for example `createdAt:desc`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> getUsers() async {
  var result = await pubnub.dataSync.getUsers();

  print('Fetched ${result.users.length} users');
}
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "user-alice",
            "entityClass": "User",
            "entityClassVersion": 1,
            "entityClassLevel": "Global",
            "payload": { "name": "Alice", "type": "shopper" },
            "createdAt": "2026-07-13T09:00:00.000Z",
            "updatedAt": "2026-07-13T09:00:00.000Z",
            "eTag": "AbCdEfGhIjKlMn"
        }
    ],
    "meta": {
        "next_cursor": "b2Zmc2V0PTIw",
        "has_next": true,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```dart
Future<void> getUsersFilterFast() async {
  var result = await pubnub.dataSync.getUsers(
    filterFast: 'type == "shopper"',
  );

  print('Found ${result.users.length} users');
}
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```dart
Future<void> getUsersFilter() async {
  var result = await pubnub.dataSync.getUsers(
    filter: 'name LIKE "*Alice*"',
  );

  print('Found ${result.users.length} users');
}
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `nextCursor` from the result and pass it back as `cursor` on the next call. Stop when `hasNext` is `false`.

```dart
Future<void> getUsersPagination() async {
  String? cursor;

  do {
    var result = await pubnub.dataSync.getUsers(limit: 50, cursor: cursor);

    for (var user in result.users) {
      print(user.id);
    }

    cursor = result.hasNext ? result.nextCursor : null;
  } while (cursor != null);
}
```

### Set user

Replaces a user in full (PUT). Send the complete set of fields, any field you omit is cleared. The class is immutable after creation, so `UserUpdate` doesn't expose it and there's nothing to send. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatchesEtag`. For a partial update, use [Update user](#update-user).

#### Method(s)

```dart
pubnub.dataSync.setUser(
  String userId,
  UserUpdate user, {
    String? ifMatchesEtag,
    Keyset? keyset,
    String? using,
  }
) // Future<SetUserResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | string | Yes |  | User identifier. |
| user | UserUpdate | Yes |  | The replacement user data. The entity class is immutable and cannot be included. |
| > classVersion | int | Yes |  | Version of the user class schema. Sent to the service as `entityClassVersion`. |
| > status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| > payload | Map<String, dynamic> | Optional |  | Free-form JSON object holding your application data. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> setUser() async {
  var result = await pubnub.dataSync.setUser(
    'user-alice',
    UserUpdate(
      classVersion: 1,
      payload: {'name': 'Alice B.', 'type': 'shopper'},
    ),
  );

  print('Replaced user, new eTag ${result.user.eTag}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice B.", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T10:15:00.000Z",
        "eTag": "CdEfGhIjKlMnOp"
    }
}
```

### Update user

Applies a partial update to a user. Paths can target fields inside `payload` or top-level stored fields. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the JSON Pointer rules.

#### Method(s)

```dart
pubnub.dataSync.updateUser(
  String userId, {
  Map<String, dynamic>? add,
  Map<String, dynamic>? replace,
  List<String>? remove,
  List<JsonPointerPair>? move,
  List<JsonPointerPair>? copy,
  Map<String, dynamic>? test,
  String? ifMatchesEtag,
  Keyset? keyset,
  String? using,
}) // Future<UpdateUserResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | string | Yes |  | User identifier. |
| add | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to values to add. Provide at least one patch operation. |
| replace | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to replacement values. Provide at least one patch operation. |
| remove | List<String> | Optional |  | Full JSON Pointers to remove. Provide at least one patch operation. |
| move | List<JsonPointerPair> | Optional |  | Pairs of `from` and `path` JSON Pointers. The value at `from` is removed and re-added at `path`. Provide at least one patch operation. |
| copy | List<JsonPointerPair> | Optional |  | Pairs of `from` and `path` JSON Pointers. The value at `from` is duplicated to `path`. Provide at least one patch operation. |
| test | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to expected values. The patch fails if any value does not match. Provide at least one patch operation. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> updateUser() async {
  var result = await pubnub.dataSync.updateUser(
    'user-alice',
    replace: {'/payload/name': 'Alice B.'},
  );

  print('Patched user, new eTag ${result.user.eTag}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "status": "active",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice B.", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T10:20:00.000Z",
        "eTag": "EfGhIjKlMnOpQr"
    }
}
```

### Remove user

Deletes a user by `userId`.

#### Method(s)

```dart
pubnub.dataSync.removeUser(
  String userId, {
  String? ifMatchesEtag,
  Keyset? keyset,
  String? using,
}) // Future<RemoveUserResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | string | Yes |  | User identifier. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> removeUser() async {
  await pubnub.dataSync.removeUser('user-alice');

  print('Removed user-alice');
}
```

#### Response

```json
{
    "status": 200
}
```

## Channels

Channels work like users. They have no top-level `name` field, all application data lives in `payload`, and they support the same operations. Refer to [channels](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#channels) for the concept.

A channel is an entity of the built-in `Channel` [entity class](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), which the service provides at the `Global` class level. Subclass it with [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) to add declared properties, then pass the subclass name as `className`.

### Create channel

Creates a channel. Supply an `id` to control the identifier, or omit it to let the server generate one.

#### Method(s)

```dart
pubnub.dataSync.createChannel(
  ChannelInput channel, {
  Keyset? keyset,
  String? using,
}) // Future<CreateChannelResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | ChannelInput | Yes |  | The channel to create. |
| > id | string | Optional | `server-generated` | Channel identifier. Omit to let the server generate a UUID. Max 255 characters. |
| > className | string | Optional | `Channel` | Name of the entity class this channel belongs to. Must be `Channel` or one of its subclasses. Defaults to `Channel` on the server if omitted. Set at creation and immutable afterward. Sent to the service as `entityClass`. |
| > classVersion | int | Yes |  | Version of the channel class schema. Sent to the service as `entityClassVersion`. |
| > classLevel | ClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `ClassLevel.global` for a class the service provides or `ClassLevel.subKey` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| > status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| > payload | Map<String, dynamic> | Optional |  | Free-form JSON object holding your application data. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> createChannel() async {
  var result = await pubnub.dataSync.createChannel(ChannelInput(
    id: 'channel-summer-sale',
    classVersion: 1,
    payload: {'name': 'Summer Sale', 'type': 'promotion'},
  ));

  print('Created ${result.channel.id} with eTag ${result.channel.eTag}');
}
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T09:05:00.000Z",
        "eTag": "GhIjKlMnOpQrSt"
    }
}
```

### Get channel

Returns a single channel by `channelId`.

#### Method(s)

```dart
pubnub.dataSync.getChannel(
  String channelId, {
  Keyset? keyset,
  String? using,
}) // Future<GetChannelResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | string | Yes |  | Channel identifier. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> getChannel() async {
  var result = await pubnub.dataSync.getChannel('channel-summer-sale');

  print('Fetched ${result.channel.id}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T09:05:00.000Z",
        "eTag": "GhIjKlMnOpQrSt"
    }
}
```

### Get all channels

Returns a paginated list of channels. All parameters are optional, so you can call `getChannels` with no arguments. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```dart
pubnub.dataSync.getChannels({
  String? className,
  int? classVersion,
  ClassLevel? classLevel,
  String? cursor,
  int? limit,
  String? filterFast,
  String? filter,
  String? sort,
  Keyset? keyset,
  String? using,
}) // Future<GetChannelsResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | string | Optional | `all channel classes` | Channel class to list. Omit to list the Global `Channel` class and all of its subclasses. |
| classVersion | int | Optional | `latest version` | Channel class version to list. Omit to use the latest version of the class. |
| classLevel | ClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `ClassLevel.global` for a class the service provides or `ClassLevel.subKey` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| cursor | string | Optional |  | Opaque pagination cursor. Omit for the first page. |
| limit | int | Optional | `20` | Maximum number of channels per page. Max `100`. |
| filterFast | string | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | string | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | string | Optional |  | Order results. Pass a comma-separated list of fields each optionally suffixed with `:asc` or `:desc`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> getChannels() async {
  var result = await pubnub.dataSync.getChannels();

  print('Fetched ${result.channels.length} channels');
}
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "channel-summer-sale",
            "entityClass": "Channel",
            "entityClassVersion": 1,
            "entityClassLevel": "Global",
            "payload": { "name": "Summer Sale", "type": "promotion" },
            "createdAt": "2026-07-13T09:05:00.000Z",
            "updatedAt": "2026-07-13T09:05:00.000Z",
            "eTag": "GhIjKlMnOpQrSt"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```dart
Future<void> getChannelsFilterFast() async {
  var result = await pubnub.dataSync.getChannels(
    filterFast: 'type == "promotion"',
  );

  print('Found ${result.channels.length} channels');
}
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```dart
Future<void> getChannelsFilter() async {
  var result = await pubnub.dataSync.getChannels(
    filter: 'name LIKE "*Summer*"',
  );

  print('Found ${result.channels.length} channels');
}
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `nextCursor` from the result and pass it back as `cursor` on the next call. Stop when `hasNext` is `false`.

```dart
Future<void> getChannelsPagination() async {
  String? cursor;

  do {
    var result = await pubnub.dataSync.getChannels(limit: 50, cursor: cursor);

    for (var channel in result.channels) {
      print(channel.id);
    }

    cursor = result.hasNext ? result.nextCursor : null;
  } while (cursor != null);
}
```

### Set channel

Replaces a channel in full (PUT). Send the complete set of fields, any field you omit is cleared. The class is immutable after creation, so `ChannelUpdate` doesn't expose it and there's nothing to send. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatchesEtag`. For a partial update, use [Update channel](#update-channel).

#### Method(s)

```dart
pubnub.dataSync.setChannel(
  String channelId,
  ChannelUpdate channel, {
    String? ifMatchesEtag,
    Keyset? keyset,
    String? using,
  }
) // Future<SetChannelResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | string | Yes |  | Channel identifier. |
| channel | ChannelUpdate | Yes |  | The replacement channel data. The entity class is immutable and cannot be included. |
| > classVersion | int | Yes |  | Version of the channel class schema. Sent to the service as `entityClassVersion`. |
| > status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| > payload | Map<String, dynamic> | Optional |  | Free-form JSON object holding your application data. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> setChannel() async {
  var result = await pubnub.dataSync.setChannel(
    'channel-summer-sale',
    ChannelUpdate(
      classVersion: 1,
      payload: {'name': 'Summer Sale 2026', 'type': 'promotion'},
    ),
  );

  print('Replaced channel, new eTag ${result.channel.eTag}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale 2026", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T11:00:00.000Z",
        "eTag": "IjKlMnOpQrStUv"
    }
}
```

### Update channel

Applies a partial update to a channel. Paths can target fields inside `payload` or top-level stored fields. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the JSON Pointer rules.

#### Method(s)

```dart
pubnub.dataSync.updateChannel(
  String channelId, {
  Map<String, dynamic>? add,
  Map<String, dynamic>? replace,
  List<String>? remove,
  List<JsonPointerPair>? move,
  List<JsonPointerPair>? copy,
  Map<String, dynamic>? test,
  String? ifMatchesEtag,
  Keyset? keyset,
  String? using,
}) // Future<UpdateChannelResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | string | Yes |  | Channel identifier. |
| add | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to values to add. Provide at least one patch operation. |
| replace | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to replacement values. Provide at least one patch operation. |
| remove | List<String> | Optional |  | Full JSON Pointers to remove. Provide at least one patch operation. |
| move | List<JsonPointerPair> | Optional |  | Pairs of `from` and `path` JSON Pointers. The value at `from` is removed and re-added at `path`. Provide at least one patch operation. |
| copy | List<JsonPointerPair> | Optional |  | Pairs of `from` and `path` JSON Pointers. The value at `from` is duplicated to `path`. Provide at least one patch operation. |
| test | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to expected values. The patch fails if any value does not match. Provide at least one patch operation. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> updateChannel() async {
  var result = await pubnub.dataSync.updateChannel(
    'channel-summer-sale',
    replace: {'/payload/name': 'Summer Sale 2026'},
  );

  print('Patched channel, new eTag ${result.channel.eTag}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "status": "active",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale 2026", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T11:05:00.000Z",
        "eTag": "KlMnOpQrStUvWx"
    }
}
```

### Remove channel

Deletes a channel by `channelId`.

#### Method(s)

```dart
pubnub.dataSync.removeChannel(
  String channelId, {
  String? ifMatchesEtag,
  Keyset? keyset,
  String? using,
}) // Future<RemoveChannelResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | string | Yes |  | Channel identifier. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> removeChannel() async {
  await pubnub.dataSync.removeChannel('channel-summer-sale');

  print('Removed channel-summer-sale');
}
```

#### Response

```json
{
    "status": 200
}
```

## Memberships

A membership links a user to a channel and carries its own `payload`. In the running example, Alice is a member of `channel-summer-sale` with the payload `{ "role": "viewer" }`. Refer to [memberships](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#memberships) for the concept.

A membership is a relationship of the built-in Global `Membership` [relationship class](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md), whose two sides are surfaced as `channelId` and `userId`. Every membership response includes both `relationshipClass` and `relationshipClassVersion`. The class is assigned by the service, so the `createMembership` and `setMembership` methods take no class parameter.

Relationship classes [don't support inheritance](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#relationship-class-inheritance), and only the Global `Membership` class produces memberships, so `relationshipClass` is always `Membership` and `relationshipClassVersion` is the only part that varies.

### Create membership

Creates a membership linking a user to a channel. The `userId`/`channelId` pair must be unique for the membership class. A membership that duplicates an existing pair is rejected with a `409`.

#### Method(s)

```dart
pubnub.dataSync.createMembership(
  MembershipInput membership, {
  Keyset? keyset,
  String? using,
}) // Future<CreateMembershipResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membership | MembershipInput | Yes |  | The membership to create. |
| > id | string | Optional | `server-generated` | Membership identifier. Omit to let the server generate a UUID. Max 255 characters. |
| > channelId | string | Yes |  | Identifier of the channel in the membership. |
| > userId | string | Yes |  | Identifier of the user in the membership. |
| > classVersion | int | Yes |  | Version of the membership class schema. Sent to the service as `relationshipClassVersion`. |
| > status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| > payload | Map<String, dynamic> | Optional |  | Free-form JSON object holding your application data. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> createMembership() async {
  var result = await pubnub.dataSync.createMembership(MembershipInput(
    id: 'membership-alice-summer-sale',
    channelId: 'channel-summer-sale',
    userId: 'user-alice',
    classVersion: 1,
    payload: {'role': 'viewer'},
  ));

  print('Created ${result.membership.id} with eTag ${result.membership.eTag}');
}
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "viewer" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T09:10:00.000Z",
        "eTag": "MnOpQrStUvWxYz"
    }
}
```

### Get membership

Returns a single membership by `membershipId`.

#### Method(s)

```dart
pubnub.dataSync.getMembership(
  String membershipId, {
  Keyset? keyset,
  String? using,
}) // Future<GetMembershipResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | string | Yes |  | Membership identifier. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> getMembership() async {
  var result =
      await pubnub.dataSync.getMembership('membership-alice-summer-sale');

  print('Fetched ${result.membership.id}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "viewer" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T09:10:00.000Z",
        "eTag": "MnOpQrStUvWxYz"
    }
}
```

### Get all memberships

Returns a paginated list of memberships. All parameters are optional, so you can call `getMemberships` with no arguments. `userId` and `channelId` can be set independently, together, or omitted entirely. Filter by `userId` to list a user's memberships or by `channelId` to list a channel's members. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```dart
pubnub.dataSync.getMemberships({
  String? userId,
  String? channelId,
  int? classVersion,
  String? cursor,
  int? limit,
  String? filterFast,
  String? filter,
  String? sort,
  Keyset? keyset,
  String? using,
}) // Future<GetMembershipsResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | string | Optional |  | List only memberships for this user. |
| channelId | string | Optional |  | List only memberships for this channel. |
| classVersion | int | Optional | `latest version` | Membership class version to list. Omit to use the latest version of the class. |
| cursor | string | Optional |  | Opaque pagination cursor. Omit for the first page. |
| limit | int | Optional | `20` | Maximum number of memberships per page. Max `100`. |
| filterFast | string | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | string | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | string | Optional |  | Order results. Pass a comma-separated list of fields each optionally suffixed with `:asc` or `:desc`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> getMemberships() async {
  var result = await pubnub.dataSync.getMemberships(userId: 'user-alice');

  print('Fetched ${result.memberships.length} memberships');
}
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "membership-alice-summer-sale",
            "channelId": "channel-summer-sale",
            "userId": "user-alice",
            "relationshipClass": "Membership",
            "relationshipClassVersion": 1,
            "payload": { "role": "viewer" },
            "createdAt": "2026-07-13T09:10:00.000Z",
            "updatedAt": "2026-07-13T09:10:00.000Z",
            "eTag": "MnOpQrStUvWxYz"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### List a channel's members with channelId

Pass `channelId` instead of `userId` to list the members of a channel rather than a user's memberships.

```dart
Future<void> getMembershipsByChannelId() async {
  var result = await pubnub.dataSync.getMemberships(
    channelId: 'channel-summer-sale',
  );

  print('Found ${result.memberships.length} members');
}
```

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```dart
Future<void> getMembershipsFilterFast() async {
  var result = await pubnub.dataSync.getMemberships(
    filterFast: 'role == "viewer"',
  );

  print('Found ${result.memberships.length} memberships');
}
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```dart
Future<void> getMembershipsFilter() async {
  var result = await pubnub.dataSync.getMemberships(
    filter: 'role LIKE "*mod*"',
  );

  print('Found ${result.memberships.length} memberships');
}
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `nextCursor` from the result and pass it back as `cursor` on the next call. Stop when `hasNext` is `false`.

```dart
Future<void> getMembershipsPagination() async {
  String? cursor;

  do {
    var result = await pubnub.dataSync.getMemberships(
      userId: 'user-alice',
      limit: 50,
      cursor: cursor,
    );

    for (var membership in result.memberships) {
      print(membership.id);
    }

    cursor = result.hasNext ? result.nextCursor : null;
  } while (cursor != null);
}
```

### Set membership

Replaces a membership in full (PUT). Send the complete set of fields, any field you omit is cleared. The channel and the user are immutable, so `MembershipUpdate` doesn't expose `channelId` or `userId` at all, there's nothing to resend. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatchesEtag`. For a partial update, use [Update membership](#update-membership).

#### Method(s)

```dart
pubnub.dataSync.setMembership(
  String membershipId,
  MembershipUpdate membership, {
    String? ifMatchesEtag,
    Keyset? keyset,
    String? using,
  }
) // Future<SetMembershipResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | string | Yes |  | Membership identifier. |
| membership | MembershipUpdate | Yes |  | The replacement membership data. The channel, the user, and the relationship class are immutable and cannot be included. |
| > classVersion | int | Yes |  | Version of the membership class schema. Sent to the service as `relationshipClassVersion`. |
| > status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| > payload | Map<String, dynamic> | Optional |  | Free-form JSON object holding your application data. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> setMembership() async {
  var result = await pubnub.dataSync.setMembership(
    'membership-alice-summer-sale',
    MembershipUpdate(
      classVersion: 1,
      payload: {'role': 'moderator'},
    ),
  );

  print('Replaced membership, new eTag ${result.membership.eTag}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "moderator" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T12:00:00.000Z",
        "eTag": "OpQrStUvWxYzAb"
    }
}
```

### Update membership

Applies a partial update to a membership. Paths can target fields inside `payload` or top-level stored fields. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the JSON Pointer rules.

#### Method(s)

```dart
pubnub.dataSync.updateMembership(
  String membershipId, {
  Map<String, dynamic>? add,
  Map<String, dynamic>? replace,
  List<String>? remove,
  List<JsonPointerPair>? move,
  List<JsonPointerPair>? copy,
  Map<String, dynamic>? test,
  String? ifMatchesEtag,
  Keyset? keyset,
  String? using,
}) // Future<UpdateMembershipResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | string | Yes |  | Membership identifier. |
| add | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to values to add. Provide at least one patch operation. |
| replace | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to replacement values. Provide at least one patch operation. |
| remove | List<String> | Optional |  | Full JSON Pointers to remove. Provide at least one patch operation. |
| move | List<JsonPointerPair> | Optional |  | Pairs of `from` and `path` JSON Pointers. The value at `from` is removed and re-added at `path`. Provide at least one patch operation. |
| copy | List<JsonPointerPair> | Optional |  | Pairs of `from` and `path` JSON Pointers. The value at `from` is duplicated to `path`. Provide at least one patch operation. |
| test | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to expected values. The patch fails if any value does not match. Provide at least one patch operation. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> updateMembership() async {
  var result = await pubnub.dataSync.updateMembership(
    'membership-alice-summer-sale',
    replace: {'/payload/role': 'moderator'},
  );

  print('Patched membership, new eTag ${result.membership.eTag}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "status": "active",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "moderator" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T12:05:00.000Z",
        "eTag": "QrStUvWxYzAbCd"
    }
}
```

### Remove membership

Deletes a membership by `membershipId`.

#### Method(s)

```dart
pubnub.dataSync.removeMembership(
  String membershipId, {
  String? ifMatchesEtag,
  Keyset? keyset,
  String? using,
}) // Future<RemoveMembershipResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | string | Yes |  | Membership identifier. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> removeMembership() async {
  await pubnub.dataSync.removeMembership('membership-alice-summer-sale');

  print('Removed membership-alice-summer-sale');
}
```

#### Response

```json
{
    "status": 200
}
```

## Entities

Entities are instances of the custom [entity classes](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md) you define on your keyset. In the running example, `product` is a class and `product-sneaker-42` is an instance. Use [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) to declare a class, and [Get entity class by ID](https://www.pubnub.com/docs/admin-api/get-entity-class-by-id.md) to read the property, filtering, and projection declarations that govern its instances.

Entity classes can extend one another. Listing a class also returns the entities of its subclasses, so `getEntities('product')` returns every `product` plus every instance of a class that extends `product`.

### Create entity

Creates an entity of a given class and version.

#### Method(s)

```dart
pubnub.dataSync.createEntity(
  EntityInput entity, {
  Keyset? keyset,
  String? using,
}) // Future<CreateEntityResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entity | EntityInput | Yes |  | The entity to create. |
| > id | string | Optional | `server-generated` | Entity identifier. Omit to let the server generate a UUID. Max 255 characters. |
| > className | string | Yes |  | Name of the entity class this instance belongs to. Set at creation and immutable afterward. Sent to the service as `entityClass`. |
| > classVersion | int | Yes |  | Version of the entity class schema. Sent to the service as `entityClassVersion`. |
| > classLevel | ClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `ClassLevel.global` for a class the service provides or `ClassLevel.subKey` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| > status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| > payload | Map<String, dynamic> | Optional |  | Free-form JSON object holding your application data. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> createEntity() async {
  var result = await pubnub.dataSync.createEntity(EntityInput(
    id: 'product-sneaker-42',
    className: 'product',
    classVersion: 1,
    payload: {'name': 'Retro Sneaker', 'price': 89.99, 'stock': 12},
  ));

  print('Created ${result.entity.id} with eTag ${result.entity.eTag}');
}
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T09:15:00.000Z",
        "eTag": "StUvWxYzAbCdEf"
    }
}
```

### Get entity

Returns a single entity by `entityId`.

#### Method(s)

```dart
pubnub.dataSync.getEntity(
  String entityId, {
  Keyset? keyset,
  String? using,
}) // Future<GetEntityResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | string | Yes |  | Entity identifier. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> getEntity() async {
  var result = await pubnub.dataSync.getEntity('product-sneaker-42');

  print('Fetched ${result.entity.id}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T09:15:00.000Z",
        "eTag": "StUvWxYzAbCdEf"
    }
}
```

### Get all entities

Returns a paginated list of entities within a class. The `className` parameter is required, entities are always listed within the context of their class. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```dart
pubnub.dataSync.getEntities(
  String className, {
  int? classVersion,
  ClassLevel? classLevel,
  String? cursor,
  int? limit,
  String? filterFast,
  String? filter,
  String? sort,
  Keyset? keyset,
  String? using,
}) // Future<GetEntitiesResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | string | Yes |  | Name of the entity class to list. |
| classVersion | int | Optional | `latest version` | Entity class version to list. Omit to use the latest version of the class. |
| classLevel | ClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `ClassLevel.global` for a class the service provides or `ClassLevel.subKey` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| cursor | string | Optional |  | Opaque pagination cursor. Omit for the first page. |
| limit | int | Optional | `20` | Maximum number of entities per page. Max `100`. |
| filterFast | string | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | string | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | string | Optional |  | Order results. Pass a comma-separated list of fields each optionally suffixed with `:asc` or `:desc`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> getEntities() async {
  var result = await pubnub.dataSync.getEntities('product');

  print('Fetched ${result.entities.length} entities');
}
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "product-sneaker-42",
            "entityClass": "product",
            "entityClassVersion": 1,
            "entityClassLevel": "SubKey",
            "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
            "createdAt": "2026-07-13T09:15:00.000Z",
            "updatedAt": "2026-07-13T09:15:00.000Z",
            "eTag": "StUvWxYzAbCdEf"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`, and combine conditions with `&&` and `||`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```dart
Future<void> getEntitiesFilterFast() async {
  var result = await pubnub.dataSync.getEntities(
    'product',
    filterFast: 'price < 100',
  );

  print('Found ${result.entities.length} entities');
}
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`, and combine conditions with `&&` and `||`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```dart
Future<void> getEntitiesFilter() async {
  var result = await pubnub.dataSync.getEntities(
    'product',
    filter: 'name LIKE "*sneaker*"',
  );

  print('Found ${result.entities.length} entities');
}
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `nextCursor` from the result and pass it back as `cursor` on the next call. Stop when `hasNext` is `false`.

```dart
Future<void> getEntitiesPagination() async {
  String? cursor;

  do {
    var result = await pubnub.dataSync.getEntities(
      'product',
      limit: 50,
      cursor: cursor,
    );

    for (var entity in result.entities) {
      print(entity.id);
    }

    cursor = result.hasNext ? result.nextCursor : null;
  } while (cursor != null);
}
```

### Set entity

Replaces an entity in full (PUT). Send the complete set of fields, any field you omit is cleared. The class is immutable after creation, so `EntityUpdate` doesn't expose it and there's nothing to send. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatchesEtag`. For a partial update, use [Update entity](#update-entity).

#### Method(s)

```dart
pubnub.dataSync.setEntity(
  String entityId,
  EntityUpdate entity, {
    String? ifMatchesEtag,
    Keyset? keyset,
    String? using,
  }
) // Future<SetEntityResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | string | Yes |  | Entity identifier. |
| entity | EntityUpdate | Yes |  | The replacement entity data. The entity class is immutable and cannot be included. |
| > classVersion | int | Yes |  | Version of the entity class schema. Sent to the service as `entityClassVersion`. |
| > status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| > payload | Map<String, dynamic> | Optional |  | Free-form JSON object holding your application data. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> setEntity() async {
  var result = await pubnub.dataSync.setEntity(
    'product-sneaker-42',
    EntityUpdate(
      classVersion: 1,
      payload: {'name': 'Retro Sneaker', 'price': 79.99, 'stock': 8},
    ),
  );

  print('Replaced entity, new eTag ${result.entity.eTag}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 79.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T13:00:00.000Z",
        "eTag": "UvWxYzAbCdEfGh"
    }
}
```

### Update entity

Applies a partial update to an entity. Paths can target fields inside `payload` or top-level stored fields. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the JSON Pointer rules.

#### Method(s)

```dart
pubnub.dataSync.updateEntity(
  String entityId, {
  Map<String, dynamic>? add,
  Map<String, dynamic>? replace,
  List<String>? remove,
  List<JsonPointerPair>? move,
  List<JsonPointerPair>? copy,
  Map<String, dynamic>? test,
  String? ifMatchesEtag,
  Keyset? keyset,
  String? using,
}) // Future<UpdateEntityResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | string | Yes |  | Entity identifier. |
| add | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to values to add. Provide at least one patch operation. |
| replace | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to replacement values. Provide at least one patch operation. |
| remove | List<String> | Optional |  | Full JSON Pointers to remove. Provide at least one patch operation. |
| move | List<JsonPointerPair> | Optional |  | Pairs of `from` and `path` JSON Pointers. The value at `from` is removed and re-added at `path`. Provide at least one patch operation. |
| copy | List<JsonPointerPair> | Optional |  | Pairs of `from` and `path` JSON Pointers. The value at `from` is duplicated to `path`. Provide at least one patch operation. |
| test | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to expected values. The patch fails if any value does not match. Provide at least one patch operation. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> updateEntity() async {
  var result = await pubnub.dataSync.updateEntity(
    'product-sneaker-42',
    replace: {'/payload/price': 79.99},
  );

  print('Patched entity, new eTag ${result.entity.eTag}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 79.99, "stock": 8 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T13:05:00.000Z",
        "eTag": "WxYzAbCdEfGhIj"
    }
}
```

#### Other examples

##### Combine patch operations, and guard the write with ifMatchesEtag

A single `updateEntity` call can mix `add`, `replace`, `remove`, `move`, `copy`, and `test` in one call. All operations in the call apply together or not at all. Add `ifMatchesEtag` (the `eTag` from a prior read) to reject the patch with a `412` if the entity changed since you read it, instead of silently overwriting a concurrent change.

```dart
Future<void> updateEntityMultipleOperations() async {
  var current = await pubnub.dataSync.getEntity('product-sneaker-42');

  var result = await pubnub.dataSync.updateEntity(
    'product-sneaker-42',
    ifMatchesEtag: current.entity.eTag,
    test: {'/status': 'active'},
    add: {
      '/payload/tags': ['sale']
    },
    replace: {'/payload/price': 79.99},
    remove: ['/payload/tempFlag'],
    move: [JsonPointerPair(from: '/payload/oldTag', path: '/payload/tag')],
    copy: [JsonPointerPair(from: '/payload/price', path: '/payload/msrp')],
  );

  print('Patched entity, new eTag ${result.entity.eTag}');
}
```

### Remove entity

Deletes an entity by `entityId`.

#### Method(s)

```dart
pubnub.dataSync.removeEntity(
  String entityId, {
  String? ifMatchesEtag,
  Keyset? keyset,
  String? using,
}) // Future<RemoveEntityResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | string | Yes |  | Entity identifier. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> removeEntity() async {
  await pubnub.dataSync.removeEntity('product-sneaker-42');

  print('Removed product-sneaker-42');
}
```

#### Response

```json
{
    "status": 200
}
```

## Relationships

A relationship links two entities and carries its own `payload`. In the running example, the `ProductOwner` relationship links `seller-bob` to `product-sneaker-42`.

Relationships are instances of the [relationship classes](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md) you define on your keyset. A relationship class declares the cardinality the service enforces (`one-to-one`, `one-to-many`, or `many-to-many`) and, optionally, which entity class each side must belong to. Use [Create a new relationship class](https://www.pubnub.com/docs/admin-api/create-a-new-relationship-class.md) to declare a class, and [Get relationship class by name and version](https://www.pubnub.com/docs/admin-api/get-relationship-class-by-name-and-version.md) to read it back.

### Create relationship

Creates a relationship between two entities. The relationship class's cardinality (one-to-one, one-to-many, or many-to-many) is enforced on create. A relationship that violates its class's cardinality is rejected with a `409`.

#### Method(s)

```dart
pubnub.dataSync.createRelationship(
  RelationshipInput relationship, {
  Keyset? keyset,
  String? using,
}) // Future<CreateRelationshipResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationship | RelationshipInput | Yes |  | The relationship to create. |
| > id | string | Optional | `server-generated` | Relationship identifier. Omit to let the server generate a UUID. Max 255 characters. |
| > entityAId | string | Yes |  | Identifier of the first linked entity. Immutable after creation. |
| > entityBId | string | Yes |  | Identifier of the second linked entity. Immutable after creation. |
| > className | string | Yes |  | Name of the relationship class this instance belongs to. Set at creation and immutable afterward. Sent to the service as `relationshipClass`. |
| > classVersion | int | Yes |  | Version of the relationship class schema. Sent to the service as `relationshipClassVersion`. |
| > status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| > payload | Map<String, dynamic> | Optional |  | Free-form JSON object holding your application data. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> createRelationship() async {
  var result = await pubnub.dataSync.createRelationship(RelationshipInput(
    id: 'rel-bob-owns-sneaker-42',
    entityAId: 'seller-bob',
    entityBId: 'product-sneaker-42',
    className: 'ProductOwner',
    classVersion: 1,
    payload: {'since': '2026-07-13'},
  ));

  print('Created ${result.relationship.id} '
      'with eTag ${result.relationship.eTag}');
}
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T09:20:00.000Z",
        "eTag": "YzAbCdEfGhIjKl"
    }
}
```

### Get relationship

Returns a single relationship by `relationshipId`.

#### Method(s)

```dart
pubnub.dataSync.getRelationship(
  String relationshipId, {
  Keyset? keyset,
  String? using,
}) // Future<GetRelationshipResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | string | Yes |  | Relationship identifier. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> getRelationship() async {
  var result =
      await pubnub.dataSync.getRelationship('rel-bob-owns-sneaker-42');

  print('Fetched ${result.relationship.id}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T09:20:00.000Z",
        "eTag": "YzAbCdEfGhIjKl"
    }
}
```

### Get all relationships

Returns a paginated list of relationships within a class. The `className` parameter is required. Filter by `entityAId` or `entityBId` to list a specific entity's links. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```dart
pubnub.dataSync.getRelationships(
  String className, {
  int? classVersion,
  String? entityAId,
  String? entityBId,
  String? cursor,
  int? limit,
  String? filterFast,
  String? filter,
  String? sort,
  Keyset? keyset,
  String? using,
}) // Future<GetRelationshipsResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | string | Yes |  | Name of the relationship class to list. |
| classVersion | int | Optional | `latest version` | Relationship class version to list. Omit to use the latest version of the class. |
| entityAId | string | Optional |  | List only relationships whose first entity is this id. |
| entityBId | string | Optional |  | List only relationships whose second entity is this id. |
| cursor | string | Optional |  | Opaque pagination cursor. Omit for the first page. |
| limit | int | Optional | `20` | Maximum number of relationships per page. Max `100`. |
| filterFast | string | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | string | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | string | Optional |  | Order results. Pass a comma-separated list of fields each optionally suffixed with `:asc` or `:desc`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> getRelationships() async {
  var result = await pubnub.dataSync.getRelationships(
    'ProductOwner',
    entityAId: 'seller-bob',
  );

  print('Fetched ${result.relationships.length} relationships');
}
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "rel-bob-owns-sneaker-42",
            "entityAId": "seller-bob",
            "entityBId": "product-sneaker-42",
            "relationshipClass": "ProductOwner",
            "relationshipClassVersion": 1,
            "payload": { "since": "2026-07-13" },
            "createdAt": "2026-07-13T09:20:00.000Z",
            "updatedAt": "2026-07-13T09:20:00.000Z",
            "eTag": "YzAbCdEfGhIjKl"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### List an entity's incoming links with entityBId

Pass `entityBId` instead of `entityAId` to list relationships where the entity is on the second side of the link.

```dart
Future<void> getRelationshipsByEntityBId() async {
  var result = await pubnub.dataSync.getRelationships(
    'ProductOwner',
    entityBId: 'product-sneaker-42',
  );

  print('Found ${result.relationships.length} relationships');
}
```

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```dart
Future<void> getRelationshipsFilterFast() async {
  var result = await pubnub.dataSync.getRelationships(
    'ProductOwner',
    filterFast: 'tier == "gold"',
  );

  print('Found ${result.relationships.length} relationships');
}
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```dart
Future<void> getRelationshipsFilter() async {
  var result = await pubnub.dataSync.getRelationships(
    'ProductOwner',
    filter: 'tier LIKE "*old"',
  );

  print('Found ${result.relationships.length} relationships');
}
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `nextCursor` from the result and pass it back as `cursor` on the next call. Stop when `hasNext` is `false`.

```dart
Future<void> getRelationshipsPagination() async {
  String? cursor;

  do {
    var result = await pubnub.dataSync.getRelationships(
      'ProductOwner',
      limit: 50,
      cursor: cursor,
    );

    for (var relationship in result.relationships) {
      print(relationship.id);
    }

    cursor = result.hasNext ? result.nextCursor : null;
  } while (cursor != null);
}
```

### Set relationship

Replaces a relationship in full (PUT). Send the complete set of fields, any field you omit is cleared. The linked entities are immutable, so `RelationshipUpdate` doesn't expose `entityAId` or `entityBId` at all, there's nothing to resend. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatchesEtag`. For a partial update, use [Update relationship](#update-relationship).

#### Method(s)

```dart
pubnub.dataSync.setRelationship(
  String relationshipId,
  RelationshipUpdate relationship, {
    String? ifMatchesEtag,
    Keyset? keyset,
    String? using,
  }
) // Future<SetRelationshipResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | string | Yes |  | Relationship identifier. |
| relationship | RelationshipUpdate | Yes |  | The replacement relationship data. The linked entities and the relationship class are immutable and cannot be included. |
| > classVersion | int | Yes |  | Version of the relationship class schema. Sent to the service as `relationshipClassVersion`. |
| > status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| > payload | Map<String, dynamic> | Optional |  | Free-form JSON object holding your application data. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> setRelationship() async {
  var result = await pubnub.dataSync.setRelationship(
    'rel-bob-owns-sneaker-42',
    RelationshipUpdate(
      classVersion: 1,
      payload: {'since': '2026-07-13', 'tier': 'gold'},
    ),
  );

  print('Replaced relationship, new eTag ${result.relationship.eTag}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13", "tier": "gold" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T14:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Update relationship

Applies a partial update to a relationship. Paths can target fields inside `payload` or top-level stored fields. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the JSON Pointer rules.

#### Method(s)

```dart
pubnub.dataSync.updateRelationship(
  String relationshipId, {
  Map<String, dynamic>? add,
  Map<String, dynamic>? replace,
  List<String>? remove,
  List<JsonPointerPair>? move,
  List<JsonPointerPair>? copy,
  Map<String, dynamic>? test,
  String? ifMatchesEtag,
  Keyset? keyset,
  String? using,
}) // Future<UpdateRelationshipResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | string | Yes |  | Relationship identifier. |
| add | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to values to add. Provide at least one patch operation. |
| replace | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to replacement values. Provide at least one patch operation. |
| remove | List<String> | Optional |  | Full JSON Pointers to remove. Provide at least one patch operation. |
| move | List<JsonPointerPair> | Optional |  | Pairs of `from` and `path` JSON Pointers. The value at `from` is removed and re-added at `path`. Provide at least one patch operation. |
| copy | List<JsonPointerPair> | Optional |  | Pairs of `from` and `path` JSON Pointers. The value at `from` is duplicated to `path`. Provide at least one patch operation. |
| test | Map<String, dynamic> | Optional |  | Full JSON Pointers mapped to expected values. The patch fails if any value does not match. Provide at least one patch operation. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> updateRelationship() async {
  var result = await pubnub.dataSync.updateRelationship(
    'rel-bob-owns-sneaker-42',
    replace: {'/payload/tier': 'platinum'},
  );

  print('Patched relationship, new eTag ${result.relationship.eTag}');
}
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13", "tier": "platinum" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T14:05:00.000Z",
        "eTag": "CdEfGhIjKlMnOp"
    }
}
```

### Remove relationship

Deletes a relationship by `relationshipId`.

#### Method(s)

```dart
pubnub.dataSync.removeRelationship(
  String relationshipId, {
  String? ifMatchesEtag,
  Keyset? keyset,
  String? using,
}) // Future<RemoveRelationshipResult>
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | string | Yes |  | Relationship identifier. |
| ifMatchesEtag | string | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |
| keyset | Keyset | Optional | `default keyset` | Override for the PubNub default keyset configuration. |
| using | string | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```dart
import 'package:pubnub/pubnub.dart';

// DataSync requests must be authorized. A client that holds a secret key signs
// its requests, a client without one sets a token with `pubnub.setToken(...)`.
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo',
    publishKey: 'demo',
    secretKey: 'demo',
    userId: UserId('dart-datasync-sample'),
  ),
);
Future<void> removeRelationship() async {
  await pubnub.dataSync.removeRelationship('rel-bob-owns-sneaker-42');

  print('Removed rel-bob-owns-sneaker-42');
}
```

#### Response

```json
{
    "status": 200
}
```

## Real-time updates

DataSync objects can publish `create`, `update`, and `delete` events that you receive in real time on the `dataSync` stream of a `Subscription`. Create a subscription to the object with `pubnub.dataSyncUser(id)`, `pubnub.dataSyncChannel(id)`, or `pubnub.dataSyncEntity(id)`, call `subscribe()` on it, and listen to `subscription.dataSync`, as described in [Add DataSync listener](https://www.pubnub.com/docs/sdks/dart/api-reference/publish-and-subscribe.md#add-datasync-listener). A membership or relationship has no handle of its own, because it never publishes on a channel named after its own id. Subscribe through the user, channel, or entity it connects.

```dart
Future<void> listenForDataSyncEvents() async {
  var subscription = pubnub.dataSyncEntity('product-sneaker-42').subscription();

  subscription.dataSync.listen((event) {
    print('${event.event.name} ${event.objectType.name} ${event.id} '
        '(class ${event.className})');
  });

  subscription.subscribe();
}
```

Each event names the change in `event`, identifies the object kind in `objectType` (`user`, `channel`, `membership`, `entity`, or `relationship`), and carries the object state in `data`, which the typed getters `id`, `status`, `payload`, `eTag`, `createdAt`, `updatedAt`, and `expiresAt` read from. For a `delete` event, only `id` and `deletedAt` are set.

`objectType` names the object kind directly, while the state always arrives in the same `data` map. Dispatch on `objectType` rather than on which getters return a value, because one event type serves all five kinds. `className` tells you the specific class within a kind, for example which subclass of `User` an event belongs to. Membership events carry `channelId` and `userId`, and relationship events carry `entityAId` and `entityBId`.

### Where each event is delivered

The channels that receive an event depend on the changed object. A relationship or membership never publishes on a channel named after its own id:

| Change to | On `create` | On `update` or `delete` |
| --- | --- | --- |
| A user | The user's `id` | The user's `id`, plus the `id` of every entity, user, or channel connected to it by a relationship or membership |
| A channel | The channel's `id` | The channel's `id`, plus the `id` of every entity, user, or channel connected to it by a relationship or membership |
| An entity | The entity's `id` | The entity's `id`, plus the `id` of every entity, user, or channel connected to it by a relationship or membership |
| A membership | **Both** the `userId` and the `channelId` of the membership | Same as `create` |
| A relationship | **Both** the `entityAId` and the `entityBId` of the relationship | Same as `create` |

:::note Update and delete also fan out to connected objects
An update or delete on a user, channel, or entity is also delivered on the `id` channel of every other object connected to it by a relationship or membership, in either direction, at the time of the change. A client subscribed to a connected object's channel receives the event too, even though that object itself did not change. A create does not fan out this way, because nothing can be connected to a brand new object yet.
The connected channels are entity, user, and channel ids. Relationships and memberships never get an id channel of their own, so they never appear in this fan-out as a channel name.
:::

So to see memberships appear and disappear for Alice, subscribe to `user-alice` rather than the membership id. A client subscribed to both sides of the same link receives the change twice, once per channel. Deduplicate create and update events on the object's `id` and `updatedAt`, and delete events on `id` and `deletedAt`.

### Projection channels

Each [projection](https://www.pubnub.com/docs/sdks/dart/api-reference/access-manager.md#grant-token) declared on the class gets its own event, published to its own channel, and carrying only that projection's view of the payload:

| Projection | Channel | Payload |
| --- | --- | --- |
| `__default__` (the base projection) | The object's own id, for example `product-sneaker-42` | The fields tagged `__default__` |
| Any named projection, for example `admin` | `__<projection>__<id>`, for example `__admin__product-sneaker-42` | The fields tagged with that projection |

Filtering applies to `payload` and to `status`: each is included in a given projection's event only if the class declares it under that projection, falling back to `__default__` when the class never declares `status`. `id`, `eTag`, `createdAt`, `updatedAt`, and `expiresAt` are never filtered. Every projection's event carries them unchanged.

So one change to an object whose class declares an `admin` projection publishes two events, and a client subscribed only to `product-sneaker-42` never sees the `admin`-only fields.

To observe a projection, pass its name as `projection` to `subscription()` on a DataSync handle. The SDK subscribes to `__<projection>__<id>` for you. You can also pass `withProjection` to `pubnub.subscribe()` or `pubnub.subscription()`, which applies to `channels` only and not to `channelGroups`. The rules are:

* A `null` or blank projection, `default`, and `__default__` all refer to the base projection, so the object's own id is subscribed as it is.
* Ids are used verbatim, so wildcards such as `customer.*` work. Don't pass an id that already carries a projection prefix.
* To observe several projections of the same object, create one subscription per projection.
* `Subscription.projection` returns the projection a subscription observes, or `null` for the base projection.

```dart
Future<void> subscribeToProjectionChannels() async {
  var entity = pubnub.dataSyncEntity('product-sneaker-42');

  // Observes `product-sneaker-42`, the base projection.
  var base = entity.subscription();
  // Observes `__admin__product-sneaker-42`.
  var admin = entity.subscription(projection: 'admin');

  base.dataSync.listen((event) {
    print('base ${event.event.name} ${event.id} payload ${event.payload}');
  });
  admin.dataSync.listen((event) {
    print('admin ${event.event.name} ${event.id} payload ${event.payload}');
  });

  base.subscribe();
  admin.subscribe();
}
```

If the class declares no properties at all there is nothing to filter, so a single unfiltered event is published to the object's own id channel.

:::warning Projection channels need channel grants
Publishing to `__<projection>__<id>` is an ordinary channel publish, and it isn't gated by the projection assignments in a token. Use Access Manager grants on `ResourceType.channel` to control who can subscribe to a projection channel. Anyone who can subscribe there receives the restricted fields. Refer to [Grant token](https://www.pubnub.com/docs/sdks/dart/api-reference/access-manager.md#grant-token).
:::

Delete events are never filtered by a projection.

Events are off by default and are enabled per class in the [Admin Portal](https://admin.pubnub.com). Refer to [enabling events](https://www.pubnub.com/docs/data-storage/structured-data/events.md#enable-datasync-events) for how to turn them on, and [receiving events](https://www.pubnub.com/docs/data-storage/structured-data/events.md) for the listener flow.

Last updated at: 2026-10-07T12:20:12.000Z
