### Create a New Maven Project for Java Source: https://docs.polyapi.io/generated_sdks/java This command generates a new Maven project with the 'maven-archetype-quickstart' archetype. It sets up the basic project structure required for a Java application. ```bash mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchitypeVersion=1.4 -DinteractiveMode=false ``` -------------------------------- ### Compile and Install PolyAPI Library Source: https://docs.polyapi.io/generated_sdks/java This command compiles the project and ensures that the PolyAPI library is downloaded and installed into your local Maven repository. It's a crucial step after modifying the `pom.xml` file. ```bash mvn clean compile ``` -------------------------------- ### Setup PolyAPI Client Source: https://docs.polyapi.io/generated_sdks/typescript Sets up the PolyAPI client by configuring server and API Key. This command may also prompt for the installation or update of dependencies like ts-node and TypeScript. ```bash $ npx poly setup ``` -------------------------------- ### Setup and Generate PolyAPI .NET SDK Source: https://docs.polyapi.io/generated_sdks/dotnet Steps to set up the PolyAPI client configuration and generate the .NET SDK for your Poly functions. This includes running the setup command and then generating the code. ```bash dotnet tool run polyapi setup dotnet new console dotnet tool run polyapi generate ``` -------------------------------- ### Setup MFA for your Account Source: https://docs.polyapi.io/authentication/setup-user-mfa Initiates the MFA setup process for a user account by providing a QR code for authenticator app pairing. ```APIDOC ## POST /otp/setup ### Description Initiates the Multi-Factor Authentication (MFA) setup process for the current user account. This endpoint returns a QR code that should be scanned by an authenticator application (e.g., Google Authenticator, Authy) to pair the device with the user's account. Alternatively, the `/otp/pair` endpoint can be used to obtain a pairing link, typically for desktop authenticator apps. ### Method POST ### Endpoint `/otp/setup` ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed for this endpoint." } ``` ### Response #### Success Response (200) - **qr_code** (string) - The QR code image data or URL to be scanned by an authenticator app. #### Response Example ```json { "qr_code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA..." } ``` ``` -------------------------------- ### Poly CLI Setup and Redeploy Command Source: https://docs.polyapi.io/environments/pushing These commands demonstrate how to configure the Poly CLI to target a specific environment and then deploy a server function. `npx poly setup` prompts for instance URL and API key, allowing switching between environments. `npx poly generate` is typically run after setup, and `npx poly function add` deploys the specified function. ```bash npx poly setup Enter your instance url (e.g. https://na1.polyapi.io) Enter your `prod` api key npx poly generate npx poly function add echo echo.ts --context test --server ``` -------------------------------- ### Compile and Run First Java Function Source: https://docs.polyapi.io/generated_sdks/java Compile the project using Maven, update the App.java file to include the Poly API invocation, and then execute the Java application. This demonstrates the basic workflow of running a serverless function. ```bash $ mvn clean compile ``` ```java package com.mycompany.app; import io.polyapi.Poly; public class App { public static void main(String[] args) { System.out.println(Poly.greetings.hello("Alice")); } } ``` ```bash mvn exec:java -Dexec.mainClass="com.mycompany.app.App" -Dexec.cleanupDaemonThreads=false ``` ```text Hello Alice ``` -------------------------------- ### Install Pre-commit for Git Hooks (Python) Source: https://docs.polyapi.io/project_glide/git-integration Installs the 'pre-commit' package in a Python project by adding it to the requirements.txt file and then running pip install. Pre-commit is a framework for managing and executing pre-commit hooks. ```bash pre-commit==4.0.1 ``` ```bash $ pip install -r requirements.txt ``` -------------------------------- ### Install Pre-commit Hook Management (Python) Source: https://docs.polyapi.io/project_glide/git-integration Installs the pre-commit hook into the local Git repository. This command enables the pre-commit framework to manage and run configured Git hooks for the project. ```bash $ python -m pre_commit install ``` -------------------------------- ### Install PolyAPI .NET Tool Source: https://docs.polyapi.io/generated_sdks/dotnet Commands to install the PolyAPI .NET Tool locally within a project. This involves creating a tool manifest and then installing the tool. ```bash mkdir my-poly-project cd my-poly-project dotnet new tool-manifest dotnet tool install --local PolyApi.Tools ``` -------------------------------- ### Deploy Java Functions to PolyAPI Source: https://docs.polyapi.io/generated_sdks/java This command uses the PolyAPI Maven plugin to compile the project and deploy the defined server functions to Poly. Ensure your environment variables for host and API key are set correctly. ```bash mvn clean compile polyapi:deploy-functions ``` -------------------------------- ### Setup MFA for Account (PolyAPI) Source: https://docs.polyapi.io/authentication/setup-user-mfa Initiates the MFA setup process by hitting the /otp/setup endpoint. This returns a QR code to be scanned by an authenticator app. Alternatively, the /otp/pair endpoint can be used to receive a pairing link, typically for desktop authenticator apps. ```http POST /otp/setup ``` -------------------------------- ### Install PolyAPI TypeScript Library Source: https://docs.polyapi.io/generated_sdks/typescript Installs the PolyAPI TypeScript library using npm. Ensure you use the correct instance name (e.g., 'na1', 'eu1'). Requires a recent version of NodeJS. ```bash $ npm install polyapi@na1 ``` ```bash $ npm install polyapi@eu1 ``` -------------------------------- ### Install Husky for Pre-commit Hooks (TypeScript) Source: https://docs.polyapi.io/project_glide/git-integration Installs the Husky package as a development dependency in a TypeScript project. Husky is used to manage Git hooks, ensuring that pre-commit and post-merge scripts are executed before or after Git operations. ```bash $ npm install --save-dev husky ``` -------------------------------- ### Python Request Example Source: https://docs.polyapi.io/api_functions/postman Demonstrates how to fetch data from a JSONPlaceholder API using the Python requests library. This is a basic example for comparison with PolyAPI's simplified approach. ```python import requests response = requests.get("https://jsonplaceholder.typicode.com/todos") ``` -------------------------------- ### Verify MFA for your Account Source: https://docs.polyapi.io/authentication/setup-user-mfa Verifies the MFA setup by submitting a token generated by the user's authenticator app. ```APIDOC ## POST /otp/verify ### Description Verifies the Multi-Factor Authentication (MFA) setup for the user account. After scanning the QR code (or using the pairing link), the user will obtain a time-based one-time password (TOTP) from their authenticator app. This endpoint is used to submit that token for verification. A successful verification confirms that MFA is correctly set up and ready for use. ### Method POST ### Endpoint `/otp/verify` ### Parameters #### Query Parameters None #### Request Body - **token** (string) - Required - The one-time password (OTP) generated by the user's authenticator app. ### Request Example ```json { "token": "123456" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating successful MFA setup. #### Response Example ```json { "message": "MFA setup verified successfully." } ``` ``` -------------------------------- ### Verify MFA for Account (PolyAPI) Source: https://docs.polyapi.io/authentication/setup-user-mfa Verifies the MFA setup by sending a token obtained from the authenticator app to the /otp/verify endpoint. A successful verification returns a 200 status code, confirming the MFA setup is complete. ```http POST /otp/verify {"token": "123456"} ``` -------------------------------- ### Example Canopy Application Metadata Configuration Source: https://docs.polyapi.io/canopy/architecture A JSON example demonstrating the configuration of metadata for a Canopy application. This includes basic application information like name, subpath, icons, and details for the login screen. ```json { "name": "Quantum Quirk", "subpath": "quantum-quirk-dashboard", "icon": "https://polyapi-public.s3.us-west-2.amazonaws.com/clients/quantum-quirk/quantum-quirk.svg", "logoSrc": "https://polyapi-public.s3.us-west-2.amazonaws.com/clients/quantum-quirk/quantum-quirk.svg", "login": { "title": "Login To Quantum Quirk Dashboard", "logoSrc": "https://polyapi-public.s3.us-west-2.amazonaws.com/clients/quantum-quirk/quantum-quirk.png" } } ``` -------------------------------- ### Example Properties Configuration Source: https://docs.polyapi.io/canopy/architecture An example of a properties configuration object within a Canopy collection. This defines the structure and behavior of item properties, including their labels, types, and UI attributes. ```json { "properties": { "id": { "label": "ID", "readOnly": true, "excludeFromCreate": true, "excludeFromUpdate": true }, "title": { "label": "Title", "type": "text" }, "description": { "label": "Description", "type": "multiline", "autoSize": true }, "status": { "label": "Status", "type": "enum", "values": [ { "name": "To Do", "value": "TODO" }, { "name": "In Progress", "value": "IN_PROGRESS" } ] } } } ``` -------------------------------- ### Poly API Server Functions: List and Get Operations Source: https://docs.polyapi.io/canopy/implement_api This snippet demonstrates how to interact with Poly API server functions. The 'list' function retrieves all available server functions for an environment by calling 'OOB.polyapi.serverFunctions.list'. The 'get' function fetches details for a specific server function using 'OOB.polyapi.serverFunctions.get', requiring an instance URL, Poly API key, and the function's ID. ```javascript { "list": { "function": { "path": "OOB.polyapi.serverFunctions.list", "type": "api" } }, "get": { "function": { "path": "OOB.polyapi.serverFunctions.get", "type": "api", "arguments": { "instanceUrl": { "variablePath": "OOB.polyapi.configurations.instanceUrl" }, "polyAPIKey": { "apiKey": true }, "id": { "id": true } } } } } ``` -------------------------------- ### Deploying PolyAPI Functions using CLI Source: https://docs.polyapi.io/canopy/implement_crud Commands to deploy Python functions as PolyAPI services. This example shows deploying functions like create_task, list_tasks, get_task, update_task, and delete_task to a 'dashboard' context as server-side functions. ```bash $ python -m polyapi function add create_task create_task.py --server --context dashboard $ python -m polyapi function add list_tasks list_tasks.py --server --context dashboard $ python -m polyapi function add get_task get_task.py --server --context dashboard $ python -m polyapi function add update_task update_task.py --server --context dashboard $ python -m polyapi function add delete_task delete_task.py --server --context dashboard ``` -------------------------------- ### Run First PolyAPI Function in .NET Source: https://docs.polyapi.io/generated_sdks/dotnet Example C# code to call a PolyAPI function ('jsonPlaceholder.todos.getList') and display the results. This demonstrates how to interact with the generated SDK. ```csharp using PolyApi.PolyContext; var todos = await Poly.jsonPlaceholder.todos.getList(); Console.WriteLine(todos.Data.Aggregate("", (acc, todo) => acc + $"{todo.Id}: {todo.Title}\n")); ``` -------------------------------- ### Invoke Deployed Python Function using PolyAPI SDK Source: https://docs.polyapi.io/generated_sdks/python Invokes the deployed server function ('hello' within the 'mycontext') using the PolyAPI Python SDK. Assumes the SDK is installed and configured. ```python from polyapi import poly print(poly.mycontext.hello()) ``` -------------------------------- ### TypeScript Webhook Configuration Source: https://docs.polyapi.io/project_glide/resources Example configuration for a PolyAPI Webhook in TypeScript. It shows the import of `PolyWebhook` and the `polyConfig` object, which includes the webhook's name, context, and description. ```typescript // Poly deployed @ - context.namespace.hook_name - /canopy/polyui/collections/webhooks/ - import { PolyWebhook } from 'polyapi'; const polyConfig: PolyWebhook = { name: 'hook_name', context: 'context.namespace', description: 'description here', // other config here }; ``` -------------------------------- ### PolyAPI Python Invocation Example Source: https://docs.polyapi.io/api_functions/postman Shows how to invoke a trained API function (e.g., 'todos.getList') using the PolyAPI Python SDK. This highlights the simplified interaction compared to direct HTTP requests. ```python from polyapi import poly response = poly.todos.getList() ``` -------------------------------- ### Prepare Poly Function: Python Example Source: https://docs.polyapi.io/project_glide/manual-prepare-and-sync Illustrates how to define a Python server function and prepare it for deployment using the `polyapi prepare` command. AI assists in generating necessary docstrings. ```python from polyapi.typedefs import PolyServerFunction polyConfig: PolyServerFunction = { 'name': 'hello_poly', 'context': 'myContext', # you can also add in optional, additional configuration for your server function here using the helpful type hints provided by the imported PolyServerFunction type. For example: 'logsEnabled': True, 'visibility': 'TENANT', # make this function visible to all environments in your tenant } def hello_poly(first_name: str) -> str: return f"Hello {first_name}! I'm Poly, your helpful AI Assistant." ``` ```bash $ python3 -m polyapi prepare ``` ```python from polyapi.typedefs import PolyServerFunction polyConfig: PolyServerFunction = { 'name': 'hello_poly', 'context': 'myContext', # you can also add in optional, additional configuration for your server function here using the helpful type hints provided by the imported PolyServerFunction type. For example: 'logsEnabled': True, 'visibility': 'TENANT', # make this function visible to all environments in your tenant } def hello_poly(first_name: str) -> str: """Function that has Poly greet a user by their name Args: first_name (str): The user's first name Returns: str: Returns a greeting from Poly """ return f"Hello {first_name}! I'm Poly, your helpful AI Assistant." ``` -------------------------------- ### Prepare Poly Function: TypeScript Example Source: https://docs.polyapi.io/project_glide/manual-prepare-and-sync Demonstrates how to define a TypeScript server function and prepare it for deployment using the `polyapi prepare` command. This process involves AI to fill in missing documentation. ```typescript import { PolyServerFunction } from 'polyapi'; const polyConfig: PolyServerFunction = { name: 'helloPoly', context: 'myContext', // you can also add in optional, additional configuration for your server function here using the helpful type hints provided by the imported PolyServerFunction type. For example: logsEnabled: true, visibility: 'TENANT', // make this function visible to all environments in your tenant }; function helloPoly(first_name: string): string { return `Hello ${first_name}! I'm Poly, your helpful AI Assistant.`; } ``` ```bash $ npx poly prepare ``` ```typescript import { PolyServerFunction } from 'polyapi'; const polyConfig: PolyServerFunction = { name: 'helloPoly', context: 'myContext', // you can also add in optional, additional configuration for your server function here using the helpful type hints provided by the imported PolyServerFunction type. For example: logsEnabled: true, visibility: 'TENANT', // make this function visible to all environments in your tenant }; /** * Function that has Poly greet a user by their name * * @param {string} first_name - The user's first name * @returns {string} Returns a greeting from Poly */ function helloPoly(first_name: string): string { return `Hello ${first_name}! I'm Poly, your helpful AI Assistant.`; } ``` -------------------------------- ### Reset MFA for User (PolyAPI) Source: https://docs.polyapi.io/authentication/setup-user-mfa Resets MFA for a specific user within a tenant. This is useful if a user gets a new MFA device. After resetting, the user can go through the MFA setup process again. ```http POST /tenants/123/users/456/reset-mfa ``` -------------------------------- ### Define a Java Server Function with PolyAPI Source: https://docs.polyapi.io/generated_sdks/java This Java code defines a simple server function named 'hello' that takes a 'name' string as input and returns a greeting. The `@PolyServerFunction` annotation registers it for deployment to Poly. ```java package com.mycompany.app; import io.polyapi.commons.api.model.PolyServerFunction; public class Greetings { @PolyServerFunction(context="greetings") public String hello(String name) { return String.format("Hello %s", name); } } ``` -------------------------------- ### Deploy Server Functions with Poly Sync (TypeScript) Source: https://docs.polyapi.io/project_glide/manual-prepare-and-sync This snippet demonstrates deploying a server function using TypeScript and the 'npx poly sync' command. It includes configuration for the server function, such as name, context, logging, and visibility. The deployment process automatically adds a comment with deployment details to the source file. ```bash $ npx poly sync ``` ```typescript // Poly deployed @ 2024-09-20T21:58:31.264Z - myContext.helloPoly - https://na1.polyapi.io/canopy/polyui/collections/server-functions/f382e9df-d591-4080-93e0-9dc2d0297444 - 75a08d6 import { PolyServerFunction } from 'polyapi'; const polyConfig: PolyServerFunction = { name: 'helloPoly', context: 'myContext', // you can also add in optional, additional configuration for your server function here using the helpful type hints provided by the imported PolyServerFunction type. For example: logsEnabled: true, visibility: 'TENANT', // make this function visible to all environments in your tenant }; /** * Function that has Poly greet a user by their name * * @param {string} first_name - The user's first name * @returns {string} Returns a greeting from Poly */ function helloPoly(first_name: string): string { return `Hello ${first_name}! I'm Poly, your helpful AI Assistant.`; } ``` -------------------------------- ### Configure Maven Project (`pom.xml`) for PolyAPI Source: https://docs.polyapi.io/generated_sdks/java This XML configuration defines the project's dependencies, including the PolyAPI library and JUnit. It also configures the PolyAPI Maven plugin for deploying functions and the Maven compiler plugin. ```xml 4.0.0 com.mycompany.app my-app 1.0-SNAPSHOT my-app http://www.example.com UTF-8 1.8 1.8 0.15.1 io.polyapi library ${poly.version} junit junit 4.11 test target/generated-resources io.polyapi polyapi-maven-plugin ${poly.version} {HOST} 443 ${env.POLY_API_KEY} generate-sources generate-sources org.apache.maven.plugins maven-compiler-plugin 3.12.1 true org.codehaus.mojo build-helper-maven-plugin 3.2.0 add-source generate-sources add-source target/generated-sources ``` -------------------------------- ### Add Apache Commons Lang Dependency and Update Function Source: https://docs.polyapi.io/generated_sdks/java Modify the pom.xml to include the Apache Commons Lang dependency. Then, update the server function in Greetings.java to use StringUtils.capitalize(). Finally, redeploy the function and test with a lowercase input. ```xml org.example my-custom-library 1.0.0 ``` ```java package com.mycompany.app; import org.apache.commons.lang3.StringUtils; import io.polyapi.commons.api.model.PolyServerFunction; public class Greetings { @PolyServerFunction(context="greetings") public String hello(String name) { return String.format("Hello %s", StringUtils.capitalize(name)); } } ``` ```bash mvn clean compile polyapi:deploy-functions ``` ```java package com.mycompany.app; import io.polyapi.Poly; public class App { public static void main(String[] args) { System.out.println(Poly.greetings.hello("bob")); } } ``` ```bash mvn exec:java -Dexec.mainClass="com.mycompany.app.App" -Dexec.cleanupDaemonThreads=false ``` ```text Hello Bob ``` -------------------------------- ### Gitlab CI/CD Workflow for PolyAPI Deployment Source: https://docs.polyapi.io/project_glide/gitlab-workflow This YAML configuration defines the stages, variables, and scripts required to deploy PolyAPI services within a Gitlab CI/CD pipeline. It handles dependency installation, PolyAPI setup, deployment synchronization, and committing deployment receipts back to the repository. Requires 'POLY_API_KEY' and 'POLY_API_BASE_URL' as masked secret variables in Gitlab. ```yaml stages: - deploy variables: NODE_VERSION: "20" POLY_API_KEY: $POLY_API_KEY POLY_API_BASE_URL: $POLY_API_BASE_URL ENVIRONMENT: development deploy_polyapi: stage: deploy image: node:${NODE_VERSION} only: - main # Execute this job only on the main branch before_script: - echo "Setting up environment" - export PACKAGE_MANAGER="npm" script: # Step: Poly pre-check - echo "Running Poly pre-check" - | if ! grep -q '"polyapi":' package.json; then echo "Please install the PolyAPI client using your package manager." exit 1 fi # Step: Setup Node and determine package manager - echo "Setting up Node and determining package manager" - | if [ -f "yarn.lock" ]; then export PACKAGE_MANAGER="yarn" elif [ -f "package-lock.json" ]; then export PACKAGE_MANAGER="npm" fi - | echo "Using package manager: $PACKAGE_MANAGER" # Step: Restore cached dependencies - echo "Restoring cached dependencies" - if [ "$PACKAGE_MANAGER" == "yarn" ]; then yarn install --cache-folder ~/.cache/yarn; else npm ci; fi # Step: Setup Poly - echo "Setting up Poly" - mkdir -p node_modules/.poly - POLY_ENV_PATH="node_modules/.poly/.config.env" - if [ ! -f "$POLY_ENV_PATH" ]; then echo -e "DISABLE_AI=true\nENVIRONMENT_SETUP_COMPLETE=true" > "$POLY_ENV_PATH"; fi # Step: Deploy - echo "Deploying with PolyAPI" - if [ "$PACKAGE_MANAGER" == "yarn" ]; then yarn poly sync --custom-path=./node_modules/.poly/; else npx poly sync --custom-path=./node_modules/.poly/; fi - git config --global user.email "${GIT_USER_EMAIL:-$GITLAB_USER_EMAIL}" - git config --global user.name "${GIT_USER_NAME:-$GITLAB_USER_NAME}" - git checkout main - git branch -vv - git remote set-url origin "https://${GITLAB_USERNAME}:${GITLAB_TOKEN}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git" # Step: Commit deployment receipts - echo "Committing deployment receipts" - git add . - if ! git diff-index --quiet HEAD; then git commit -m "PolyAPI Deployment" --no-verify; else echo "No changes to commit."; fi # Step: Push changes - echo "Pushing changes" - git push origin "${CI_DEFAULT_BRANCH}" -o ci.skip cache: - key: "$ENVIRONMENT-Node-deps" paths: - "node_modules/" - ".npm/" - ".cache/yarn" - key: "$ENVIRONMENT-poly-deps" paths: - "node_modules/.poly/" ``` -------------------------------- ### Deploy Server Functions with Poly Sync (Python) Source: https://docs.polyapi.io/project_glide/manual-prepare-and-sync This snippet shows how to deploy a server function using Python and the 'python3 -m polyapi sync' command. It defines the function's configuration including name, context, logging, and visibility. Upon deployment, a comment with deployment metadata is appended to the Python file. ```bash $ python3 -m polyapi sync ``` ```python # Poly deployed @ 2024-09-20T21:58:31.264Z - myContext.hello_poly - https://na1.polyapi.io/canopy/polyui/collections/server-functions/f382e9df-d591-4080-93e0-9dc2d0297444 - 75a08d6 from polyapi.typedefs import PolyServerFunction polyConfig: PolyServerFunction = { 'name': 'hello_poly', 'context': 'myContext', # you can also add in optional, additional configuration for your server function here using the helpful type hints provided by the imported PolyServerFunction type. For example: 'logsEnabled': True, 'visibility': 'TENANT', # make this function visible to all environments in your tenant } def hello_poly(first_name: str) -> str: """Function that has Poly greet a user by their name Args: first_name (str): The user's first name Returns: str: Returns a greeting from Poly """ return f"Hello {first_name}! I'm Poly, your helpful AI Assistant." ``` -------------------------------- ### Python Client Function Configuration Source: https://docs.polyapi.io/project_glide/resources Demonstrates setting up a PolyAPI Client Function in Python. Includes the necessary import, the `polyConfig` dictionary with function details, and a Python function definition with type hints and a docstring. ```python # Poly deployed @ - context.namespace.fn_name - /canopy/polyui/collections/client-functions/ - from polyapi.typedefs import PolyClientFunction polyConfig: PolyClientFunction = { 'name': 'fn_name', 'context': 'context.namespace', # other config here } def fn_name(first_name: str) -> str: """Function description Args: arg (str): Argument description Returns: str: Return description """ return "" ``` -------------------------------- ### Example Collection Configuration Source: https://docs.polyapi.io/canopy/architecture An example of a collection configuration object in Canopy. This defines the 'tasks' collection with properties like 'id', 'title', 'description', and 'status', along with CRUD operations. ```json { "collections": [ { "id": "tasks", "name": "Tasks", "group": "Dashboard", "nameProperty": "title", "properties": { "id": { "label": "ID", "readOnly": true, "excludeFromCreate": true, "excludeFromUpdate": true }, "title": { "label": "Title", "type": "text" }, "description": { "label": "Description", "type": "multiline", "autoSize": true }, "status": { "label": "Status", "type": "enum", "values": [ { "name": "To Do", "value": "TODO" }, { "name": "In Progress", "value": "IN_PROGRESS" } ] } }, "itemActions": [ "get", "update", "create" ], "create": { "actionLabel": "Add", "submitLabel": "Save", "cancelLabel": "Cancel", "function": { "path": "dashboard.createTask", "type": "server", "arguments": { "body": { "data": true } } } }, "list": { "function": { "path": "dashboard.listTasks", "type": "server" } }, "get": {}, "update": {}, "delete": {} } ] } ``` -------------------------------- ### Get Task Function - TypeScript Source: https://docs.polyapi.io/canopy/implement_crud Implements the 'get' operation to retrieve a single task by its ID. It fetches all tasks and then filters them to find the one matching the provided ID. Returns the task object or null if not found. Dependencies: 'polyapi' library. ```typescript // get-task.ts import { vari } from 'polyapi'; async function getTask(id: string): Promise { const tasks = await vari.dashboard.tasks.get(); const task = tasks.find(task => task.id === id); return task || null; } ``` -------------------------------- ### Example Canopy Application JSON Configuration Source: https://docs.polyapi.io/canopy/create_application This JSON configuration defines a Canopy application named 'Quantum Quirk'. It includes application settings, login customization, and a structured data collection example, demonstrating how to set up a management dashboard. ```json { "name": "Quantum Quirk", "description": "The ultimate management dashboard app for streamlining productivity.", "visibility": "Tenant", "config": { "layout": { "title": "Quantum Quirk Dashboard", "sections": [ { "title": "Data Collection", "fields": [ { "name": "input_field_1", "label": "First Input", "type": "text", "required": true }, { "name": "input_field_2", "label": "Second Input", "type": "number", "required": false } ] } ] }, "login": { "custom_logo": "/path/to/your/logo.png", "welcome_message": "Welcome to Quantum Quirk!" } } } ``` -------------------------------- ### Github Action for PolyAPI Deployment (Python) Source: https://docs.polyapi.io/project_glide/git-integration A Github Actions workflow file for deploying a Python project to PolyAPI. It triggers on push events to the main branch and utilizes the 'polyapi/poly-deployment-action-py' action for deployment, requiring POLY_API_KEY and POLY_API_BASE_URL secrets. ```yaml name: Deploy to PolyAPI on: push: branches: - main concurrency: group: ${{ github.ref }} cancel-in-progress: true jobs: deploy: runs-on: ubuntu-latest steps: - name: Poly Deploy uses: polyapi/poly-deployment-action-py@v0.0.8 with: poly_api_key: ${{ secrets.POLY_API_KEY }} poly_api_base_url: ${{ secrets.POLY_API_BASE_URL }} ``` -------------------------------- ### Deploy Python Function with Runtime API Key Source: https://docs.polyapi.io/generated_sdks/python Deploys a Python function with a specified runtime API key for enhanced security and granular permission control during execution. Uses the PolyAPI CLI. ```bash $ python -m polyapi function add hello hello.py --context mycontext --server --execution-api-key my-api-key ``` -------------------------------- ### Modify Specification Input - Example Source: https://docs.polyapi.io/api_functions/openapi This section provides an example of a 'Specification Input' JSON file, which defines Poly resources like API functions. It details how to modify various aspects of a function, such as its arguments, return type schema, and source configuration. ```APIDOC ## Modify a Specification Input A `Specification Input` object defines Poly resources. After generating it with `npx poly model generate ...`, you can edit the `json` file to change resource details. ### Example Specification Input ```json { "functions": [ { "name": "createPost", "context": "jsonPlaceholder", "description": "Creates a new post.", "arguments": [ { "name": "hostUrl", "type": "string", "required": true, "description": "Specifies the host URL for the service. It should be a fully qualified URL string that provides the base address of the service endpoint.", "removeIfNotPresentOnExecute": false }, { "name": "body", "type": "object", "typeSchema": { "$schema": "http://json-schema.org/draft-06/schema#", "required": [ "name" ], "properties": { "name": { "type": "string" } }, "x-readme-ref-name": "CreatePost", "definitions": {} }, "required": true, "description": "The payload containing the details of the new blog post. This should include necessary information such as the title, content, author, and any other relevant metadata required by the blog platform.", "removeIfNotPresentOnExecute": false } ], "returnType": "object", "returnTypeSchema": { "$schema": "http://json-schema.org/draft-06/schema#", "required": [ "id", "name" ], "properties": { "id": { "type": "number", "format": "int64" }, "name": { "type": "string" } }, "x-readme-ref-name": "Post", "definitions": {} }, "source": { "auth": { "type": "noauth" }, "method": "POST", "body": { "mode": "raw", "raw": "{{body}}", "language": "json" }, "url": "{{hostUrl}}/posts", "headers": [] } } ], "webhooks": [] } ``` ### Modifiable Fields You can modify details such as: * `arguments` * `name` * `returnTypeSchema` * `source` * and more... For a complete list of available options, refer to the [CreateApiFunctionDto schema](link-to-createapifunctiondto-schema) and [CreateWebhookHandleDto schema](link-to-createwebhookhandle-dto-schema). ### Validation After editing your `Specification Input`, you can validate it using the Poly library: ```bash $ npx poly model validate ./fake-json-placeholder-spec.json ``` ``` -------------------------------- ### Example of Injecting Vari Variable in Server Function (TypeScript) Source: https://docs.polyapi.io/generated_sdks/client_functions Demonstrates how to inject a 'vari' variable within a server function and pass it to a client function. This example highlights the need to pass injected variables as arguments to client functions if they are not directly accessible. ```typescript import { vari } from "polyapi"; export async function myServerFunction() { const myVariable = vari.myVariable.inject(); return await myClientFunction(myVariable); } ``` -------------------------------- ### Deploy Server Functions using PolyAPI CLI Source: https://docs.polyapi.io/canopy/implement_crud Commands to deploy the created TypeScript server functions to the 'dashboard' context using the PolyAPI CLI. Each command adds a specific function (create, list, get, update, delete) to the server. ```bash $ npx poly function add createTask create-task.ts --context dashboard --server $ npx poly function add listTasks list-tasks.ts --context dashboard --server $ npx poly function add getTask get-task.ts --context dashboard --server $ npx poly function add updateTask update-task.ts --context dashboard --server $ npx poly function add deleteTask delete-task.ts --context dashboard --server ```