### Install InsForge SDK Source: https://docs.insforge.dev/core-concepts/authentication/sdk Installs the InsForge SDK using npm. This is the initial step to integrate the SDK into your project. ```bash npm install @insforge/sdk ``` -------------------------------- ### Installation Source: https://docs.insforge.dev/core-concepts/database/sdk Install the InsForge SDK using npm, yarn, or pnpm. ```APIDOC ## Installation Install the InsForge SDK using your preferred package manager: ### npm ```bash npm install @insforge/sdk ``` ### yarn ```bash yarn add @insforge/sdk ``` ### pnpm ```bash pnpm install @insforge/sdk ``` ``` -------------------------------- ### Verify MCP Installation with AI Prompts Source: https://docs.insforge.dev/mcp-installation Tests the MCP connection by prompting the AI assistant to perform database operations. These examples check if the AI can list tables or create new ones, confirming the MCP integration. ```text "Using Insforge MCP, show me what database tables exist" ``` ```text "Create a new table called 'test_mcp' with id and name fields" ``` -------------------------------- ### Install Insforge CLI Client (NPM) Source: https://docs.insforge.dev/quickstart Installs the Insforge CLI client for connecting your AI agent to your Insforge backend. It automatically includes your API key and base URL. ```bash npx @insforge/install --client cursor \ --env API_KEY=ik_d02a35cfd8056c18e9e59b34bf8bf773 \ --env API_BASE_URL=https://your-app.us-east.insforge.app ``` -------------------------------- ### Storage Bucket List Example (Array) Source: https://docs.insforge.dev/api-reference/admin/list-all-buckets An example demonstrating the format of the bucket names returned in the API response. ```json [ "avatars", "documents", "uploads" ] ``` -------------------------------- ### Quick MCP Installation for AI Tools Source: https://docs.insforge.dev/mcp-installation Installs the Insforge MCP server for AI tools using an npm command. It automatically includes your API key and base URL for seamless integration. Replace '[your-tool]' with the specific AI client. ```bash npx @insforge/install --client cursor \ --env API_KEY=ik_d02a35cfd8056c18e9e59b34bf8bf773 \ --env API_BASE_URL=https://trqnn5z3.us-east.insforge.app ``` -------------------------------- ### Manual MCP Server Installation Source: https://docs.insforge.dev/mcp-installation Installs the Insforge MCP server globally using npm. This is a prerequisite for manual configuration in AI tools that support direct MCP setup. ```bash npm install -g @insforge/mcp-server ``` -------------------------------- ### Install InsForge SDK using npm Source: https://docs.insforge.dev/core-concepts/storage/sdk Installs the InsForge SDK package using npm. This is the first step to integrate InsForge file storage into your project. ```bash npm install @insforge/sdk ``` -------------------------------- ### Query Translation Example: GET request to products API Source: https://docs.insforge.dev/core-concepts/database/architecture Demonstrates how an HTTP GET request with query parameters is translated into an optimized SQL SELECT statement. This showcases PostgREST's ability to interpret filter conditions like 'greater than or equal to' and 'equals' into SQL clauses. ```HTTP GET /api/database/records/products?price=gte.100&category=eq.electronics ``` ```SQL SELECT * FROM products WHERE price >= 100 AND category = 'electronics' ``` -------------------------------- ### API Authentication Response Example (JSON) Source: https://docs.insforge.dev/api-reference/client/user-login Example of a successful API authentication response, including user details and an access token. This JSON structure is typically returned after a user successfully logs in or registers. ```json { "user": { "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "email": "", "name": "", "emailVerified": true, "createdAt": "2023-11-07T05:31:56Z", "updatedAt": "2023-11-07T05:31:56Z" }, "accessToken": "" } ``` -------------------------------- ### PostgREST Query Syntax: Operators and Examples Source: https://docs.insforge.dev/core-concepts/database/architecture Illustrates various PostgREST operators that map directly to SQL equivalents for filtering data. Examples show how to use operators like 'eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'like', 'ilike', 'in', and 'is' in API request URLs. ```HTTP GET /api/database/records/users?id=eq.123 ``` ```HTTP GET /api/database/records/orders?status=neq.deleted ``` ```HTTP GET /api/database/records/profiles?age=gt.18 ``` ```HTTP GET /api/database/records/products?price=gte.100 ``` ```HTTP GET /api/database/records/events?created=lt.2024-01-01 ``` ```HTTP GET /api/database/records/inventory?quantity=lte.10 ``` ```HTTP GET /api/database/records/customers?name=like.*john* ``` ```HTTP GET /api/database/records/emails?email=ilike.*gmail* ``` ```HTTP GET /api/database/records/tasks?status=in.(active,pending) ``` ```HTTP GET /api/database/records/appointments?deleted_at=is.null ``` -------------------------------- ### Complex Query Example Source: https://docs.insforge.dev/core-concepts/database/sdk This example demonstrates a complex query combining multiple filters and ordering. It selects products from the 'electronics' category that are either on sale or have a rating greater than or equal to 4.5, ordered by price. ```javascript // Products on sale OR highly rated const { data, error } = await insforge.database .from('products') .select() .eq('category', 'electronics') .or('on_sale.eq.true,rating.gte.4.5') .order('price', { ascending: true }) ``` -------------------------------- ### Counting and Pagination Source: https://docs.insforge.dev/core-concepts/database/sdk This example demonstrates how to retrieve data with an exact count and paginate results. It fetches the first 10 products that are in stock and logs the number of items displayed versus the total count. ```javascript // Get data with exact count const { data, count, error } = await insforge.database .from('products') .select('*', { count: 'exact' }) .eq('in_stock', true) .range(0, 9) // First 10 items console.log(`Showing ${data.length} of ${count} products`) ``` -------------------------------- ### API Response Example Source: https://docs.insforge.dev/api-reference/admin/update-table-schema Example of a successful response when a table schema is updated. It confirms the operation and lists the changes made. ```json { "message": "Table schema updated successfully", "tableName": "posts", "operations": [ "added 2 columns", "dropped 1 columns", "renamed 1 columns", "added 1 foreign keys", "dropped 1 foreign keys" ] } ``` -------------------------------- ### Example JSON Response Structure Source: https://docs.insforge.dev/api-reference/client/query-records This JSON structure represents a typical response containing a list of records from the database. Each record includes an ID, name, email, and timestamps for creation and updates. This serves as an example of the data format returned by the API. ```json [ { "id": "248373e1-0aea-45ce-8844-5ef259203749", "name": "John Doe", "email": "john@example.com", "createdAt": "2025-07-18T05:37:24.338Z", "updatedAt": "2025-07-18T05:37:24.338Z" }, { "id": "348373e1-0aea-45ce-8844-5ef259203750", "name": "Jane Smith", "email": "jane@example.com", "createdAt": "2025-07-19T08:15:10.123Z", "updatedAt": "2025-07-19T08:15:10.123Z" } ] ``` -------------------------------- ### API Response for Table Creation (JSON) Source: https://docs.insforge.dev/api-reference/admin/create-table Example JSON response indicating successful table creation. It includes a success message and the name of the created table. ```json { "message": "Table created successfully", "tableName": "posts" } ``` -------------------------------- ### Protected API Call Example Source: https://docs.insforge.dev/core-concepts/authentication/sdk Demonstrates making a protected API call to the database. The SDK automatically includes authentication tokens in the request headers. ```javascript // No need to manually add Authorization header const { data, error } = await insforge.database .from('posts') .insert({ title: 'My Post', content: 'This is automatically authenticated' }) .select() ``` -------------------------------- ### Authorization Header Example Source: https://docs.insforge.dev/api-reference/admin/delete-users-admin-only This example shows the format for the Bearer authentication token required for accessing protected API endpoints. The token must be included in the 'Authorization' header. ```http Authorization: Bearer ``` -------------------------------- ### Troubleshooting Connection Timeout Source: https://docs.insforge.dev/mcp-installation Provides steps to diagnose and resolve connection timeouts when using Insforge MCP. It includes checking internet connection, Docker status, and testing the backend health directly. ```bash curl [API_BASE_URL]/health ``` -------------------------------- ### React Streaming Chat Example Source: https://docs.insforge.dev/core-concepts/ai/sdk Demonstrates how to handle streaming chat responses within a React component. It updates the UI in real-time as the AI generates the response. ```javascript import { useState } from 'react'; import { createClient } from '@insforge/sdk'; const insforge = createClient({ baseUrl: 'https://your-app.us-east.insforge.app' }); function ChatInterface() { const [response, setResponse] = useState(''); const [loading, setLoading] = useState(false); const handleChat = async (message) => { setLoading(true); setResponse(''); const stream = await insforge.ai.chat.completions.create({ model: 'anthropic/claude-3.5-haiku', message, stream: true }); for await (const event of stream) { if (event.chunk) { setResponse(prev => prev + event.chunk); } if (event.done) { setLoading(false); } } }; return (
{loading ? 'Thinking...' : response}
); } ``` -------------------------------- ### Handle Avatar Upload with Preview Source: https://docs.insforge.dev/core-concepts/storage/sdk A complete example demonstrating how to handle avatar uploads, including displaying a preview of the selected image and updating the user's profile with the new avatar URL. It uses `uploadAuto` for convenience. ```javascript async function handleAvatarUpload(fileInput) { const file = fileInput.files[0]; // Show preview const reader = new FileReader(); reader.onload = (e) => { document.getElementById('preview').src = e.target.result; }; reader.readAsDataURL(file); // Upload file const { data, error } = await insforge.storage .from('avatars') .uploadAuto(file) if (error) { console.error('Upload failed:', error); return; } // Update user profile with new avatar URL const { error: updateError } = await insforge.auth.setProfile({ avatar_url: data.url }) if (!updateError) { console.log('Avatar updated successfully!'); } } ``` -------------------------------- ### API GET Request for Database Records Source: https://docs.insforge.dev/api-reference/client/query-records This section details the GET request to the /api/database/records/{tableName} endpoint. It explains the path parameter 'tableName' and various query parameters like 'limit', 'offset', 'order', 'select', and 'field' for filtering and sorting records. Authorization via Bearer token is also mentioned. ```http GET /api/database/records/{tableName} --- #### Authorizations bearerAuth #### Path Parameters tableName string required Name of the table to query #### Query Parameters limit integer default:100 Maximum number of records to return Required range: `1 <= x <= 1000` offset integer default:0 Number of records to skip for pagination Required range: `x >= 0` order string Sort order (e.g., "createdAt.desc", "name.asc") select string Comma-separated list of columns to return field string Filter by field value (e.g., "?status=eq.active", "?age=gt.18") #### Response 200 application/json List of records ``` -------------------------------- ### GET /api/database/tables Source: https://docs.insforge.dev/api-reference/admin/list-tables Retrieves a list of all available table names in the database. ```APIDOC ## GET /api/database/tables ### Description Retrieves a list of all available table names in the database. ### Method GET ### Endpoint /api/database/tables ### Parameters #### Query Parameters #### Request Body ### Request Example ### Response #### Success Response (200) - **tables** (string[]) - List of table names #### Response Example ```json [ "users", "posts", "comments", "categories" ] ``` #### Authorizations - **bearerAuth**: Bearer authentication header of the form `Bearer `, where `` is your auth token. ``` -------------------------------- ### Cursor MCP Configuration via Composer File Source: https://docs.insforge.dev/mcp-installation Manually configures Insforge MCP for Cursor by adding a rule to the `.cursorrules` file. This informs Cursor about the Insforge backend's location and its capabilities. ```text You have access to Insforge backend at https://your-app.us-east.insforge.app Use the MCP tools to interact with the database, auth, and storage. ``` -------------------------------- ### Monitor Token Usage and Costs with Insforge Source: https://docs.insforge.dev/core-concepts/ai/sdk Demonstrates how to retrieve and log token usage information from AI model responses. This is crucial for cost management and understanding API interaction efficiency. The example logs prompt tokens, completion tokens, and total tokens. ```javascript const { data, error } = await insforge.ai.chat.completions.create({ model: 'openai/gpt-4', message: 'Explain quantum computing' }); if (data) { console.log('Token usage:', { promptTokens: data.usage?.promptTokens, completionTokens: data.usage?.completionTokens, totalTokens: data.usage?.totalTokens }); } ``` -------------------------------- ### Claude Desktop MCP Configuration Source: https://docs.insforge.dev/mcp-installation Configures the Insforge MCP server for Claude Desktop by editing its JSON configuration file. It specifies the command, arguments, and environment variables for the MCP server. ```json { "mcpServers": { "insforge": { "command": "npx", "args": ["-y", "@insforge/mcp-server"], "env": { "API_KEY": "your-api-key", "API_BASE_URL": "https://your-app.us-east.insforge.app" } } } } ``` -------------------------------- ### PostgREST Query Syntax: Complex Queries Source: https://docs.insforge.dev/core-concepts/database/architecture Shows how to construct complex queries in PostgREST by combining multiple conditions using 'AND', 'OR', and nested logic. These examples demonstrate advanced filtering capabilities for more sophisticated data retrieval. ```HTTP GET /api/database/records/products?price=gte.100&category=eq.electronics ``` ```HTTP GET /api/database/records/products?or=(price.lt.50,on_sale.is.true) ``` ```HTTP GET /api/database/records/orders?and=(status.eq.pending,or=(priority.eq.high,created_at.lt.2024-01-01)) ``` -------------------------------- ### Cline (VS Code) MCP Server Configuration Source: https://docs.insforge.dev/mcp-installation Adds a new MCP server configuration for Insforge within the Cline extension settings in VS Code. This allows Cline to connect to the MCP server using specified command and environment variables. ```json { "insforge": { "command": "npx", "args": ["-y", "@insforge/mcp-server"], "env": { "API_KEY": "your-api-key", "API_BASE_URL": "https://your-app.us-east.insforge.app" } } } ``` -------------------------------- ### Image Upload and Profile Update using JavaScript Source: https://docs.insforge.dev/core-concepts/storage/overview Provides a comprehensive example of uploading an image to InsForge and then updating a user's profile with the image URL. This involves two separate API calls: one for the file upload and another for the database record update. ```javascript // Image upload with preview async function uploadAvatar(file) { const formData = new FormData(); formData.append('file', file); const res = await fetch('/api/storage/buckets/avatars/objects', { method: 'POST', headers: { 'Authorization': `Bearer ${token}` }, body: formData }); const { url } = await res.json(); // Save URL to user profile await fetch('/api/database/records/profiles', { method: 'PATCH', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ avatar_url: url }) }); return url; } ``` -------------------------------- ### Create New Project Directory Source: https://docs.insforge.dev/quickstart Creates a new directory for your application and navigates into it. This is a standard command-line operation for setting up a new project environment. ```bash mkdir my-app cd my-app ``` -------------------------------- ### Basic Sign Up with Name Source: https://docs.insforge.dev/core-concepts/authentication/sdk Performs a basic user sign-up using email and password. It returns user data and an access token upon successful registration. ```javascript const { data, error } = await insforge.auth.signUp({ email: 'user@example.com', password: 'secure_password123' }) // Returns: { data: { user, accessToken }, error } ``` -------------------------------- ### Best Practices Source: https://docs.insforge.dev/core-concepts/database/sdk Follow these best practices for optimal SDK usage. ```APIDOC ## Best Practices - **Handle Errors**: Always check the `error` object from every database operation. - **Use `.select()`**: Append `.select()` to `INSERT`, `UPDATE`, and `DELETE` operations to retrieve the affected records. - **Batch Operations**: When possible, insert multiple records in a single call to improve efficiency. ``` -------------------------------- ### Initialize InsForge Client Source: https://docs.insforge.dev/core-concepts/authentication/sdk Initializes the InsForge client with your application's base URL. This client instance is used for all subsequent SDK operations. ```javascript import { createClient } from '@insforge/sdk'; const insforge = createClient({ baseUrl: 'https://your-app.us-east.insforge.app' }); ``` -------------------------------- ### Initiate OAuth Sign In Source: https://docs.insforge.dev/core-concepts/authentication/sdk Initiates the sign-in process with an OAuth provider like Google. The SDK automatically handles the callback after redirection. ```javascript // Redirects to Google OAuth await insforge.auth.signInWithOAuth({ provider: 'google', redirectTo: 'http://localhost:3000/dashboard' }) // SDK automatically detects and handles the OAuth callback ``` -------------------------------- ### Client Initialization Source: https://docs.insforge.dev/core-concepts/database/sdk Initialize the InsForge client with your application's base URL. ```APIDOC ## Client Initialization Initialize the InsForge client by providing your application's base URL. ### Code Example ```javascript import { createClient } from '@insforge/sdk'; const insforge = createClient({ baseUrl: 'https://your-app.us-east.insforge.app' }); ``` ``` -------------------------------- ### GET /api/auth/sessions/current Source: https://docs.insforge.dev/api-reference/client/get-current-user Retrieves the details of the currently authenticated user session. ```APIDOC ## GET /api/auth/sessions/current ### Description Retrieves the details of the currently authenticated user session. ### Method GET ### Endpoint /api/auth/sessions/current ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **user** (object) - Contains user information including id, email, name, and role. #### Response Example ```json { "user": { "id": "", "email": "", "name": "", "role": "" } } ``` #### Error Response (401) Unauthorized ``` -------------------------------- ### POST /api/auth/users Source: https://docs.insforge.dev/api-reference/client/register-new-user Registers a new user with the provided details. ```APIDOC ## POST /api/auth/users ### Description Registers a new user with the provided details. ### Method POST ### Endpoint /api/auth/users ### Parameters #### Request Body - **email** (string) - required - User's email address. - **password** (string) - required - User's password (minimum 8 characters). - **name** (string) - optional - User's full name. ### Request Example ```json { "email": "user@example.com", "password": "securepassword123", "name": "John Doe" } ``` ### Response #### Success Response (201) - **user** (object) - Information about the created user. - **id** (string) - User's unique identifier. - **email** (string) - User's email address. - **name** (string) - User's full name. - **emailVerified** (boolean) - Indicates if the user's email has been verified. - **createdAt** (string) - Timestamp of user creation. - **updatedAt** (string) - Timestamp of last user update. - **accessToken** (string) - JWT authentication token for the newly created user. #### Response Example ```json { "user": { "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "email": "user@example.com", "name": "John Doe", "emailVerified": false, "createdAt": "2023-11-07T05:31:56Z", "updatedAt": "2023-11-07T05:31:56Z" }, "accessToken": "" } ``` ``` -------------------------------- ### Get Table Schema Source: https://docs.insforge.dev/api-reference/admin/get-table-schema Retrieves the schema for a specified table in the database. ```APIDOC ## GET /api/database/tables/{tableName} ### Description Retrieves the schema for a specified table in the database. This endpoint allows you to inspect the structure of a table, including its columns, data types, constraints, and relationships. ### Method GET ### Endpoint /api/database/tables/{tableName} ### Parameters #### Path Parameters - **tableName** (string) - Required - The name of the table for which to retrieve the schema. ### Request Example ```json { "example": "This endpoint does not require a request body." } ``` ### Response #### Success Response (200) - **tableName** (string) - The name of the table. - **columns** (object[]) - An array of objects, where each object describes a column in the table. Each column object may contain fields like `name`, `type`, `nullable`, `unique`, `isPrimaryKey`, and `foreignKey` details. #### Response Example ```json { "tableName": "posts", "columns": [ { "name": "id", "type": "uuid", "nullable": false, "unique": true, "isPrimaryKey": true, "foreignKey": null }, { "name": "title", "type": "string", "nullable": false, "unique": false, "isPrimaryKey": false, "foreignKey": null }, { "name": "userId", "type": "uuid", "nullable": false, "unique": false, "isPrimaryKey": false, "foreignKey": { "table": "users", "column": "id", "on_delete": "CASCADE" } } ] } ``` #### Error Responses - **404** - Table not found. ``` -------------------------------- ### Get Current Authenticated User Source: https://docs.insforge.dev/core-concepts/authentication/sdk Retrieves the currently logged-in user's authentication details and profile information. ```javascript // Gets current authenticated user with profile const { data, error } = await insforge.auth.getCurrentUser() if (data) { console.log('Auth info:', data.user) // { id, email, role } console.log('Profile:', data.profile) // { nickname, avatar_url, bio, ... } } ``` -------------------------------- ### GET /api/auth/users Source: https://docs.insforge.dev/api-reference/admin/list-all-users-admin-only Retrieves a list of users with optional filtering and pagination. Requires Bearer token authentication. ```APIDOC ## GET /api/auth/users ### Description Retrieves a list of users. Supports pagination via `page` and `limit` query parameters, and filtering by `search` and `role`. ### Method GET ### Endpoint /api/auth/users ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination. Defaults to 1. - **limit** (integer) - Optional - The number of results per page. Defaults to 10. - **search** (string) - Optional - A search term to filter users by name or email. - **role** (enum) - Optional - Filters users by their role. Available options: `user`, `admin`. #### Request Body None ### Response #### Success Response (200) - **data** (object[]) - An array of user objects, each containing `id`, `email`, `name`, `role`, and `created_at`. - **pagination** (object) - An object containing `offset`, `limit`, and `total` for pagination information. #### Response Example ```json { "data": [ { "id": "", "email": "", "name": "", "role": "", "created_at": "2023-11-07T05:31:56Z" } ], "pagination": { "offset": 123, "limit": 123, "total": 123 } } ``` ``` -------------------------------- ### POST /api/auth/sessions Source: https://docs.insforge.dev/api-reference/client/user-login Creates a new user session by providing email and password. Returns user information and an access token upon successful authentication. ```APIDOC ## POST /api/auth/sessions ### Description Creates a new user session by providing email and password. Returns user information and an access token upon successful authentication. ### Method POST ### Endpoint /api/auth/sessions ### Parameters #### Request Body - **email** (string, email) - required - The user's email address. - **password** (string) - required - The user's password. ### Request Example ```json { "email": "", "password": "" } ``` ### Response #### Success Response (200) - **user** (object) - User details including id, email, name, emailVerified, createdAt, and updatedAt. - **accessToken** (string) - The access token for the authenticated session. #### Response Example ```json { "user": { "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "email": "", "name": "", "emailVerified": true, "createdAt": "2023-11-07T05:31:56Z", "updatedAt": "2023-11-07T05:31:56Z" }, "accessToken": "" } ``` ``` -------------------------------- ### GET /api/database/records/{tableName} Source: https://docs.insforge.dev/api-reference/client/query-records Retrieves records from a specified database table. Supports pagination, sorting, filtering, and column selection. ```APIDOC ## GET /api/database/records/{tableName} ### Description Retrieves records from a specified database table. Supports pagination, sorting, filtering, and column selection. ### Method GET ### Endpoint /api/database/records/{tableName} ### Parameters #### Path Parameters - **tableName** (string) - Required - Name of the table to query #### Query Parameters - **limit** (integer) - Optional - Default: 100. Maximum number of records to return. Required range: `1 <= x <= 1000` - **offset** (integer) - Optional - Default: 0. Number of records to skip for pagination. Required range: `x >= 0` - **order** (string) - Optional - Sort order (e.g., "createdAt.desc", "name.asc") - **select** (string) - Optional - Comma-separated list of columns to return - **field** (string) - Optional - Filter by field value (e.g., "?status=eq.active", "?age=gt.18") ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **object[]** - List of records #### Response Example ```json [ { "id": "248373e1-0aea-45ce-8844-5ef259203749", "name": "John Doe", "email": "john@example.com", "createdAt": "2025-07-18T05:37:24.338Z", "updatedAt": "2025-07-18T05:37:24.338Z" }, { "id": "348373e1-0aea-45ce-8844-5ef259203750", "name": "Jane Smith", "email": "jane@example.com", "createdAt": "2025-07-19T08:15:10.123Z", "updatedAt": "2025-07-19T08:15:10.123Z" } ] ``` #### Authorizations - bearerAuth: Bearer authentication header of the form `Bearer `, where `` is your auth token. ``` -------------------------------- ### GET /api/storage/buckets/{bucketName}/objects Source: https://docs.insforge.dev/api-reference/admin/list-objects-in-bucket Retrieves a list of objects stored within a specified bucket. Supports filtering by prefix and pagination. ```APIDOC ## GET /api/storage/buckets/{bucketName}/objects ### Description Retrieves a list of objects stored within a specified bucket. Supports filtering by prefix and pagination. ### Method GET ### Endpoint /api/storage/buckets/{bucketName}/objects ### Parameters #### Path Parameters - **bucketName** (string) - Required - The name of the bucket to list objects from. #### Query Parameters - **prefix** (string) - Optional - Filter objects by key prefix. - **limit** (integer) - Optional - The maximum number of objects to return. Default: 100. Required range: `1 <= x <= 1000`. - **offset** (integer) - Optional - The number of objects to skip. Default: 0. Required range: `x >= 0`. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **data** (object[]) - An array of objects, each containing details like bucket, key, size, mimeType, uploadedAt, and url. - **pagination** (object) - Contains pagination information including offset, limit, and total count. - **nextActions** (string) - Provides information on related actions like uploading or downloading objects. #### Response Example ```json { "data": [ { "bucket": "avatars", "key": "users/user123.jpg", "size": 102400, "mimeType": "image/jpeg", "uploadedAt": "2024-01-15T10:30:00Z", "url": "/api/storage/buckets/avatars/objects/users/user123.jpg" } ], "pagination": { "offset": 0, "limit": 100, "total": 2 }, "nextActions": "You can use PUT /api/storage/buckets/:bucketName/objects/:objectKey to upload with a specific key, or POST /api/storage/buckets/:bucketName/objects to upload with auto-generated key, and GET /api/storage/buckets/:bucketName/objects/:objectKey to download an object." } ``` #### Error Handling (Error details not provided in the source text) ``` -------------------------------- ### Initialize InsForge Client Source: https://docs.insforge.dev/core-concepts/storage/sdk Initializes the InsForge client with your application's base URL. This client instance is then used for all subsequent storage operations. ```javascript import { createClient } from '@insforge/sdk'; const insforge = createClient({ baseUrl: 'https://your-app.us-east.insforge.app' }); ``` -------------------------------- ### Configure Insforge Client with Default Settings Source: https://docs.insforge.dev/core-concepts/ai/sdk Shows how to configure the Insforge client with default AI model and parameters. This includes setting a default model, temperature, and maximum tokens, simplifying subsequent API calls by avoiding repeated parameter specification. ```javascript const insforge = createClient({ baseUrl: 'https://your-app.us-east.insforge.app', ai: { defaultModel: 'anthropic/claude-3.5-haiku', defaultTemperature: 0.7, defaultMaxTokens: 1000 } }); ``` -------------------------------- ### Get Any User's Profile Source: https://docs.insforge.dev/core-concepts/authentication/sdk Fetches the profile information for any user, identified by their user ID. This allows access to public or shared profile data. ```javascript // Get profile by user ID const { data: profile, error } = await insforge.auth.getProfile('user-id-123') console.log(profile) // { id, nickname, avatar_url, bio, birthday, ... } ``` -------------------------------- ### Query All Records from a Table Source: https://docs.insforge.dev/core-concepts/database/sdk This code demonstrates how to fetch all records from a specified table ('products' in this case) using the InsForge SDK. It returns the data and any potential errors encountered during the operation. ```javascript const { data, error } = await insforge.database .from('products') .select() ``` -------------------------------- ### Get Current Session Source: https://docs.insforge.dev/core-concepts/authentication/sdk Retrieves the current session details, including the access token and user information, directly from local storage without an API call. ```javascript // Gets session from local storage (no API call) const { data, error } = await insforge.auth.getCurrentSession() if (data?.session) { console.log('Token:', data.session.accessToken) console.log('User:', data.session.user) } ``` -------------------------------- ### Storage Upload and Download Actions Source: https://docs.insforge.dev/api-reference/admin/list-objects-in-bucket Provides information and endpoints for uploading and downloading objects from storage buckets. ```APIDOC ## Storage Upload and Download Actions ### Description This section details the API endpoints and actions available for managing objects within storage buckets, including uploading objects with specific keys or auto-generated keys, and downloading objects. ### Endpoints for Uploading and Downloading - **Upload with specific key**: `PUT /api/storage/buckets/:bucketName/objects/:objectKey` - **Upload with auto-generated key**: `POST /api/storage/buckets/:bucketName/objects` - **Download object**: `GET /api/storage/buckets/:bucketName/objects/:objectKey` ### Example Usage (from `nextActions` field) ``` You can use PUT /api/storage/buckets/:bucketName/objects/:objectKey to upload with a specific key, or POST /api/storage/buckets/:bucketName/objects to upload with auto-generated key, and GET /api/storage/buckets/:bucketName/objects/:objectKey to download an object. ``` ``` -------------------------------- ### List Users API Endpoint Source: https://docs.insforge.dev/api-reference/admin/list-all-users-admin-only This describes the GET request to the /api/auth/users endpoint, used to retrieve a list of users. It supports query parameters for pagination, searching, and filtering by role. ```http GET /api/auth/users ``` ```json { "data": [ { "id": "", "email": "", "name": "", "role": "", "created_at": "2023-11-07T05:31:56Z" } ], "pagination": { "offset": 123, "limit": 123, "total": 123 } } ``` -------------------------------- ### Build a Chat Application with Insforge AI Source: https://docs.insforge.dev/core-concepts/ai/sdk Demonstrates creating a complete chat interface with conversation history. It includes sending user messages, receiving AI responses, and handling streaming for long outputs. The class manages message history and interacts with the Insforge client. ```javascript class ChatApp { constructor() { this.client = createClient({ baseUrl: 'https://your-app.us-east.insforge.app' }); this.messages = []; } async sendMessage(userInput) { // Add user message to history this.messages.push({ role: 'user', content: userInput }); // Get AI response const { data, error } = await this.client.ai.chat.completions.create({ model: 'anthropic/claude-3.5-haiku', messages: this.messages, temperature: 0.7, maxTokens: 1000 }); if (error) { console.error('Chat error:', error); return null; } // Add assistant response to history this.messages.push({ role: 'assistant', content: data.response }); return data.response; } async streamMessage(userInput) { this.messages.push({ role: 'user', content: userInput }); const stream = await this.client.ai.chat.completions.create({ model: 'anthropic/claude-3.5-haiku', messages: this.messages, stream: true }); let fullResponse = ''; for await (const event of stream) { if (event.chunk) { fullResponse += event.chunk; // Update UI with partial response this.updateUI(event.chunk); } } this.messages.push({ role: 'assistant', content: fullResponse }); return fullResponse; } updateUI(chunk) { // Update your UI with streaming chunk document.getElementById('response').innerHTML += chunk; } clearHistory() { this.messages = []; } } // Usage const chat = new ChatApp(); const response = await chat.sendMessage('Hello!'); ``` -------------------------------- ### S3 Client Configuration and Multi-Tenancy Key Generation (JavaScript) Source: https://docs.insforge.dev/core-concepts/storage/architecture Demonstrates the initialization of an AWS S3 client using the AWS SDK v3 and how to construct an S3 object key that incorporates an application key for multi-tenancy isolation. This code is suitable for Node.js environments. ```javascript // S3 client configuration const s3Client = new S3Client({ region: this.region, // e.g., 'us-east-2' // IAM role credentials are automatically used on EC2 // No explicit credentials needed in production }); // File paths use app key prefix for multi-tenancy const s3Key = `${this.appKey}/${bucket}/${key}`; ``` -------------------------------- ### Generate Image Galleries with Insforge AI Source: https://docs.insforge.dev/core-concepts/ai/sdk Shows how to generate multiple images based on a text prompt and display them in a gallery. It also demonstrates saving generated images to Insforge storage. This function requires a 'gallery' element in the DOM. ```javascript async function createImageGallery(prompt, count = 4) { const { data, error } = await insforge.ai.images.generate({ model: 'google/gemini-2.5-flash-image-preview', prompt, numImages: count, size: '512x512', quality: 'hd' }); if (error) { console.error('Generation failed:', error); return; } // Create gallery HTML const gallery = document.getElementById('gallery'); gallery.innerHTML = ''; data.images.forEach((image, index) => { const img = document.createElement('img'); img.src = image.url; img.alt = `Generated image ${index + 1}`; img.className = 'gallery-image'; gallery.appendChild(img); }); // Save to storage if needed for (const image of data.images) { const response = await fetch(image.url); const blob = await response.blob(); await insforge.storage .from('generated-images') .uploadAuto(blob); } } // Generate gallery await createImageGallery('Cute puppies playing in a garden', 6); ``` -------------------------------- ### Example JSON Response for Deleted Records Source: https://docs.insforge.dev/api-reference/client/delete-records This JSON snippet shows the typical response format when records are successfully deleted and the `return=representation` header is used. It includes the ID, name, and timestamps for the deleted record. ```json [ { "id": "123e4567-e89b-12d3-a456-426614174000", "name": "Deleted User", "createdAt": "2025-01-01T00:00:00Z", "updatedAt": "2025-01-21T11:00:00Z" } ] ``` -------------------------------- ### Chat Completions - Basic Source: https://docs.insforge.dev/core-concepts/ai/sdk Create a chat completion with a simple message. This endpoint allows you to send a single user message and receive a text response from the AI model. ```APIDOC ## POST /ai/chat/completions ### Description Creates a chat completion by sending a user message to the specified AI model. ### Method POST ### Endpoint /ai/chat/completions ### Parameters #### Request Body - **model** (string) - Required - The AI model to use for the chat completion. - **message** (string) - Required - The user's message content. ### Request Example { "model": "anthropic/claude-3.5-haiku", "message": "What is the capital of France?" } ### Response #### Success Response (200) - **response** (string) - The AI model's text response. #### Response Example { "response": "The capital of France is Paris." } ``` -------------------------------- ### Current User Session Endpoint Source: https://docs.insforge.dev/api-reference/client/get-current-user Details the GET request for the '/api/auth/sessions/current' endpoint, which retrieves information about the current user's session. It specifies possible response codes (200, 401) and the format of the response body. ```http GET /api/auth/sessions/current ``` -------------------------------- ### Image Generation Source: https://docs.insforge.dev/core-concepts/ai/sdk Generate images based on a text prompt using various AI models. Supports parameters for size, quality, and style. ```APIDOC ## POST /ai/images/generate ### Description Generates images based on a provided text prompt using specified AI models. You can control various aspects of the image generation process. ### Method POST ### Endpoint /ai/images/generate ### Parameters #### Request Body - **model** (string) - Required - The AI model to use for image generation. - **prompt** (string) - Required - A text description of the desired image. - **negativePrompt** (string) - Optional - Text describing what to avoid in the image. - **size** (string) - Optional - Predefined image size (e.g., '1024x1024'). - **width** (number) - Optional - Custom image width in pixels. - **height** (number) - Optional - Custom image height in pixels. - **numImages** (number) - Optional - The number of images to generate. - **quality** (string) - Optional - Image quality setting ('standard' or 'hd'). - **style** (string) - Optional - Image style preference ('vivid' or 'natural'). - **responseFormat** (string) - Optional - The format of the response ('url' or 'b64_json'). ### Request Example { "model": "google/gemini-2.5-flash-image-preview", "prompt": "A serene landscape with mountains at sunset", "size": "1024x1024", "quality": "hd" } ### Response #### Success Response (200) - **images** (array) - An array of generated image objects, each containing a URL or base64 encoded JSON. - **url** (string) - The URL of the generated image (if responseFormat is 'url'). - **b64_json** (string) - The base64 encoded image data (if responseFormat is 'b64_json'). #### Response Example { "images": [ { "url": "https://example.com/image.png" } ] } ``` -------------------------------- ### JWT Token Payload Example Source: https://docs.insforge.dev/core-concepts/authentication/architecture This JSON object represents the structure of a JWT token payload, including standard claims like subject, email, role, issuance and expiration times, issuer, and audience. These fields are crucial for stateless authentication and authorization. ```json { "sub": "user_id_uuid", "email": "user@example.com", "role": "authenticated", "iat": 1704067200, "exp": 1704672000, "iss": "insforge", "aud": "insforge-api" } ```