### Full Appwrite Web SDK Example Source: https://github.com/appwrite/sdk-for-web/blob/main/README.md A complete example demonstrating SDK initialization and user registration. It combines client setup with the first API call to the Account service. ```javascript // Init your Web SDK const client = new Client(); client .setEndpoint('http://localhost/v1') // Your Appwrite Endpoint .setProject('455x34dfkj') ; const account = new Account(client); // Register User account.create(ID.unique(), "email@example.com", "password", "Walter O'Brien") .then(function (response) { console.log(response); }, function (error) { console.log(error); }); ``` -------------------------------- ### Install Appwrite SDK via NPM Source: https://github.com/appwrite/sdk-for-web/blob/main/README.md Use this command to install the Appwrite SDK as a dependency in your Node.js project. It's recommended for projects using module bundlers. ```bash npm install appwrite --save ``` -------------------------------- ### Register New User Source: https://github.com/appwrite/sdk-for-web/blob/main/README.md Example of registering a new user with Appwrite using the Account service. This requires an initialized client and uses `ID.unique()` for a new user ID. ```javascript const account = new Account(client); // Register User account.create(ID.unique(), "email@example.com", "password", "Walter O'Brien") .then(function (response) { console.log(response); }, function (error) { console.log(error); }); ``` -------------------------------- ### Get Session using SDK Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/account/get-session.md Use this method to retrieve session details by providing the session ID. Ensure your client is initialized with your project details. ```javascript import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const account = new Account(client); const result = await account.getSession({ sessionId: '' }); console.log(result); ``` -------------------------------- ### Get Screenshot Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/avatars/get-screenshot.md Generates a screenshot of a given URL with customizable options. ```APIDOC ## GET /avatars/screenshot ### Description Generates a screenshot of a given URL. This method allows for detailed customization of the screenshot, including dimensions, scale, theme, user agent, and more. ### Method GET ### Endpoint /avatars/screenshot ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the website to capture. - **width** (integer) - Optional - The desired width of the screenshot in pixels. - **height** (integer) - Optional - The desired height of the screenshot in pixels. - **scale** (integer) - Optional - The scale of the screenshot. Minimum value is 1. Maximum value is 2. - **theme** (string) - Optional - The theme to use for the screenshot. Possible values are 'light' or 'dark'. - **userAgent** (string) - Optional - The user agent string to use for the request. - **fullpage** (boolean) - Optional - Whether to capture the full page or just the viewport. - **locale** (string) - Optional - The locale to use for the screenshot. Format: ISO 639-1 language code combined with ISO 3166-1 country code. - **timezone** (string) - Optional - The timezone to use for the screenshot. Use `Timezone` enum for available options. - **latitude** (float) - Optional - The latitude to use for the screenshot. - **longitude** (float) - Optional - The longitude to use for the screenshot. - **accuracy** (integer) - Optional - The accuracy of the location in meters. - **touch** (boolean) - Optional - Whether to emulate touch events. - **sleep** (integer) - Optional - The time in seconds to wait before taking the screenshot. - **quality** (integer) - Optional - The quality of the JPEG screenshot. Minimum value is 0. Maximum value is 100. - **output** (string) - Optional - The output format for the screenshot. Possible values are 'jpeg', 'png', 'webp'. ### Response #### Success Response (200) - **image** (string) - The screenshot image in the specified format. #### Response Example (Image data would be returned here, not representable as JSON) ``` -------------------------------- ### Create TOTP Authenticator Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/account/create-mfa-authenticator.md This snippet demonstrates how to initiate the creation of a TOTP authenticator for a user. The response will contain details needed to complete the setup, such as a secret key. ```APIDOC ## createMFAAuthenticator ### Description Creates a new MFA authenticator for the user. Currently, only TOTP is supported. ### Method `account.createMFAAuthenticator(authenticatorCreationRequest)` ### Parameters #### Request Body - **type** (string) - Required - The type of the authenticator to create. Use `AuthenticatorType.Totp` for TOTP. ### Request Example ```javascript const result = await account.createMFAAuthenticator({ type: AuthenticatorType.Totp }); ``` ### Response #### Success Response (200) - **$id** (string) - The ID of the authenticator. - **userId** (string) - The ID of the user the authenticator belongs to. - **type** (string) - The type of the authenticator. - **secret** (string) - The secret key for TOTP authenticators, used to generate codes. - **qr** (string) - The QR code string for TOTP authenticators, which can be used to set up authenticator apps. - **name** (string) - The name of the authenticator (e.g., 'Default TOTP'). - **datetimeCreated** (string) - The date and time the authenticator was created. - **datetimeUpdated** (string) - The date and time the authenticator was last updated. #### Response Example ```json { "$id": "60a5f1b2c3d4e5f6a7b8c9d0", "userId": "60a5f1b2c3d4e5f6a7b8c9d1", "type": "totp", "secret": "YOUR_TOTP_SECRET_KEY", "qr": "otpauth://totp/Appwrite:user@example.com?secret=YOUR_TOTP_SECRET_KEY&issuer=Appwrite", "name": "Default TOTP", "datetimeCreated": "2023-10-27T10:00:00.000+00:00", "datetimeUpdated": "2023-10-27T10:00:00.000+00:00" } ``` ``` -------------------------------- ### Get File Preview Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/storage/get-file-preview.md Generates a preview of a file. You can specify various parameters to customize the preview, such as width, height, quality, and output format. ```APIDOC ## Get File Preview ### Description Generates a preview of a file with customizable options. ### Method ```javascript storage.getFilePreview(parameters) ``` ### Parameters #### Path Parameters - **bucketId** (string) - Required - Bucket ID. - **fileId** (string) - Required - File ID. #### Query Parameters - **width** (integer) - Optional - Preview width, in pixels. Default value is 0. - **height** (integer) - Optional - Preview height, in pixels. Default value is 0. - **gravity** (string) - Optional - Image gravity. Default value is `ImageGravity.Center`. - **quality** (integer) - Optional - Preview quality, between 0 and 100. Default value is -1. - **borderWidth** (integer) - Optional - Preview border width, in pixels. Default value is 0. - **borderColor** (string) - Optional - Preview border color. Default value is an empty string. - **borderRadius** (integer) - Optional - Preview border radius, in pixels. Default value is 0. - **opacity** (float) - Optional - Preview opacity, between 0 and 1. Default value is 0. - **rotation** (integer) - Optional - Preview rotation in degrees. Default value is -360. - **background** (string) - Optional - Preview background color. Default value is an empty string. - **output** (string) - Optional - Preview output format. Default value is `ImageFormat.Jpg`. - **token** (string) - Optional - Security token. Default value is an empty string. ### Request Example ```javascript const result = await storage.getFilePreview({ bucketId: '', fileId: '', width: 800, height: 600, quality: 80, output: ImageFormat.Png }); ``` ### Response #### Success Response (200) - **data** (string) - The file preview data as a string (e.g., base64 encoded). #### Response Example ```json { "data": "" } ``` ``` -------------------------------- ### Manage User Accounts with Appwrite SDK Source: https://context7.com/appwrite/sdk-for-web/llms.txt Handles user registration, email/password sessions, anonymous sessions, OAuth2 login, MFA setup, email updates, listing sessions, and logging out. Ensure AppwriteException is handled for errors. ```javascript import { Client, Account, OAuthProvider, AuthenticatorType, ID } from "appwrite"; const client = new Client() .setEndpoint('https://us-east-1.cloud.appwrite.com/v1') .setProject(''); const account = new Account(client); try { // 1. Register a new user const newUser = await account.create({ userId: ID.unique(), email: 'walter@example.com', password: 'supersecret123', name: "Walter O'Brien" }); console.log('Registered:', newUser.$id); // 2. Create an email/password session (login) const session = await account.createEmailPasswordSession({ email: 'walter@example.com', password: 'supersecret123' }); console.log('Session created:', session.$id); // 3. Retrieve the logged-in user const me = await account.get(); console.log('Logged in as:', me.name, me.email); // 4. Create an anonymous session (guest) const anonSession = await account.createAnonymousSession(); console.log('Anonymous session:', anonSession.$id); // 5. OAuth2 login — redirects the browser (no await) account.createOAuth2Session({ provider: OAuthProvider.Google, success: 'https://myapp.com/dashboard', failure: 'https://myapp.com/login' }); // 6. Enable TOTP-based MFA for the logged-in user const totp = await account.createMFAAuthenticator({ type: AuthenticatorType.Totp }); console.log('TOTP secret URI:', totp.uri); // scan with authenticator app // 7. Update email address const updated = await account.updateEmail({ email: 'new-email@example.com', password: 'supersecret123' }); console.log('Email updated:', updated.email); // 8. List all active sessions const sessions = await account.listSessions(); console.log('Active sessions:', sessions.sessions.length); // 9. Delete the current session (logout) await account.deleteSession({ sessionId: 'current' }); console.log('Logged out'); } catch (e) { if (e instanceof AppwriteException) { console.error(`[${e.code}] ${e.message}`); } } ``` -------------------------------- ### Create Row Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/tablesdb/create-row.md This example demonstrates how to create a new row in a specified table within a database. It includes setting the database ID, table ID, a unique row ID, the data for the row, and optional permissions and transaction ID. ```APIDOC ## Create Row ### Description Creates a new row in a specified table within a database. ### Method `tablesDB.createRow(attributes)` ### Parameters #### Path Parameters - **databaseId** (string) - Required - The ID of the database. - **tableId** (string) - Required - The ID of the table. - **rowId** (string) - Required - The ID of the row to create. Use `ID.unique()` for auto-generation. #### Request Body - **data** (object) - Required - An object containing the key-value pairs for the row's attributes. - **permissions** (array) - Optional - An array of permission objects to set for the row. - **transactionId** (string) - Optional - The ID of the transaction to associate with this operation. ``` -------------------------------- ### Get a File - Appwrite SDK for Web Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/storage/get-file.md Use this snippet to retrieve a file from your Appwrite storage. Ensure you have initialized the Appwrite client and Storage service with your project details. ```javascript import { Client, Storage } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const storage = new Storage(client); const result = await storage.getFile({ bucketId: '', fileId: '' }); console.log(result); ``` -------------------------------- ### Import Appwrite SDK Modules Source: https://github.com/appwrite/sdk-for-web/blob/main/README.md Import the necessary classes from the Appwrite SDK after installation. This is typically done at the top of your JavaScript files. ```javascript import { Client, Account } from "appwrite"; ``` -------------------------------- ### TablesDB Row Management with Appwrite SDK Source: https://context7.com/appwrite/sdk-for-web/llms.txt Utilize TablesDB for SQL-style row-based storage operations. This example demonstrates initializing the client, creating a row with data and permissions, listing rows with queries, upserting a row, atomically incrementing a column, and deleting a row. ```javascript import { Client, TablesDB, Permission, Role, ID } from "appwrite"; const client = new Client() .setEndpoint('https://us-east-1.cloud.appwrite.io/v1') .setProject(''); const tablesDB = new TablesDB(client); // Create a row const row = await tablesDB.createRow({ databaseId: 'analytics-db', tableId: 'events', rowId: ID.unique(), data: { userId: 'user-abc', event: 'page_view', path: '/dashboard', timestamp: new Date().toISOString() }, permissions: [Permission.read(Role.user('user-abc'))] }); console.log('Row created:', row.$id); // List rows with queries const rows = await tablesDB.listRows({ databaseId: 'analytics-db', tableId: 'events', queries: [ Query.equal('userId', 'user-abc'), Query.orderDesc('timestamp'), Query.limit(50) ] }); console.log(`${rows.total} events found`); // Upsert a row await tablesDB.upsertRow({ databaseId: 'analytics-db', tableId: 'user_stats', rowId: 'user-abc-stats', data: { userId: 'user-abc', pageViews: 1, lastSeen: new Date().toISOString() } }); // Increment a column atomically await tablesDB.incrementRowColumn({ databaseId: 'analytics-db', tableId: 'user_stats', rowId: 'user-abc-stats', attribute: 'pageViews', value: 1 }); // Delete a row await tablesDB.deleteRow({ databaseId: 'analytics-db', tableId: 'events', rowId: row.$id }); ``` -------------------------------- ### Get File Download using Appwrite Web SDK Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/storage/get-file-download.md Use this snippet to initiate a file download from Appwrite Storage. Ensure you have initialized the Appwrite client and storage service. The token parameter is optional and can be used for authenticated downloads. ```javascript import { Client, Storage } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const storage = new Storage(client); const result = storage.getFileDownload({ bucketId: '', fileId: '', token: '' // optional }); console.log(result); ``` -------------------------------- ### Get File Preview with Appwrite SDK for Web Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/storage/get-file-preview.md Use this snippet to generate a preview of a file stored in Appwrite. You can specify dimensions, quality, format, and other options to customize the preview. Ensure you have initialized the Appwrite client with your endpoint and project ID. ```javascript import { Client, Storage, ImageGravity, ImageFormat } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const storage = new Storage(client); const result = storage.getFilePreview({ bucketId: '', fileId: '', width: 0, // optional height: 0, // optional gravity: ImageGravity.Center, // optional quality: -1, // optional borderWidth: 0, // optional borderColor: '', // optional borderRadius: 0, // optional opacity: 0, // optional rotation: -360, // optional background: '', // optional output: ImageFormat.Jpg, // optional token: '' // optional }); console.log(result); ``` -------------------------------- ### Get Function Execution Details Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/functions/get-execution.md Use this snippet to retrieve the details of a specific function execution. Ensure you have initialized the Appwrite client and Functions service with your project details. ```javascript import { Client, Functions } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const functions = new Functions(client); const result = await functions.getExecution({ functionId: '', executionId: '' }); console.log(result); ``` -------------------------------- ### Teams — Collaborative Access Management Source: https://context7.com/appwrite/sdk-for-web/llms.txt This section explains how to use the `Teams` service to create teams, manage memberships with custom roles, and control team-level preferences. It includes examples for creating teams, inviting members, listing memberships, updating roles, setting preferences, and deleting teams. ```APIDOC ## Teams — Collaborative Access Management The `Teams` service creates teams, manages memberships with custom roles, and controls team-level preferences. ```javascript import { Client, Teams, ID } from "appwrite"; const client = new Client() .setEndpoint('https://us-east-1.cloud.appwrite.io/v1') .setProject(''); const teams = new Teams(client); // Create a team const team = await teams.create({ teamId: ID.unique(), name: 'Editorial Staff', roles: ['editor', 'reviewer', 'admin'] }); console.log('Team created:', team.$id, team.name); // Invite a member (sends invitation email) const membership = await teams.createMembership({ teamId: team.$id, roles: ['editor'], email: 'alice@example.com', url: 'https://myapp.com/accept-invite' // redirect URL in invitation email }); console.log('Invited:', membership.$id, membership.userEmail); // List all memberships const members = await teams.listMemberships({ teamId: team.$id }); members.memberships.forEach(m => console.log(m.userName, m.roles)); // Update a member's roles await teams.updateMembership({ teamId: team.$id, membershipId: membership.$id, roles: ['editor', 'reviewer'] }); // Save team-level preferences await teams.updatePrefs({ teamId: team.$id, prefs: { theme: 'dark', notificationsEnabled: true } }); // Remove a member await teams.deleteMembership({ teamId: team.$id, membershipId: membership.$id }); // Delete the team await teams.delete({ teamId: team.$id }); ``` ``` -------------------------------- ### Get Team Preferences Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/teams/get-prefs.md Retrieves the preferences object for a team. Use this method to get the current settings and configurations associated with a specific team. ```APIDOC ## GET /teams/{teamId}/prefs ### Description Retrieves the preferences object for a team. ### Method GET ### Endpoint /teams/{teamId}/prefs ### Parameters #### Path Parameters - **teamId** (string) - Required - The ID of the team for which to retrieve preferences. ### Response #### Success Response (200) - **prefs** (object) - An object containing the team's preferences. ### Response Example { "prefs": { "key1": "value1", "key2": "value2" } } ``` -------------------------------- ### Initialize Appwrite Client and Databases Service Source: https://context7.com/appwrite/sdk-for-web/llms.txt Set up the Appwrite client with your project's endpoint and ID. Instantiate the Databases service to interact with your Appwrite project's collections and documents. ```javascript import { Client, Databases, Query, Permission, Role, ID } from "appwrite"; const client = new Client() .setEndpoint('https://us-east-1.cloud.appwrite.io/v1') .setProject(''); const databases = new Databases(client); ``` -------------------------------- ### Initialize and Configure Appwrite Client Source: https://context7.com/appwrite/sdk-for-web/llms.txt Configure the Client with your endpoint and project ID before using any service. Optional configurations include JWT authentication, locale override, and user impersonation. ```javascript import { Client, Account, Databases, AppwriteException } from "appwrite"; const client = new Client() .setEndpoint('https://us-east-1.cloud.appwrite.io/v1') // Appwrite Cloud or self-hosted URL .setProject('my-project-id'); // Found in Appwrite Console → Settings // Optional: authenticate with a JWT instead of a session cookie client.setJWT('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'); // Optional: override the locale for localized responses client.setLocale('en-US'); // Optional: impersonate another user (requires impersonator capability on the session) client.setImpersonateUserId('user-abc123'); // Inspect the headers that will be sent with every request const headers = client.getHeaders(); console.log(headers); // { 'x-sdk-name': 'Web', 'x-sdk-version': '25.0.0', 'X-Appwrite-Project': 'my-project-id', ... } // Ping the server to verify connectivity const pong = await client.ping(); console.log(pong); // "pong" ``` -------------------------------- ### Get Image using Avatars Service Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/avatars/get-image.md Use the Avatars service to get an image from a given URL. Optional width and height parameters can be provided to resize the image. ```javascript import { Client, Avatars } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const avatars = new Avatars(client); const result = avatars.getImage({ url: 'https://example.com', width: 0, // optional height: 0 // optional }); console.log(result); ``` -------------------------------- ### Client — Initialize and Configure the SDK Source: https://context7.com/appwrite/sdk-for-web/llms.txt The `Client` class is the root object for configuring the SDK. It must be configured with your Appwrite endpoint and project ID before instantiating any service. Optional configurations include setting JWT for authentication, overriding locale, and impersonating users. ```APIDOC ## Client — Initialize and Configure the SDK ### Description The `Client` class is the root object that holds endpoint, project, and authentication configuration shared across all services. It must be configured before instantiating any service. ### Method Instantiate and configure the Client object. ### Usage ```javascript import { Client, Account, Databases, AppwriteException } from "appwrite"; const client = new Client() .setEndpoint('https://us-east-1.cloud.appwrite.io/v1') // Appwrite Cloud or self-hosted URL .setProject('my-project-id'); // Found in Appwrite Console → Settings // Optional: authenticate with a JWT instead of a session cookie client.setJWT('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'); // Optional: override the locale for localized responses client.setLocale('en-US'); // Optional: impersonate another user (requires impersonator capability on the session) client.setImpersonateUserId('user-abc123'); // Inspect the headers that will be sent with every request const headers = client.getHeaders(); console.log(headers); // { 'x-sdk-name': 'Web', 'x-sdk-version': '25.0.0', 'X-Appwrite-Project': 'my-project-id', ... } // Ping the server to verify connectivity const pong = await client.ping(); console.log(pong); // "pong" ``` ### Response #### Success Response (200) - **pong** (string) - Indicates successful connection. ``` -------------------------------- ### Get File View - Appwrite SDK for Web Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/storage/get-file-view.md Use this snippet to get a view of a file from your Appwrite storage. Ensure you have initialized the Appwrite client and storage service before calling this function. The token parameter is optional and can be used for temporary access. ```javascript import { Client, Storage } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const storage = new Storage(client); const result = storage.getFileView({ bucketId: '', fileId: '', token: '' // optional }); console.log(result); ``` -------------------------------- ### Get Transaction Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/tablesdb/get-transaction.md Fetches a transaction using its unique ID. ```APIDOC ## Get Transaction ### Description Retrieves the details of a specific transaction using its ID. ### Method `getTransaction` ### Parameters #### Input Parameters - **transactionId** (string) - Required - The unique identifier of the transaction to retrieve. ### Request Example ```javascript const result = await tablesDB.getTransaction({ transactionId: '' }); ``` ### Response #### Success Response (200) Returns an object containing the transaction details. #### Response Example ```json { "$id": "60c72b2f96714", "$collectionId": "60c72b2f96714", "$createdAt": "2023-10-27T10:00:00.000+00:00", "$updatedAt": "2023-10-27T10:00:00.000+00:00", "amount": 1000, "currency": "USD", "status": "completed", "description": "Payment for order #123" } ``` ``` -------------------------------- ### Manage Appwrite Teams and Memberships Source: https://context7.com/appwrite/sdk-for-web/llms.txt This snippet demonstrates how to create and manage teams, invite members with specific roles, list all members, update roles, set team preferences, and delete teams or memberships. Ensure the client is initialized. ```javascript import { Client, Teams, ID } from "appwrite"; const client = new Client() .setEndpoint('https://us-east-1.cloud.appwrite.io/v1') .setProject(''); const teams = new Teams(client); // Create a team const team = await teams.create({ teamId: ID.unique(), name: 'Editorial Staff', roles: ['editor', 'reviewer', 'admin'] }); console.log('Team created:', team.$id, team.name); // Invite a member (sends invitation email) const membership = await teams.createMembership({ teamId: team.$id, roles: ['editor'], email: 'alice@example.com', url: 'https://myapp.com/accept-invite' // redirect URL in invitation email }); console.log('Invited:', membership.$id, membership.userEmail); // List all memberships const members = await teams.listMemberships({ teamId: team.$id }); members.memberships.forEach(m => console.log(m.userName, m.roles)); // Update a member's roles await teams.updateMembership({ teamId: team.$id, membershipId: membership.$id, roles: ['editor', 'reviewer'] }); // Save team-level preferences await teams.updatePrefs({ teamId: team.$id, prefs: { theme: 'dark', notificationsEnabled: true } }); // Remove a member await teams.deleteMembership({ teamId: team.$id, membershipId: membership.$id }); // Delete the team await teams.delete({ teamId: team.$id }); ``` -------------------------------- ### Get Transaction Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/databases/get-transaction.md Fetches a transaction using its unique ID. ```APIDOC ## Get Transaction ### Description Retrieves a specific transaction by its ID. ### Method `getTransaction` ### Parameters #### Path Parameters - **transactionId** (string) - Required - The ID of the transaction to retrieve. ### Request Example ```javascript const result = await databases.getTransaction({ transactionId: '' }); ``` ### Response #### Success Response (200) - **transaction** (object) - The transaction object. #### Response Example ```json { "$id": "60c72b2f96714", "$collectionId": "60c72b2f96714", "$databaseId": "60c72b2f96714", "amount": 1000, "currency": "USD", "status": "completed", "createdAt": "2023-10-27T10:00:00.000+00:00", "updatedAt": "2023-10-27T10:05:00.000+00:00" } ``` ``` -------------------------------- ### Create User Account - JavaScript Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/account/create.md Use this snippet to create a new user account. Ensure you have initialized the Appwrite client with your project details and API endpoint. ```javascript import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const account = new Account(client); const result = await account.create({ userId: '', email: 'email@example.com', password: '', name: '' // optional }); console.log(result); ``` -------------------------------- ### List Currencies using Appwrite SDK for Web Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/locale/list-currencies.md Initialize the Appwrite client and use the Locale service to fetch a list of currencies. Ensure you replace placeholders with your actual API endpoint and project ID. ```javascript import { Client, Locale } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const locale = new Locale(client); const result = await locale.listCurrencies(); console.log(result); ``` -------------------------------- ### Get Team Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/teams/get.md This snippet shows how to retrieve a team using the `teams.get` method. ```APIDOC ## Get Team ### Description Retrieves a team using its unique ID. ### Method `teams.get(teamId: string)` ### Parameters #### Path Parameters - **teamId** (string) - Required - The unique ID of the team to retrieve. ### Request Example ```javascript const result = await teams.get({ teamId: '' }); ``` ### Response #### Success Response (200) - **$id** (string) - The team's unique ID. - **name** (string) - The team's name. - **createdAt** (string) - The date the team was created. - **updatedAt** (string) - The date the team was last updated. - **membersCount** (integer) - The number of members in the team. - **total** (integer) - The total number of teams available in the response. #### Response Example ```json { "$id": "60a9b0f1b1f1f1f1f1f1f1f1", "name": "Team Alpha", "createdAt": "2023-01-01T12:00:00.000+00:00", "updatedAt": "2023-01-01T12:00:00.000+00:00", "membersCount": 5, "total": 1 } ``` ``` -------------------------------- ### Get Session Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/account/get-session.md Retrieves the details of a specific user session using its ID. ```APIDOC ## Get Session ### Description Retrieves the details of a specific user session using its ID. ### Method POST ### Endpoint /account/sessions ### Parameters #### Request Body - **sessionId** (string) - Required - The ID of the session to retrieve. ### Request Example ```json { "sessionId": "" } ``` ### Response #### Success Response (200) - **$id** (string) - The unique identifier for the session. - **userId** (string) - The ID of the user associated with the session. - **provider** (string) - The authentication provider used for the session (e.g., 'email', 'google'). - **providerUid** (string) - The unique identifier from the provider. - **providerAccessToken** (string) - The access token from the provider. - **providerAccessTokenExpiry** (string) - The expiration time of the provider access token. - **providerRefreshToken** (string) - The refresh token from the provider. - **userAgent** (string) - The user agent string of the device that created the session. - **ip** (string) - The IP address from which the session was created. - **osName** (string) - The name of the operating system. - **osVersion** (string) - The version of the operating system. - **clientName** (string) - The name of the client (e.g., 'Chrome', 'Firefox'). - **clientVersion** (string) - The version of the client. - **clientEngine** (string) - The rendering engine of the client (e.g., 'Blink', 'Gecko'). - **clientEngineVersion** (string) - The version of the client engine. - **deviceName** (string) - The name of the device. - **deviceBrand** (string) - The brand of the device. - **deviceFamily** (string) - The family of the device. - **countryCode** (string) - The ISO 3166-1 alpha-2 country code. - **country** (string) - The name of the country. - **region** (string) - The name of the region. - **city** (string) - The name of the city. - **createdAt** (string) - The date and time the session was created. #### Response Example ```json { "$id": "63a7c1f7d4b1e3a7f0f0", "userId": "63a7c1f7d4b1e3a7f0f0", "provider": "email", "providerUid": "", "providerAccessToken": "", "providerAccessTokenExpiry": "", "providerRefreshToken": "", "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36", "ip": "127.0.0.1", "osName": "Windows", "osVersion": "10", "clientName": "Chrome", "clientVersion": "108.0.0.0", "clientEngine": "Blink", "clientEngineVersion": "108.0.0.0", "deviceName": "Desktop", "deviceBrand": "Other", "deviceFamily": "Other", "countryCode": "US", "country": "United States", "region": "California", "city": "San Francisco", "createdAt": "2023-01-01T12:00:00.000+00:00" } ``` ``` -------------------------------- ### Execute a GraphQL Query Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/graphql/query.md Initialize the Appwrite client and execute a GraphQL query. Ensure you replace placeholders with your actual API endpoint and project ID. ```javascript import { Client, Graphql } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const graphql = new Graphql(client); const result = await graphql.query({ query: {} }); console.log(result); ``` -------------------------------- ### List Transactions using Appwrite SDK Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/databases/list-transactions.md Initialize the Appwrite client and then use the Databases service to list all transactions. Replace placeholders with your actual API endpoint and project ID. ```javascript import { Client, Databases } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const databases = new Databases(client); const result = await databases.listTransactions({ queries: [] // optional }); console.log(result); ``` -------------------------------- ### Disable MFA Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/account/update-mfa.md This example demonstrates how to disable Multi-Factor Authentication for the current user account. ```APIDOC ## Disable MFA ### Description Disables Multi-Factor Authentication for the current user. ### Method `account.updateMFA` ### Parameters #### Request Body - **mfa** (boolean) - Required - Set to `false` to disable MFA. ### Request Example ```json { "mfa": false } ``` ### Response #### Success Response (200) Returns the updated user object. #### Response Example ```json { "$id": "60a9b0f1e1f1f1f1f1f1f1f1", "name": "John Doe", "email": "john.doe@example.com", "registration": "2023-01-01T12:00:00.000+00:00", "prefs": {}, "mfa": false, "mfaLevel": "none" } ``` ``` -------------------------------- ### Get Image Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/avatars/get-image.md Retrieves an image from a given URL. You can optionally specify the width and height for resizing. ```APIDOC ## GET /avatars/image ### Description Retrieves an image from a given URL. You can optionally specify the width and height for resizing. ### Method GET ### Endpoint /avatars/image ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the image to retrieve. - **width** (integer) - Optional - The desired width of the image. - **height** (integer) - Optional - The desired height of the image. ### Response #### Success Response (200) - **image** (string) - The image data in base64 format. ``` -------------------------------- ### Realtime Service - Event Subscriptions Source: https://context7.com/appwrite/sdk-for-web/llms.txt Explains how to establish real-time connections, subscribe to various events (database documents, files, account changes), and manage subscriptions using the Appwrite Realtime service. ```APIDOC ## Realtime Service - Event Subscriptions ### Description The `Realtime` service enables live event subscriptions through a persistent WebSocket connection. It allows clients to receive server-sent events for changes in databases, storage, function executions, account activities, and team memberships in real-time. The `Channel` builder facilitates type-safe channel descriptors for subscriptions. ### Methods #### `subscribe` Subscribes to real-time events on specified channels. Can include server-side query filtering. - **Parameters**: - `channel` (Channel) - Required - The channel descriptor to subscribe to. - `callback` (function) - Required - A callback function to handle incoming events. - `queries` (Array) - Optional - Server-side queries to filter events. #### `unsubscribe` Unsubscribes from a specific real-time subscription. - **Parameters**: - `subscriptionId` (string) - Required - The ID of the subscription to unsubscribe from. #### `update` Updates the channels or queries for an existing subscription without reconnecting. - **Parameters**: - `subscriptionId` (string) - Required - The ID of the subscription to update. - `channels` (Array) - Optional - New channels to subscribe to. - `queries` (Array) - Optional - New queries to filter events. #### `disconnect` Disconnects the Realtime service from the server, closing all active subscriptions. ### Connection Lifecycle Hooks - **`onOpen(callback)`**: Registers a callback function to be executed when the Realtime connection is successfully opened. - **`onClose(callback)`**: Registers a callback function to be executed when the Realtime connection is closed. - **`onError(callback)`**: Registers a callback function to be executed when an error occurs during the Realtime connection. ### Example Usage ```javascript import { Client, Realtime, Channel, Query } from "appwrite"; const client = new Client() .setEndpoint('https://us-east-1.cloud.appwrite.io/v1') .setProject(''); const realtime = new Realtime(client); // Connection lifecycle hooks realtime.onOpen(() => console.log('Realtime connected')); realtime.onClose(() => console.log('Realtime disconnected')); realtime.onError((err, code) => console.error('Realtime error', code, err?.message)); // Subscribe to all document changes in a collection const sub1 = await realtime.subscribe( Channel.database('blog-db').collection('posts').document(), (event) => { console.log('Document event:', event.events, event.payload); } ); // Subscribe to a specific document const sub2 = await realtime.subscribe( Channel.database('blog-db').collection('posts').document('post-123'), (event) => console.log('Post updated:', event.payload) ); // Subscribe to file events in a bucket const sub3 = await realtime.subscribe( Channel.bucket('profile-photos').file(), (event) => console.log('File event:', event.events[0]) ); // Subscribe to the current user's account events const sub4 = await realtime.subscribe( Channel.account(), (event) => console.log('Account changed:', event.events) ); // Subscribe with server-side query filtering const sub5 = await realtime.subscribe( Channel.database('blog-db').collection('posts').document(), (event) => console.log('Filtered event:', event.payload), [Query.equal('status', 'published')] ); // Update a subscription await sub1.update({ queries: [Query.equal('status', 'draft')] }); // Unsubscribe from a single subscription await sub1.unsubscribe(); // Disconnect all subscriptions await realtime.disconnect(); ``` ``` -------------------------------- ### Get User Preferences Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/account/get-prefs.md Fetches the current user's preferences. This method does not require any parameters. ```APIDOC ## GET /account/prefs ### Description Retrieves the user's preferences. ### Method GET ### Endpoint /account/prefs ### Response #### Success Response (200) - **prefs** (object) - User preferences object. ### Response Example ```json { "prefs": { "exampleKey": "exampleValue" } } ``` ``` -------------------------------- ### List Files in a Bucket - Web SDK Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/storage/list-files.md Use this snippet to list files in a specific bucket. Ensure you have initialized the Appwrite client and storage service. Optional parameters like queries, search, and total count can be provided. ```javascript import { Client, Storage } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const storage = new Storage(client); const result = await storage.listFiles({ bucketId: '', queries: [], // optional search: '', // optional total: false // optional }); console.log(result); ``` -------------------------------- ### List Account Logs Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/account/list-logs.md Use the `listLogs` method to retrieve account logs. Ensure you have initialized the Appwrite client with your endpoint and project ID. The `queries` and `total` parameters are optional. ```javascript import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint .setProject(''); // Your project ID const account = new Account(client); const result = await account.listLogs({ queries: [], // optional total: false // optional }); console.log(result); ``` -------------------------------- ### Get Browser Icon Source: https://github.com/appwrite/sdk-for-web/blob/main/docs/examples/avatars/get-browser.md Retrieves the URL of a browser icon. You can specify the icon code, dimensions, and quality. ```APIDOC ## GET /avatars/browser ### Description Retrieves the URL of a browser icon. You can specify the icon code, dimensions, and quality. ### Method GET ### Endpoint /avatars/browser ### Parameters #### Query Parameters - **code** (string) - Required - Browser code. Use one of the constants from `Browser` class, e.g. `Browser.AvantBrowser`. - **width** (integer) - Optional - Width of the image in pixels. Defaults to 100. - **height** (integer) - Optional - Height of the image in pixels. Defaults to 100. - **quality** (integer) - Optional - Quality of the image. Defaults to 100. Minimum is 0, maximum is 100. ### Response #### Success Response (200) - **url** (string) - URL of the browser icon. ```