Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 112 additions & 69 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
# Appwrite Unity SDK

![License](https://img.shields.io/github/license/appwrite/sdk-for-unity.svg?style=flat-square)
![License](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg?style=flat-square)
![Version](https://img.shields.io/badge/api%20version-2.5.0-blue.svg?style=flat-square)
![Unity](https://img.shields.io/badge/Unity-2021.3%2B-blue.svg?style=flat-square)
[![Build Status](https://img.shields.io/travis/com/appwrite/sdk-for-unity?style=flat-square)](https://travis-ci.com/appwrite/sdk-for-unity)
[![Twitter Account](https://img.shields.io/twitter/follow/appwrite?color=00acee&label=twitter&style=flat-square)](https://twitter.com/appwrite)
[![X Account](https://img.shields.io/badge/follow-%40appwrite-000000?logo=x&style=flat-square)](https://x.com/appwrite)
[![Discord](https://img.shields.io/discord/564160730845151244?label=discord&style=flat-square)](https://appwrite.io/discord)

**This SDK targets Appwrite server version 2.5.x as shipped on Appwrite Cloud.** Self-hosted releases can lag behind Cloud — if you run an older self-hosted build, use a matching older SDK from [previous releases](https://github.com/appwrite/sdk-for-unity/releases) when APIs differ.
Expand All @@ -14,123 +13,171 @@ Appwrite is an open-source backend as a service server that abstracts and simpli

## Installation

Requires Unity 2021.3 or later. Installing from a git URL also requires [Git](https://git-scm.com/downloads) on your `PATH`.

### Unity Package Manager (UPM)

1. Open Unity and go to **Window > Package Manager**.
2. Click the **+** button and select **Add package from git URL**.
3. Enter the following URL:
1. In Unity, open **Window > Package Manager**.
2. Click the **+** button and select **Add package from git URL** (**Install package from git URL** in Unity 6).
3. Enter the following URL and click **Add** (**Install** in Unity 6):

```sh
```text
https://github.com/appwrite/sdk-for-unity.git#0.10.0
```

4. Click **Add**.
The `#0.10.0` suffix pins the package to a release. Change it to any released tag, or omit it to track the latest commit on the default branch.

You can also add the package to `Packages/manifest.json` directly:

```json
{
"dependencies": {
"io.appwrite.unity": "https://github.com/appwrite/sdk-for-unity.git#0.10.0"
}
}
```

### Install from disk

The `#0.10.0` suffix pins the package to a specific release. Change it to any released tag, or omit `#0.10.0` to track the latest commit on the default branch.
1. Download the source code archive of a release from [GitHub](https://github.com/appwrite/sdk-for-unity/releases) and extract it.
2. In **Window > Package Manager**, click the **+** button and select **Add package from disk** (**Install package from disk** in Unity 6).
3. Select the `package.json` file in the extracted folder.

### Manual Installation
## OAuth on Android

Download the latest release from [GitHub](https://appwrite.io/releases/latest) and import the Unity package into your project.
OAuth sign-in returns to your app through the `appwrite-callback-<PROJECT_ID>` URL scheme. Enable **Custom Main Manifest** in **Project Settings > Player > Android > Publishing Settings** and add this intent filter to the Unity activity in `Assets/Plugins/Android/AndroidManifest.xml`, replacing `<PROJECT_ID>` with your project ID:

```xml
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="appwrite-callback-<PROJECT_ID>" />
</intent-filter>
```

## Getting Started

Before you begin, create an Appwrite project and add a Unity platform in your Appwrite Console.
### Install dependencies

This SDK requires the following Unity packages and libraries:
The SDK depends on two packages that are installed separately:

- [**UniTask**](https://github.com/Cysharp/UniTask): For async/await support in Unity.
- [**NativeWebSocket**](https://github.com/endel/NativeWebSocket): For WebSocket realtime subscriptions.
- **System.Text.Json**: For JSON serialization, provided as a DLL in the project.
- [**UniTask**](https://github.com/Cysharp/UniTask) for async/await support.
- [**NativeWebSocket**](https://github.com/endel/NativeWebSocket) for realtime subscriptions.

After installing the SDK, open **Appwrite → Setup Assistant** in Unity and install the required dependencies.
When you first import the SDK, the **Appwrite Setup Assistant** opens and offers to install them. You can reopen it at any time from **Appwrite > Setup Assistant**. The SDK's runtime code stays disabled until UniTask is installed. `System.Text.Json` and its dependencies ship with the SDK as DLLs.

### Configure the SDK
### Configure your project

Create an Appwrite configuration using the **QuickStart** window in the **Appwrite Setup Assistant**, or through **Appwrite → Create Configuration**.
Create a project in the [Appwrite Console](https://cloud.appwrite.io/). Find your endpoint and project ID in the project's **Settings** page.

### Using AppwriteManager
If you build for WebGL, add a **Web** platform to your project with the hostname that serves your build, so Appwrite accepts requests from it.

Then create an `AppwriteConfig` asset with **Appwrite > Create Configuration**, or click **Setup Current Scene** in the Setup Assistant to create the asset and add an `AppwriteManager` to the open scene. Set the endpoint (for example `https://<REGION>.cloud.appwrite.io/v1`), your project ID, and the services you want `AppwriteManager` to create.

### Make your first request with AppwriteManager

`AppwriteManager` creates the client and the services selected in your configuration, and can open the realtime connection.

```csharp
[SerializeField] private AppwriteConfig config;
private AppwriteManager _manager;
using Appwrite;
using Appwrite.Services;
using Cysharp.Threading.Tasks;
using UnityEngine;

private async UniTask ExampleWithManager()
public class AppwriteExample : MonoBehaviour
{
_manager = AppwriteManager.Instance ?? new GameObject("AppwriteManager").AddComponent<AppwriteManager>();
_manager.SetConfig(config);
[SerializeField] private AppwriteConfig config;

private RealtimeSubscription subscription;

var success = await _manager.Initialize(needRealtime: true);
if (!success)
private async void Start()
{
Debug.LogError("Failed to initialize AppwriteManager");
return;
}
var manager = AppwriteManager.Instance;
if (manager == null)
{
manager = new GameObject("AppwriteManager").AddComponent<AppwriteManager>();
}

var client = _manager.Client;
var pingResult = await client.Ping();
Debug.Log($"Ping result: {pingResult}");
manager.SetConfig(config);

var realtime = _manager.Realtime;
var subscription = realtime.Subscribe(
new[] { "databases.*.collections.*.documents" },
response =>
if (!await manager.Initialize(needRealtime: true))
{
var eventName = response.Events != null && response.Events.Length > 0
? response.Events[0]
: "unknown";

Debug.Log($"Realtime event: {eventName}");
Debug.LogError("Failed to initialize AppwriteManager");
return;
}
);

// Keep a reference to close the subscription when your MonoBehaviour is destroyed.
// subscription.Close();
var tablesDB = manager.GetService<TablesDB>();
var rows = await tablesDB.ListRows(
databaseId: "<DATABASE_ID>",
tableId: "<TABLE_ID>");
Debug.Log($"Found {rows.Total} rows");

subscription = manager.Realtime.Subscribe(
Channel.TablesDB("<DATABASE_ID>").Table("<TABLE_ID>").Row(),
response => Debug.Log($"Realtime event: {response.Events[0]}"));
}

private void OnDestroy()
{
subscription?.Close();
}
}
```

### Using Client directly
`GetService<T>()` throws if the service is not selected in your `AppwriteConfig`.

### Using the client directly

You can also create a client and services yourself, without `AppwriteManager`:

```csharp
private async UniTask ExampleWithDirectClient()
{
var client = Client.From(
projectId: "<PROJECT_ID>",
endpoint: "https://<REGION>.cloud.appwrite.io/v1",
endpointRealtime: "wss://<REGION>.cloud.appwrite.io/v1");
var client = Client.From(
projectId: "<PROJECT_ID>",
endpoint: "https://<REGION>.cloud.appwrite.io/v1");

var pingResult = await client.Ping();
Debug.Log($"Direct client ping: {pingResult}");
}
var account = new Account(client);
var session = await account.CreateAnonymousSession();
Debug.Log($"Signed in as {session.UserId}");
```

You can also create authenticated clients with `Client.FromSession` or `Client.FromImpersonation` when those authentication flows are needed.
`Client.FromSession`, `Client.FromJWT` and `Client.FromImpersonation` create clients that are already authenticated.

### OAuth sign-in

`account.CreateOAuth2Session()` opens the provider's sign-in page and waits for Appwrite to redirect back to your app on the `appwrite-callback-<PROJECT_ID>` URL scheme. Appwrite accepts this scheme for your project without extra Console setup, but your build must handle it:

- **Android**: see [OAuth on Android](#oauth-on-android).
- **iOS**: add `appwrite-callback-<PROJECT_ID>` to **Supported URL schemes** under **Project Settings > Player > iOS > Other Settings**.
- **WebGL**: not supported. The sign-in page replaces your build in the same tab, and a browser cannot return to it on the callback scheme, so the call never completes. Use another sign-in method, such as email and password, in WebGL builds.

### Error handling

The SDK throws an `AppwriteException` when a request fails. It exposes `Message`, `Code`, `Type`, and `Response` properties that you can use to inspect the error.

```csharp
try
{
var result = await client.Ping();
var user = await account.Get();
}
catch (AppwriteException ex)
{
Debug.LogError($"Appwrite Error: {ex.Message}");
Debug.LogError($"Status Code: {ex.Code}");
Debug.LogError($"Appwrite error: {ex.Message}");
Debug.LogError($"Status code: {ex.Code}");
Debug.LogError($"Response: {ex.Response}");
}
```

## Preparing Models for Databases API
### Preparing models for TablesDB

When working with the Databases API in Unity, models should be prepared for serialization using the System.Text.Json library. System.Text.Json uses CLR property names by default unless a naming policy is configured. If your project or SDK configuration serializes property names differently from your Appwrite collection attributes, this can cause errors due to mismatches between serialized property names and actual attribute names in your collection.
The SDK serializes request data with `System.Text.Json` and converts property names from `PascalCase` to `camelCase`. If your table's column names are not in `camelCase`, the serialized names will not match your columns.

To avoid this, add the `JsonPropertyName` attribute to each property in your model class to match the attribute name in Appwrite:
Add the `JsonPropertyName` attribute to each property of your model so it serializes to the column name:

```csharp
using System.Text.Json.Serialization;

public class TestModel
public class Movie
{
[JsonPropertyName("name")]
public string Name { get; set; }
Expand All @@ -140,20 +187,16 @@ public class TestModel
}
```

The `JsonPropertyName` attribute ensures your data object is serialized with the correct attribute names for Appwrite databases.

### Learn more
You can use the following resources to learn more and get help:

- 🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-client)
- 🚀 [Appwrite Quick Starts](https://appwrite.io/docs/quick-starts)
- 📜 [Appwrite Docs](https://appwrite.io/docs)
- 💬 [Discord Community](https://appwrite.io/discord)
- 🧰 [Appwrite SDK Generator](https://github.com/appwrite/sdk-generator)


## Contribution

This library is auto-generated by the Appwrite [SDK Generator](https://github.com/appwrite/sdk-for-unity). To learn how you can help improve this SDK, please check the [contribution guide](https://github.com/appwrite/sdk-for-unity/blob/master/CONTRIBUTING.md) before sending a pull request.
This library is auto-generated by the Appwrite [SDK Generator](https://github.com/appwrite/sdk-generator). To learn how you can help improve this SDK, please check the [contribution guide](https://github.com/appwrite/sdk-generator/blob/main/CONTRIBUTING.md) before sending a pull request.

## License

Expand Down