### GraphQL Query Example Source: https://flxbl.dev/docs/getting-started Example of querying product data using GraphQL. ```APIDOC ## GraphQL Query ### Description Retrieves product data using a GraphQL query, with options for filtering and limiting results. ### Method POST ### Endpoint `/api/v1/dynamic-gql/:tenantId` (Assumed endpoint for GraphQL) ### Parameters #### Query Parameters None #### Request Body (GraphQL Query) - **query** (string) - The GraphQL query string. - **variables** (object) - Optional - Variables to be used in the query. ### Request Example ```graphql query { products(where: { inStock: true }, limit: 10) { id name price belongsTo { name slug } } } ``` ### Response #### Success Response (200) - **data** (object) - Contains the results of the GraphQL query. - **products** (array) - An array of product objects. - **id** (string) - The unique identifier for the product. - **name** (string) - The name of the product. - **price** (number) - The price of the product. - **belongsTo** (object) - Information about related entities. - **name** (string) - Name of the related entity. - **slug** (string) - Slug of the related entity. #### Response Example ```json { "data": { "products": [ { "id": "prod_789ghi", "name": "Wireless Mouse", "price": 25.50, "belongsTo": { "name": "Electronics", "slug": "electronics" } } ] } } ``` ``` -------------------------------- ### FLXBL SDK and CLI Usage Source: https://flxbl.dev/docs/getting-started Instructions for installing and using the FLXBL SDK and CLI for application development. ```APIDOC ## FLXBL SDK and CLI ### Description Guides users on installing the FLXBL SDK and CLI, and generating a typed client from their schema for application development. ### Method CLI Commands ### Endpoint N/A (Local CLI Operations) ### Parameters None ### Request Example ```bash # Install the SDK and CLI npm install @flxbl-dev/client npm install -g @flxbl-dev/cli # Log in to your FLXBL account via CLI flxbl login # Generate a typed client from your schema flxbl generate ``` ### Response N/A (CLI execution output) ``` -------------------------------- ### Create Data via REST API Source: https://flxbl.dev/docs/getting-started Example of creating a new product entry using the FLXBL REST API. ```APIDOC ## POST /api/v1/dynamic/Product ### Description Creates a new record in the specified dynamic resource (e.g., Product). ### Method POST ### Endpoint `/api/v1/dynamic/Product` ### Parameters #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the product. - **description** (string) - Optional - A description of the product. - **price** (number) - Required - The price of the product. - **inStock** (boolean) - Required - Indicates if the product is currently in stock. ### Request Example ```json { "name": "Wireless Headphones", "description": "Premium noise-canceling headphones", "price": 299.99, "inStock": true } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created product. - **name** (string) - The name of the product. - **description** (string) - The description of the product. - **price** (number) - The price of the product. - **inStock** (boolean) - Indicates if the product is in stock. #### Response Example ```json { "id": "prod_123abc", "name": "Wireless Headphones", "description": "Premium noise-canceling headphones", "price": 299.99, "inStock": true } ``` ``` -------------------------------- ### Install and Generate FLXBL SDK Client Source: https://flxbl.dev/docs/getting-started This snippet shows how to install the FLXBL SDK and CLI using npm and then log in and generate a typed client from your schema. This is an alternative to direct API calls for application development, providing a type-safe TypeScript interface. ```bash # Install the SDK and CLI npm install @flxbl-dev/client npm install -g @flxbl-dev/cli # Generate a typed client from your schema flxbl login flxbl generate ``` -------------------------------- ### Query Data with FLXBL GraphQL Source: https://flxbl.dev/docs/getting-started This example demonstrates querying product data using GraphQL. It fetches products that are in stock, limits the results to 10, and retrieves specific fields like id, name, price, and related 'belongsTo' information. This requires a GraphQL endpoint and proper authentication. ```graphql # GraphQL query query { products(where: { inStock: true }, limit: 10) { id name price belongsTo { name slug } } } ``` -------------------------------- ### Query Data via REST API Source: https://flxbl.dev/docs/getting-started Example of querying product data with filters using the FLXBL Query DSL. ```APIDOC ## POST /api/v1/dynamic/Product/query ### Description Queries records from a dynamic resource using the FLXBL Query DSL. Allows filtering, sorting, and limiting results. ### Method POST ### Endpoint `/api/v1/dynamic/Product/query` ### Parameters #### Query Parameters None #### Request Body - **where** (object) - Optional - Criteria for filtering records. Supports operators like `$lte`, `$eq`. - **price** (object) - Example filter for price. - **$lte** (number) - Less than or equal to. - **inStock** (object) - Example filter for stock status. - **$eq** (boolean) - Equal to. - **orderBy** (string) - Optional - Field to sort the results by. - **orderDirection** (string) - Optional - Direction of sorting ('ASC' or 'DESC'). - **limit** (integer) - Optional - Maximum number of records to return. ### Request Example ```json { "where": { "price": { "$lte": 500 }, "inStock": { "$eq": true } }, "orderBy": "price", "orderDirection": "ASC", "limit": 10 } ``` ### Response #### Success Response (200) - **results** (array) - An array of product objects matching the query. - **id** (string) - The unique identifier for the product. - **name** (string) - The name of the product. - **price** (number) - The price of the product. - **inStock** (boolean) - Indicates if the product is in stock. #### Response Example ```json { "results": [ { "id": "prod_456def", "name": "Bluetooth Speaker", "price": 79.99, "inStock": true } ] } ``` ``` -------------------------------- ### Create Data with FLXBL REST API Source: https://flxbl.dev/docs/getting-started This example demonstrates how to create a new product entry using the FLXBL REST API. It utilizes a POST request with JSON payload, including product details like name, description, price, and stock status. An Authorization header with the API key is required. ```bash // Create a product via REST API curl -X POST https://api.flxbl.dev/api/v1/dynamic/Product \ -H "Authorization: Bearer flxbl_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "name": "Wireless Headphones", "description": "Premium noise-canceling headphones", "price": 299.99, "inStock": true }' ``` -------------------------------- ### Install FLXBL SDK Source: https://flxbl.dev/docs/sdk Installs the FLXBL client package using npm. This is the first step to integrating the SDK into your project. ```bash npm install @flxbl-dev/client ``` -------------------------------- ### Query Data with FLXBL REST API Source: https://flxbl.dev/docs/getting-started This example shows how to query product data using the FLXBL REST API with a POST request. It includes filtering by price and stock status, sorting by price, and limiting the results. The Query DSL is used in the JSON payload, and an Authorization header is necessary. ```bash // Query products with filters curl -X POST https://api.flxbl.dev/api/v1/dynamic/Product/query \ -H "Authorization: Bearer flxbl_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "where": { "price": { "$lte": 500 }, "inStock": { "$eq": true } }, "orderBy": "price", "orderDirection": "ASC", "limit": 10 }' ``` -------------------------------- ### Install FLXBL CLI Source: https://flxbl.dev/docs/cli Installs the FLXBL CLI globally using npm or allows direct execution with npx. This is the first step to using the CLI for managing FLXBL projects. ```bash # Install globally npm install -g @flxbl-dev/cli # Or run directly with npx npx @flxbl-dev/cli ``` -------------------------------- ### Install graphql-ws Package Source: https://flxbl.dev/docs/graphql-subscriptions Installs the necessary `graphql-ws` package using npm. This package is a dependency for establishing WebSocket connections for GraphQL subscriptions. ```bash npm install graphql-ws ``` -------------------------------- ### MCP Integration Configuration Source: https://flxbl.dev/docs/getting-started Configuration to integrate FLXBL's MCP server with your IDE for AI-assisted development. ```APIDOC ## MCP Integration Configuration ### Description This configuration allows AI assistants in your IDE to interact with FLXBL for schema design, code generation, and backend management. ### Method N/A (Configuration File) ### Endpoint N/A (Local IDE Configuration) ### Parameters #### Environment Variables - **FLXBL_INSTANCE_URL** (string) - Required - The base URL for the FLXBL API. - **FLXBL_API_KEY** (string) - Required - Your personal API key from the FLXBL dashboard. ### Request Example ```json { "mcpServers": { "flxbl": { "command": "npx", "args": ["@flxbl-dev/mcp"], "env": { "FLXBL_INSTANCE_URL": "https://api.flxbl.dev", "FLXBL_API_KEY": "flxbl_your_api_key_here" } } } } ``` ### Response N/A (Configuration setup) ``` -------------------------------- ### Configure FLXBL MCP Integration Source: https://flxbl.dev/docs/getting-started This configuration snippet sets up the FLXBL MCP server for AI assistants within an IDE. It requires Node.js and specifies the command, arguments, and environment variables for the MCP integration, including the FLXBL API key. ```json // ~/.cursor/mcp.json { "mcpServers": { "flxbl": { "command": "npx", "args": ["@flxbl-dev/mcp"], "env": { "FLXBL_INSTANCE_URL": "https://api.flxbl.dev", "FLXBL_API_KEY": "flxbl_your_api_key_here" } } } } ``` -------------------------------- ### Quick Start: Initialize and Create Record with FLXBL Client Source: https://flxbl.dev/docs/sdk Demonstrates how to initialize the FlxblClient with instance URL and API key, and then create a new record using a POST request to the '/api/v1/dynamic/Product' endpoint. It logs the created product details to the console. ```javascript import { FlxblClient } from '@flxbl-dev/client'; const client = new FlxblClient({ instanceUrl: 'https://api.flxbl.dev', apiKey: 'flxbl_your_api_key', }); // Create a record const product = await client.request('POST', '/api/v1/dynamic/Product', { name: 'Wireless Headphones', price: 299.99, inStock: true, }); console.log(product); // { id: 'node_abc123', name: '...', ... } ``` -------------------------------- ### Complete API Query Example Source: https://flxbl.dev/docs/query-dsl An example of a comprehensive API query using `curl`. This demonstrates combining multiple `where` conditions with logical operators (`$and`, `$or`), graph traversal using `traverse`, and ordering results. It targets the `/api/v1/dynamic/Product/query` endpoint. ```shell curl -X POST https://api.flxbl.dev/api/v1/dynamic/Product/query \ -H "Authorization: Bearer flxbl_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "where": { "$and": [ { "price": { "$gte": 10, "$lte": 500 } }, { "inStock": { "$eq": true } }, { "$or": [ { "tags": { "$contains": "featured" } }, { "tags": { "$contains": "sale" } } ] } ] }, "traverse": [{ "relationship": "BELONGS_TO", "direction": "out", "where": { "slug": { "$in": ["electronics", "accessories"] } } }], "orderBy": "price", "orderDirection": "ASC", "limit": 20 }' ``` -------------------------------- ### Install FLXBL MCP CLI Source: https://flxbl.dev/docs/index Installs the FLXBL MCP command-line interface globally using npm. This tool is used for interacting with FLXBL, including schema design with AI assistants. ```bash npm install -g @flxbl-dev/mcp ``` ```bash npx @flxbl-dev/mcp ``` -------------------------------- ### Example Usage of Generated FLXBL Client Source: https://flxbl.dev/docs/cli Demonstrates how to use the generated FLXBL client in a TypeScript application. It shows how to create a client instance with authentication details and how to perform typed queries, including filtering and ordering. ```typescript import { createFlxblClient } from './flxbl/_generated'; const client = createFlxblClient({ instanceUrl: 'https://api.flxbl.dev', apiKey: 'flxbl_xxx', }); // Fully typed — autocomplete on fields, filters, etc. const products = await client.Product.findMany({ where: { price: { $lte: 100 } }, orderBy: 'name', }); ``` -------------------------------- ### FLXBL GraphQL API Query Examples (GraphQL) Source: https://flxbl.dev/docs/api-reference Provides examples of common GraphQL queries for the FLXBL API, including fetching lists of products with filters, counting items, and querying with sorting and pagination. ```graphql # GraphQL endpoint # POST /api/v1/dynamic-gql/:tenantId # Query example query { products(where: { inStock: { equals: true } }, limit: 10) { id name price belongsTo { id name } } } # Count query - get total count for pagination query { productsCount(where: { inStock: { equals: true } }) } # Returns: { "data": { "productsCount": 157 } } # Query with sorting query { products( where: { inStock: { equals: true } } orderBy: "price" orderDirection: ASC limit: 20 offset: 0 ) { id name price } } ``` -------------------------------- ### List Users via Dynamic API (Admin) Source: https://flxbl.dev/docs/end-user-auth This example illustrates how an administrator can retrieve a list of all users from an identity entity using the Dynamic API. It's a GET request to the entity's path (e.g., `/api/v1/dynamic/Customer`) and requires an API key or tenant JWT in the `Authorization` header. The response contains user data, with password fields always redacted. ```http # Your backend lists all users (with API key) GET /api/v1/dynamic/Customer Authorization: Bearer flxbl_your_api_key # Response - password fields are always redacted { "data": [ { "id": "node_abc123", "email": "user@example.com", "name": "Jane Customer", "role": "member", "isActive": true } ] } ``` -------------------------------- ### Common Use Cases Source: https://flxbl.dev/docs/graphql-subscriptions Examples of how FLXBL GraphQL subscriptions can be utilized in various application scenarios. ```APIDOC ## Use Cases * **Real-time dashboards:** Update metrics and charts as data changes. * **Live feeds:** Display new content immediately as it's created. * **Collaborative editing:** Sync changes across multiple users. * **Notifications:** Trigger alerts when specific events occur. * **Cache invalidation:** Automatically refresh cached data when it changes. ``` -------------------------------- ### FLXBL GraphQL API Mutation Example (GraphQL) Source: https://flxbl.dev/docs/api-reference Demonstrates how to create a new product using a GraphQL mutation in the FLXBL API. It shows the mutation structure and the expected response fields. ```graphql # Mutation example mutation { createProduct(input: { name: "New Product" price: 99.99 }) { id name createdAt } } ``` -------------------------------- ### Create New Schema Interactively or from File Source: https://flxbl.dev/docs/cli Create a new database schema. This can be done interactively, where the CLI guides you through the process, or by importing a schema definition from a JSON file. The schema can also be auto-activated upon creation. ```bash # Interactive schema creation flxbl schema create # Import from JSON file flxbl schema create --file schema.json # Create and auto-activate flxbl schema create --file schema.json --activate ``` -------------------------------- ### Create Service Account Source: https://flxbl.dev/docs/user-management This example illustrates the concept of creating a service account, which is designed for automated processes. Service accounts authenticate via API keys and are assigned a user identity for audit logs and specific permissions. ```MCP "Create a service account called 'ci-pipeline' with read access to all entities and write access to deployments" // The service account gets: // 1. A user identity for audit logs // 2. An API key for authentication // 3. Scoped permissions like regular users ``` -------------------------------- ### Environment Variable Configuration for FLXBL Source: https://flxbl.dev/docs/integration-patterns Shows an example of environment variables used to configure FLXBL connections. This includes the base API URL, tenant ID, and API key for server-side operations, emphasizing that the .env file should not be committed to version control. ```dotenv # .env (never commit this file) FLXBL_URL=https://api.flxbl.dev FLXBL_TENANT_ID=your_tenant_id FLXBL_API_KEY=flxbl_your_api_key # For server-side only ``` -------------------------------- ### Verify FLXBL Webhook Signature (Python) Source: https://flxbl.dev/docs/webhooks Presents a Python example for verifying FLXBL webhook signatures using the `hmac` and `hashlib` modules. It includes a function to compare the computed signature with the one provided in the request header. ```python # Verify webhook signature (Python example) import hmac import hashlib def verify_webhook_signature(payload: bytes, signature: str, secret: str) -> bool: expected = hmac.new( secret.encode(), payload, hashlib.sha256 ).hexdigest() provided = signature.replace('sha256=', '') return hmac.compare_digest(expected, provided) # Flask webhook handler @app.route('/webhooks/flxbl', methods=['POST']) def handle_webhook(): signature = request.headers.get('X-Webhook-Signature') payload = request.get_data() if not verify_webhook_signature(payload, signature, WEBHOOK_SECRET): return 'Invalid signature', 401 event = request.get_json() if event['type'] == 'entity.created': handle_entity_created(event['data']) # ... handle other events return 'OK', 200 ``` -------------------------------- ### Initialize FLXBL Project Source: https://flxbl.dev/docs/cli Sets up a new FLXBL project in your repository, creating a `flxbl.config.ts` file. This configuration file specifies your instance URL and code generation settings. Initialization can be interactive or use flags for direct configuration. ```bash # Initialize a FLXBL project (interactive) flxbl init # Or with flags flxbl init --instance https://api.flxbl.dev --output-dir ./flxbl/_generated ``` -------------------------------- ### Get Authenticated User Profile via Identity API Source: https://flxbl.dev/docs/end-user-auth This example shows how an authenticated user can retrieve their own profile information using the Identity API. It requires a GET request to the `/me` endpoint with an `Authorization` header containing a Bearer token. The response includes the user's details, excluding sensitive information like the password. ```http # Authenticated user fetches their own profile GET /api/v1/identity/{tenantId}/me Authorization: Bearer eyJhbGciOiJIUzI1NiIs... # Response { "id": "node_abc123", "email": "user@example.com", "name": "Jane Customer", "role": "member", "_isVerified": true } ``` -------------------------------- ### JavaScript/TypeScript GraphQL WebSocket Client and Subscription Source: https://flxbl.dev/docs/graphql-subscriptions Demonstrates how to create a WebSocket client using `graphql-ws` in JavaScript/TypeScript. It includes setting up connection parameters with authentication, handling connection events, and subscribing to real-time data like product creations. Automatic reconnection with exponential backoff is configured. ```typescript import { createClient } from 'graphql-ws'; // Create a WebSocket client with authentication const client = createClient({ url: 'wss://api.flxbl.dev/api/v1/dynamic-gql/ws', connectionParams: { Authorization: `Bearer ${API_KEY}`, }, // Automatic reconnection with exponential backoff retryAttempts: 5, shouldRetry: () => true, on: { connected: () => console.log('Connected to FLXBL'), closed: () => console.log('Connection closed'), error: (err) => console.error('Connection error:', err), }, }); // Subscribe to product creations const unsubscribe = client.subscribe( { query: `subscription { productCreated { id name price createdAt } }`, }, { next: (data) => { console.log('New product:', data.data.productCreated); }, error: (err) => { console.error('Subscription error:', err); }, complete: () => { console.log('Subscription completed'); }, } ); // Unsubscribe when done // unsubscribe(); ``` -------------------------------- ### Complete E-commerce Schema Example Source: https://flxbl.dev/docs/schema-design A comprehensive FLXBL schema example for an e-commerce application, including entities for products, categories, and customers, along with their relationships. ```json { "entities": [ { "name": "Product", "fields": [ { "name": "name", "type": "STRING", "required": true }, { "name": "price", "type": "FLOAT", "required": true }, { "name": "tags", "type": "STRING_ARRAY", "required": false } ] }, { "name": "Category", "fields": [ { "name": "name", "type": "STRING", "required": true }, { "name": "slug", "type": "STRING", "required": true } ] }, { "name": "Customer", "fields": [ { "name": "email", "type": "STRING", "required": true }, { "name": "name", "type": "STRING", "required": true } ] } ], "relationships": [ { "name": "BELONGS_TO", "sourceEntityName": "Product", "targetEntityName": "Category", "cardinality": "MANY_TO_ONE" }, { "name": "PURCHASED_BY", "sourceEntityName": "Product", "targetEntityName": "Customer", "cardinality": "MANY_TO_MANY", "fields": [ { "name": "quantity", "type": "NUMBER", "required": true } ] } ], "description": "E-commerce schema with products, categories, and customers" } ``` -------------------------------- ### FLXBL Client Initialization Source: https://flxbl.dev/docs/sdk Demonstrates how to initialize the FLXBL client using either an API key for server-side applications or an access token for client-side sessions. ```APIDOC ## FLXBL Client Initialization ### Description Initialize the FLXBL client with your instance URL and authentication credentials. Supports API keys for server-side and access tokens (JWTs) for client-side applications. ### Method `new FlxblClient(options)` ### Parameters #### Request Body - **instanceUrl** (string) - Required - The base URL of your FLXBL instance. - **apiKey** (string) - Required (if accessToken is not provided) - Your FLXBL API key. - **accessToken** (string) - Required (if apiKey is not provided) - Your FLXBL access token (JWT). ### Request Example ```javascript import { FlxblClient } from '@flxbl-dev/client'; // Option 1: API key (recommended for server-side) const client = new FlxblClient({ instanceUrl: 'https://api.flxbl.dev', apiKey: 'flxbl_your_api_key', }); // Option 2: Access token (for client-side / user sessions) const client2 = new FlxblClient({ instanceUrl: 'https://api.flxbl.dev', accessToken: 'eyJhbGciOiJIUzI1NiIs...', }); ``` ### Response #### Success Response (200) Returns an instance of the `FlxblClient`. #### Response Example ```json { "message": "Client initialized successfully" } ``` ``` -------------------------------- ### GraphQL Batch Mutations for Products Source: https://flxbl.dev/docs/api-reference Demonstrates how to perform batch create, update, and delete operations for products using GraphQL. These mutations allow for bulk data manipulation, improving efficiency for common operations. The responses indicate success and failure details for each item in the batch. ```graphql mutation { batchCreateProduct(input: [ { name: "Widget A", price: 29.99 }, { name: "Widget B", price: 39.99 } ]) { successful { id name price } failed { index error { code message field } } successCount failureCount } } # Batch update mutation mutation { batchUpdateProduct(input: [ { id: "node_abc", data: { price: 24.99 } }, { id: "node_def", data: { price: 34.99 } } ]) { successful { id name price } successCount } } # Batch delete mutation mutation { batchDeleteProduct(ids: ["node_abc", "node_def"]) { successful { id } successCount failureCount } } ``` -------------------------------- ### Python WebSocket Subscription to Product Creations Source: https://flxbl.dev/docs/graphql-subscriptions This Python script demonstrates how to connect to the FLXBL WebSocket API, authenticate using an API key, and subscribe to 'productCreated' events. It includes steps for sending connection initialization, waiting for acknowledgment, subscribing to the event, and listening for incoming product data. The script also handles graceful unsubscription on keyboard interrupt. ```python pip install websockets import asyncio import json from websockets import connect API_KEY = "flxbl_your_api_key" WS_URL = "wss://api.flxbl.dev/api/v1/dynamic-gql/ws" async def subscribe_to_products(): async with connect(WS_URL) as websocket: # Step 1: Send connection_init with auth await websocket.send(json.dumps({ "type": "connection_init", "payload": { "Authorization": f"Bearer {API_KEY}" } })) # Step 2: Wait for connection_ack response = await websocket.recv() ack = json.loads(response) if ack["type"] != "connection_ack": raise Exception(f"Connection failed: {ack}") print("✓ Connected to FLXBL") # Step 3: Subscribe to product creations await websocket.send(json.dumps({ "id": "product-sub-1", "type": "subscribe", "payload": { "query": "" subscription {\n productCreated {\n id\n name\n price\n createdAt\n }\n }\n " } })) print("✓ Subscribed to productCreated events") # Step 4: Listen for events try: async for message in websocket: data = json.loads(message) if data["type"] == "next": product = data["payload"]["data"]["productCreated"] print(f"New product: {product['name']} (${product['price']})") elif data["type"] == "error": print(f"Error: {data['payload']}") break elif data["type"] == "complete": print("Subscription completed") break except KeyboardInterrupt: # Step 5: Unsubscribe gracefully await websocket.send(json.dumps({ "id": "product-sub-1", "type": "complete" })) print("Unsubscribed") # Run the subscription asyncio.run(subscribe_to_products()) ``` -------------------------------- ### Get Identity Configuration API Source: https://flxbl.dev/docs/identity-config Retrieves the current identity configuration settings for the tenant. ```APIDOC ## GET /api/v1/identity/config ### Description Retrieves the current identity configuration settings. ### Method GET ### Endpoint `/api/v1/identity/config` ### Authentication Admin JWT ### Response #### Success Response (200) - **accessTokenExpiry** (string) - The expiry duration for access tokens (e.g., "30 minutes"). - **refreshTokenExpiry** (string) - The expiry duration for refresh tokens (e.g., "7 days"). - **minPasswordLength** (string) - The minimum required password length (e.g., "10 characters"). - **emailVerification** (string) - Indicates if email verification is required (e.g., "Required" or "Optional"). ``` -------------------------------- ### GraphQL API Endpoint Source: https://flxbl.dev/docs/api-reference Details on how to interact with the FLXBL GraphQL API, including the endpoint and example queries/mutations. ```APIDOC ## POST /api/v1/dynamic-gql/:tenantId ### Description The endpoint for interacting with the FLXBL GraphQL API. ### Method POST ### Endpoint /api/v1/dynamic-gql/:tenantId ### Parameters #### Path Parameters - **tenantId** (string) - Required - Your FLXBL tenant ID. #### Request Body - **query** (string) - The GraphQL query or mutation to execute. - **variables** (object) - Optional - Variables for the GraphQL query. ### Request Example (Query) ```graphql query { products(where: { inStock: { equals: true } }, limit: 10) { id name price belongsTo { id name } } } ``` ### Request Example (Mutation) ```graphql mutation { createProduct(input: { name: "New Product" price: 99.99 }) { id name createdAt } } ``` ### Response #### Success Response (200) - Returns the result of the GraphQL query or mutation. #### Response Example (Query Result) ```json { "data": { "products": [ { "id": "prod_123", "name": "Example Product", "price": 19.99, "belongsTo": { "id": "cat_456", "name": "Electronics" } } ] } } ``` #### Response Example (Mutation Result) ```json { "data": { "createProduct": { "id": "prod_789", "name": "New Product", "createdAt": "2026-01-15T10:30:00Z" } } } ``` ## GET /api/v1/dynamic-gql/{tenantId}/schema.graphql ### Description Downloads the GraphQL schema file. ### Method GET ### Endpoint /api/v1/dynamic-gql/{tenantId}/schema.graphql ``` -------------------------------- ### Implement Role-Based Authorization in Server Middleware Source: https://flxbl.dev/docs/end-user-auth This JavaScript example shows how to implement authorization logic in your server middleware. It fetches user data, defines role levels, and checks if the user has the minimum required role before allowing access to a protected route. This is crucial for managing end-user permissions. ```javascript // Example: Checking roles in your server middleware const user = await fetchUserFromFLXBL(accessToken); // Define your role hierarchy const ROLE_LEVELS = { viewer: 1, editor: 2, admin: 3 }; // Check permissions function hasMinimumRole(userRole, requiredRole) { return ROLE_LEVELS[userRole] >= ROLE_LEVELS[requiredRole]; } // Protect routes if (!hasMinimumRole(user.role, 'editor')) { throw new Error('Forbidden: Insufficient permissions'); } ``` -------------------------------- ### Get Authenticated User Profile API Source: https://flxbl.dev/docs/identity-config Retrieves the profile information of the currently authenticated user. ```APIDOC ## GET /api/v1/identity/{tenantId}/me ### Description Retrieves the profile information of the currently authenticated user. ### Method GET ### Endpoint `/api/v1/identity/{tenantId}/me` ### Parameters #### Path Parameters - **tenantId** (string) - Required - The unique identifier for the tenant. ### Authentication End-User JWT ### Response #### Success Response (200) - **userId** (string) - The user's unique identifier. - **email** (string) - The user's email address. - **firstName** (string) - The user's first name. - **lastName** (string) - The user's last name. ``` -------------------------------- ### get_graphql_schema Source: https://flxbl.dev/docs/mcp-integration Get the GraphQL SDL (Schema Definition Language) for your active schema. Returns type definitions, queries, mutations, and subscriptions. ```APIDOC ## get_graphql_schema ### Description Get the GraphQL SDL (Schema Definition Language) for your active schema. Returns type definitions, queries, mutations, and subscriptions. ### Method GET ### Endpoint /api/graphql ### Parameters *No parameters required.* ### Request Example ```json {} ``` ### Response #### Success Response (200) - **GraphQL SDL** (string) - The GraphQL Schema Definition Language string. #### Response Example ```graphql type User { id: ID! name: String } type Query { users: [User] } ``` ``` -------------------------------- ### Get User Profile API Source: https://flxbl.dev/docs/identity-config Authenticated end users can retrieve their own profile data. Password fields are automatically redacted from the response. ```APIDOC ## GET /api/v1/identity/{tenantId}/me ### Description Authenticated end users can retrieve their own profile data. Password fields are automatically redacted from the response. ### Method GET ### Endpoint /api/v1/identity/{tenantId}/me ### Parameters #### Query Parameters - **Authorization** (string) - Required - Bearer token for authentication. ### Response #### Success Response (200) - **id** (string) - The user's unique identifier. - **email** (string) - The user's email address. - **name** (string) - The user's name. - **phone** (string) - The user's phone number. - **_isVerified** (boolean) - Indicates if the user's email has been verified. #### Response Example ```json { "id": "node_abc123", "email": "customer@example.com", "name": "Jane Customer", "phone": "+1-555-0123", "_isVerified": true } ``` ``` -------------------------------- ### Export Schema, List Versions, and Manage Migrations Source: https://flxbl.dev/docs/cli Manage schema lifecycle, including exporting the schema to a JSON file for backup or import, listing all available schema versions, checking the status of schema migrations, and deleting specific schemas. ```bash # Export schema to JSON (importable format) flxbl schema export -o schema.json flxbl schema export --schema-id abc123 # List schema versions flxbl schema versions # Check migration status flxbl schema migrate # Delete a schema flxbl schema delete flxbl schema delete --force ``` -------------------------------- ### get_api_spec Source: https://flxbl.dev/docs/mcp-integration Get the OpenAPI 3.0 specification for your active schema. Returns complete REST API documentation including endpoints, schemas, and query parameters. ```APIDOC ## get_api_spec ### Description Get the OpenAPI 3.0 specification for your active schema. Returns complete REST API documentation including endpoints, schemas, and query parameters. ### Method GET ### Endpoint /api/openapi/{schemaId} ### Parameters #### Path Parameters - **schemaId** (string) - Required - The ID of the schema for which to retrieve the OpenAPI specification. #### Query Parameters - **format** (string) - Optional - The desired format for the specification. Can be 'json' for the full specification or 'summary' for a condensed overview. ### Request Example ```json { "format": "json" } ``` ```json { "format": "summary" } ``` ### Response #### Success Response (200) - **OpenAPI Specification** (object) - The OpenAPI 3.0 specification in JSON format, or a summary if requested. #### Response Example ```json { "openapi": "3.0.0", "info": { "title": "My API", "version": "1.0.0" }, "paths": { "/users": { "get": { "summary": "List users" } } } } ``` ``` -------------------------------- ### Get User Profile Source: https://flxbl.dev/docs/end-user-auth Allows an authenticated user to fetch their own profile information. This endpoint requires a JWT in the Authorization header and is part of the Identity API. ```APIDOC ## Get Profile ```http # Authenticated user fetches their own profile GET /api/v1/identity/{tenantId}/me Authorization: Bearer eyJhbGciOiJIUzI1NiIs... ``` ### Response ```json { "id": "node_abc123", "email": "user@example.com", "name": "Jane Customer", "role": "member", "_isVerified": true } ``` ``` -------------------------------- ### User Registration via Identity API Source: https://flxbl.dev/docs/end-user-auth This example shows a POST request to the Identity API for end-user registration. It includes the tenant ID in the URL and a JSON payload with user credentials like email, password, and name. The response confirms successful registration and may include a message for further actions like email verification. ```http # Your app's users register themselves POST /api/v1/identity/{tenantId}/register Content-Type: application/json { "email": "user@example.com", "password": "SecurePassword123", "name": "Jane Customer" } # Response { "id": "node_abc123", "message": "Registration successful. Please check your email to verify your account." } ``` -------------------------------- ### Checking User Permissions via API Source: https://flxbl.dev/docs/access-control Illustrates how to check if the current user has a specific permission by making a GET request to the authorization endpoint with the permission as a query parameter. ```json // Check if current user has permission GET /api/v1/auth/check-permission?permission=entity:Article:create // Response { "hasPermission": true, "role": "Content Manager" } ``` -------------------------------- ### Permission Format Examples Source: https://flxbl.dev/docs/access-control Defines the structure for permissions in FLXBL, specifying formats for entities and relationships, along with available operations like create, read, update, delete, and wildcard. ```plaintext // Permission format entity:{EntityName}:{operation} relationship:{RelationshipName}:{operation} // Operations create = create new records read = read/query records update = modify existing records delete = remove records * = all operations ``` -------------------------------- ### Generate Client Types Tool Options Source: https://flxbl.dev/docs/mcp-integration Demonstrates the options for the `generate_client_types` tool, which creates client code from a schema in various formats like TypeScript interfaces, Zod schemas, Python Pydantic models, or language-agnostic API contracts. ```text // generate_client_types tool // Generate code from your schema // TypeScript interfaces language: "typescript", format: "interface" // Zod schemas with API client language: "typescript", format: "zod" // Python Pydantic models language: "python", format: "pydantic" // Language-agnostic API contract language: "any", format: "schema" ``` -------------------------------- ### Get User Profile Source: https://flxbl.dev/docs/identity-config Retrieves the profile data for an authenticated end-user. Password fields are automatically redacted from the response. This endpoint requires an Authorization header with a Bearer token. ```http GET /api/v1/identity/{tenantId}/me Authorization: Bearer eyJhbGciOiJIUzI1NiIs... // Response { "id": "node_abc123", "email": "customer@example.com", "name": "Jane Customer", "phone": "+1-555-0123", "_isVerified": true } ``` -------------------------------- ### View Active Schema in Different Formats Source: https://flxbl.dev/docs/cli Display the currently active database schema. Supports multiple output formats including table (default), tree (ASCII art), and JSON for detailed inspection. ```bash # Show active schema flxbl schema # Different formats flxbl schema show --format table # Tabular view (default) flxbl schema show --format tree # ASCII tree flxbl schema show --format json # Full JSON ``` -------------------------------- ### TypeScript Client for Type-Safe Queries Source: https://flxbl.dev/docs/query-dsl Illustrates how to use the generated TypeScript client to interact with the Flxbl API. It shows initializing the client with base URL and API key, and performing type-safe queries for products with filtering, traversal, and ordering. The results are typed as `Product[]`. ```typescript import { createFlxblClient } from './schemas'; const client = createFlxblClient({ baseUrl: 'https://api.flxbl.dev', apiKey: 'flxbl_your_api_key' }); // Query with type safety const products = await client.query('Product', { where: { price: { $gte: 10, $lte: 100 }, inStock: { $eq: true } }, traverse: [{ relationship: 'BELONGS_TO', direction: 'out', where: { slug: { $eq: 'electronics' } } }], orderBy: 'price', orderDirection: 'ASC', limit: 20 }); console.log(products); // Typed as Product[] ``` -------------------------------- ### Authenticate Requests with FLXBL API Key Source: https://flxbl.dev/docs/api-keys Shows how to include an API key in the `Authorization` header for authenticating requests to the FLXBL API. Examples are provided for cURL, JavaScript/TypeScript, and Python. ```http // Using an API key for authentication curl -X GET https://api.flxbl.dev/api/v1/dynamic/Product \ -H "Authorization: Bearer flxbl_ab12cd34_7f8g9h..." ``` ```javascript // JavaScript/TypeScript const response = await fetch('https://api.flxbl.dev/api/v1/dynamic/Product', { headers: { 'Authorization': 'Bearer flxbl_ab12cd34_7f8g9h...' } }); ``` ```python # Python import requests response = requests.get( 'https://api.flxbl.dev/api/v1/dynamic/Product', headers={'Authorization': 'Bearer flxbl_ab12cd34_7f8g9h...'} ) ``` -------------------------------- ### Get GraphQL Schema (JSON) Source: https://flxbl.dev/docs/mcp-integration Retrieve the GraphQL Schema Definition Language (SDL) for your active schema. This includes type definitions, queries, mutations, and subscriptions. No parameters are required for this action. ```json {} ``` -------------------------------- ### Best Practices Source: https://flxbl.dev/docs/graphql-subscriptions Recommendations for effectively and efficiently using FLXBL GraphQL subscriptions in your application. ```APIDOC ## Best Practices * Use specific filters to reduce unnecessary event traffic. * Handle connection drops and implement reconnection logic. * Unsubscribe when components unmount to prevent memory leaks. * Consider using the `id` filter for update/delete subscriptions when watching specific entities. ``` -------------------------------- ### Validate Schema Tool Configuration Source: https://flxbl.dev/docs/mcp-integration Example configuration for the `validate_schema` tool, which checks a schema for errors like reserved names or invalid types before publishing. It returns validation issues and design suggestions. ```json // validate_schema tool // Checks for errors before publishing { "entities": [{ "name": "Product", "fields": [ { "name": "id", "type": "STRING", "required": true } // Error: 'id' is reserved ] }] } // Returns validation errors and design suggestions ```