### Make First Request with cURL Source: https://zuplo.com/docs/ai-gateway/getting-started Send a test request to your Zuplo Gateway URL using cURL. This example demonstrates the necessary headers and JSON payload for interacting with chat completion endpoints. ```bash curl https://your-ai-gateway-url.zuplo.app/v1/chat/completions \ -H "Authorization: Bearer YOUR_ZUPLO_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4", "messages": [{"role": "user", "content": "Hello, world!"}] }' ``` -------------------------------- ### Install Clerk Dependencies Source: https://zuplo.com/docs/dev-portal/zudoku/configuration/authentication-clerk Command to install the required Clerk JavaScript SDK for the project. ```bash npm install @clerk/clerk-js ``` -------------------------------- ### Integrate OpenAI SDK with Zuplo AI Gateway Source: https://zuplo.com/docs/ai-gateway/getting-started Demonstrates the transition from direct OpenAI API calls to using the Zuplo AI Gateway as a proxy. This involves updating the SDK configuration to point to the Zuplo gateway URL and using a Zuplo-managed API key. ```javascript import OpenAI from "openai"; // Old approach - directly calling OpenAI const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); const completion = await openai.chat.completions.create({ model: "gpt-4", messages: [{ role: "user", content: "Hello!" }], }); console.log(completion.choices[0].message.content); ``` ```javascript import OpenAI from "openai"; // New approach - using Zuplo AI Gateway const openai = new OpenAI({ apiKey: process.env.ZUPLO_API_KEY, baseURL: "https://your-ai-gateway-url.zuplo.app/v1", }); const completion = await openai.chat.completions.create({ model: "gpt-4", messages: [{ role: "user", content: "Hello!" }], }); console.log(completion.choices[0].message.content); ``` -------------------------------- ### Get Consumer Request Examples Source: https://zuplo.com/docs/api/api-keys-consumers Examples for retrieving a specific consumer by its name. This involves a GET request to the consumer endpoint, with options to include API keys, managers, and control key formatting. Examples are provided for cURL, JavaScript, Python, Java, Go, C#, Kotlin, Ruby, and Swift. ```shell curl --request GET \ --url 'https://dev.zuplo.com/v1/accounts/{accountName}/key-buckets/{bucketName}/consumers/{consumerName}?include-api-keys=true&key-format=masked' ``` ```javascript const url = 'https://dev.zuplo.com/v1/accounts/{accountName}/key-buckets/{bucketName}/consumers/{consumerName}?include-api-keys=true&key-format=masked'; fetch(url) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` ```python import requests url = "https://dev.zuplo.com/v1/accounts/{accountName}/key-buckets/{bucketName}/consumers/{consumerName}?include-api-keys=true&key-format=masked" response = requests.get(url) print(response.json()) ``` ```java import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class GetConsumer { public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://dev.zuplo.com/v1/accounts/{accountName}/key-buckets/{bucketName}/consumers/{consumerName}?include-api-keys=true&key-format=masked") .build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { System.out.println(response.body().string()); } else { System.err.println("Error: " + response.code()); } } } } ``` ```go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { url := "https://dev.zuplo.com/v1/accounts/{accountName}/key-buckets/{bucketName}/consumers/{consumerName}?include-api-keys=true&key-format=masked" req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Println("Error creating request:", err) return } client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println("Error reading response body:", err) return } fmt.Println(string(body)) } ``` ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class GetConsumer { public static async Task Main(string[] args) { using (var client = new HttpClient()) { var url = "https://dev.zuplo.com/v1/accounts/{accountName}/key-buckets/{bucketName}/consumers/{consumerName}?include-api-keys=true&key-format=masked"; var response = await client.GetAsync(url); var responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } } ``` ```kotlin import okhttp3.OkHttpClient import okhttp3.Request fun main() { val client = OkHttpClient() val request = Request.Builder() .url("https://dev.zuplo.com/v1/accounts/{accountName}/key-buckets/{bucketName}/consumers/{consumerName}?include-api-keys=true&key-format=masked") .build() client.newCall(request).execute().use { response -> if (response.isSuccessful) { println(response.body?.string()) } else { println("Error: ${response.code}") } } } ``` ```ruby require 'net/http' require 'uri' uri = URI.parse("https://dev.zuplo.com/v1/accounts/{accountName}/key-buckets/{bucketName}/consumers/{consumerName}?include-api-keys=true&key-format=masked") request = Net::HTTP::Get.new(uri) response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(request) end puts response.body ``` ```swift import Foundation func getConsumer() { guard let url = URL(string: "https://dev.zuplo.com/v1/accounts/{accountName}/key-buckets/{bucketName}/consumers/{consumerName}?include-api-keys=true&key-format=masked") else { return } var request = URLRequest(url: url) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Error: \(error)"); return } guard let data = data else { return } if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { print(json) } } task.resume() } getConsumer() ``` -------------------------------- ### Create Lists Source: https://zuplo.com/docs/dev-portal/zudoku/markdown/overview Examples of unordered and ordered lists with support for nested items. ```markdown - Item 1 - Item 2 - Nested item - Another nested item 1. First item 2. Second item 1. Nested item 2. Another nested item ``` -------------------------------- ### Install Azure AD Browser SDK Source: https://zuplo.com/docs/dev-portal/zudoku/configuration/authentication-azure-ad This bash command installs the `@azure/msal-browser` package, which is the Microsoft Authentication Library for browsers. This SDK is essential for handling authentication flows with Azure AD in single-page applications. ```bash npm install @azure/msal-browser ``` -------------------------------- ### Create a New Zuplo API with an Official Example Source: https://zuplo.com/docs/cli/create-zuplo-api Creates a new Zuplo API project from an official example available in the Zuplo GitHub repository. The `--example` flag followed by the example name is used for this purpose. A list of available examples can be found in the Zuplo examples repository. ```bash npx create-zuplo-api@latest my-api --example my-example ``` -------------------------------- ### Complete Frontmatter Example Source: https://zuplo.com/docs/dev-portal/zudoku/markdown/frontmatter A comprehensive example demonstrating how to combine multiple frontmatter properties within a single markdown file. ```markdown --- title: Advanced Configuration Guide description: Learn how to configure advanced features in Dev Portal category: Configuration navigation_label: Advanced Config navigation_icon: settings toc: true disable_pager: false draft: false --- This page content follows the frontmatter... ``` -------------------------------- ### Create Pro Plan with Trial using cURL Source: https://zuplo.com/docs/articles/monetization/plans This snippet demonstrates how to send a POST request to the Zuplo metering API to define a plan with a trial phase and a default subscription phase. It requires a valid API key and bucket ID to execute successfully. ```shell curl \ https://dev.zuplo.com/v3/metering/$BUCKET_ID/plans \ --request POST \ --header "Authorization: Bearer $ZAPI_KEY" \ --header "Content-Type: application/json" \ --data @- << EOF { "key": "pro", "name": "Pro Plan", "description": "For growing teams with a 1-week free trial", "currency": "USD", "billingCadence": "P1M", "phases": [ { "key": "trial", "name": "Trial", "duration": "P1W", "rateCards": [ { "type": "flat_fee", "key": "api_requests", "name": "API Requests (Trial)", "featureKey": "api_requests", "billingCadence": null, "price": null, "entitlementTemplate": { "type": "metered", "issueAfterReset": 1000, "isSoftLimit": false, "usagePeriod": "P1W" } }, { "type": "flat_fee", "key": "priority_support", "name": "Priority Support (Trial)", "featureKey": "priority_support", "billingCadence": null, "price": null, "entitlementTemplate": { "type": "boolean", "config": true } } ] }, { "key": "default", "name": "Default", "duration": null, "rateCards": [ { "type": "usage_based", "key": "api_requests", "name": "API Requests", "featureKey": "api_requests", "billingCadence": "P1M", "entitlementTemplate": { "type": "metered", "issueAfterReset": 10000, "isSoftLimit": true, "usagePeriod": "P1M" }, "price": { "type": "tiered", "mode": "graduated", "tiers": [ { "upToAmount": "10000", "flatPrice": { "type": "flat", "amount": "99.00" }, "unitPrice": null }, { "flatPrice": null, "unitPrice": { "type": "unit", "amount": "0.01" } } ] } }, { "type": "flat_fee", "key": "priority_support", "name": "Priority Support", "featureKey": "priority_support", "billingCadence": null, "price": null, "entitlementTemplate": { "type": "boolean", "config": true } } ] } ] } EOF ``` -------------------------------- ### Get Tunnel Details (Objective-C) Source: https://zuplo.com/docs/api/tunnels Example of how to get tunnel details using Objective-C. This snippet demonstrates making a GET request using NSURLSession. ```objectivec #import @interface TunnelClient : NSObject @end @implementation TunnelClient - (void)getTunnelWithAccountName:(NSString *)accountName tunnelId:(NSString *)tunnelId completionHandler:(void (^)(NSString *responseString, NSError *error))completionHandler { NSString *urlString = [NSString stringWithFormat:@"https://dev.zuplo.com/v1/accounts/%@/tunnels/%@", accountName, tunnelId]; NSURL *url = [NSURL URLWithString:urlString]; NSURLSession *session = [NSURLSession sharedSession]; [[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { completionHandler(nil, error); return; } NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) { completionHandler(responseString, nil); } else { NSError *httpError = [NSError errorWithDomain:@"TunnelAPIError" code:httpResponse.statusCode userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Request failed with status: %ld", (long)httpResponse.statusCode]}]; completionHandler(nil, httpError); } }] resume]; } @end ``` -------------------------------- ### Add Free Trial to Monthly Plan (Shell) Source: https://zuplo.com/docs/articles/monetization/plan-examples This example extends the basic plan to include a 2-week free trial. After the trial, customers automatically transition to the default paid phase. The trial includes 1,000 requests and is free. ```shell curl \ https://dev.zuplo.com/v3/metering/$BUCKET_ID/plans \ --request POST \ --header "Authorization: Bearer $ZAPI_KEY" \ --header "Content-Type: application/json" \ --data @- << EOF { "key": "starter", "name": "Starter Plan", "description": "1,000 API requests per month with 2-week free trial", "currency": "USD", "billingCadence": "P1M", "phases": [ { "key": "trial", "name": "Free Trial", "duration": "P2W", "rateCards": [ { "type": "flat_fee", "key": "api_requests", "name": "API Requests (Trial)", "featureKey": "api_requests", "billingCadence": null, "price": null, "entitlementTemplate": { "type": "metered", "issueAfterReset": 1000, "isSoftLimit": false, "usagePeriod": "P2W" } } ] }, { "key": "default", "name": "Default", "duration": null, "rateCards": [ { "type": "flat_fee", "key": "api_requests", "name": "API Requests", "featureKey": "api_requests", "billingCadence": "P1M", "price": { "type": "flat", "amount": "9.99" }, "entitlementTemplate": { "type": "metered", "issueAfterReset": 1000, "isSoftLimit": false, "usagePeriod": "P1M" } } ] } ] } EOF ``` -------------------------------- ### Get Tunnel Details (C#) Source: https://zuplo.com/docs/api/tunnels Example of how to get tunnel details using C#. This snippet demonstrates making a GET request using HttpClient. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class TunnelClient { private readonly HttpClient _httpClient; public TunnelClient(HttpClient httpClient) { _httpClient = httpClient; } public async Task GetTunnelAsync(string accountName, string tunnelId) { var response = await _httpClient.GetAsync($"https://dev.zuplo.com/v1/accounts/{accountName}/tunnels/{tunnelId}"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } ``` -------------------------------- ### Configure Usage-Based Plan with Overage Charges (Shell) Source: https://zuplo.com/docs/articles/monetization/plan-examples This snippet demonstrates how to use curl to POST a new plan configuration to the Zuplo API. It defines a 'starter' plan with a free trial and a default phase that includes tiered pricing for API requests. The first 1,000 requests are a flat fee, and subsequent requests are charged at a per-unit rate, effectively implementing overage charges. The `isSoftLimit` is set to `true` to allow usage beyond the initial quota. ```shell curl \ https://dev.zuplo.com/v3/metering/$BUCKET_ID/plans \ --request POST \ --header "Authorization: Bearer $ZAPI_KEY" \ --header "Content-Type: application/json" \ --data @- << EOF { "key": "starter", "name": "Starter Plan", "description": "1,000 API requests per month with 2-week free trial and overages", "currency": "USD", "billingCadence": "P1M", "phases": [ { "key": "trial", "name": "Free Trial", "duration": "P2W", "rateCards": [ { "type": "flat_fee", "key": "api_requests", "name": "API Requests (Trial)", "featureKey": "api_requests", "billingCadence": null, "price": null, "entitlementTemplate": { "type": "metered", "issueAfterReset": 1000, "isSoftLimit": false, "usagePeriod": "P2W" } } ] }, { "key": "default", "name": "Default", "duration": null, "rateCards": [ { "type": "usage_based", "key": "api_requests", "name": "API Requests", "featureKey": "api_requests", "billingCadence": "P1M", "entitlementTemplate": { "type": "metered", "issueAfterReset": 1000, "isSoftLimit": true, "usagePeriod": "P1M" }, "price": { "type": "tiered", "mode": "graduated", "tiers": [ { "upToAmount": "1000", "flatPrice": { "type": "flat", "amount": "9.99" }, "unitPrice": null }, { "flatPrice": null, "unitPrice": { "type": "unit", "amount": "0.01" } } ] } } ] } ] } EOF ``` -------------------------------- ### Get Tunnel Details (JavaScript) Source: https://zuplo.com/docs/api/tunnels Example of how to get tunnel details using JavaScript. This snippet demonstrates making a GET request to the tunnel endpoint. ```javascript async function getTunnel(accountName, tunnelId) { const response = await fetch(`https://dev.zuplo.com/v1/accounts/${accountName}/tunnels/${tunnelId}`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.json(); } ``` -------------------------------- ### Initialize Migration Environment Source: https://zuplo.com/docs/dev-portal/migration Commands to clone the existing repository and create a new feature branch for the migration process. ```bash git clone https://github.com/my-org/my-api cd my-api git checkout -b dev-portal-migration ``` -------------------------------- ### Deploying Zuplo Configuration via Git Source: https://zuplo.com/docs/articles/terraform Demonstrates the standard GitOps workflow for managing Zuplo projects. This process involves cloning the repository, modifying configuration files, and pushing changes to trigger an automatic deployment. ```bash # Clone your Zuplo project git clone https://github.com/your-org/your-zuplo-project.git # Make changes to your API configuration # Edit config/routes.oas.json, add policies, etc. # Deploy your changes git add . git commit -m "Add rate limiting policy" git push origin main ``` -------------------------------- ### Get Tunnel Details (Kotlin) Source: https://zuplo.com/docs/api/tunnels Example of how to get tunnel details using Kotlin. This snippet demonstrates making a GET request using Ktor Client. ```kotlin import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* object TunnelClient { private val client = HttpClient() suspend fun getTunnel(accountName: String, tunnelId: String): String { val response = client.get("https://dev.zuplo.com/v1/accounts/$accountName/tunnels/$tunnelId") if (!response.status.isSuccess()) { throw Exception("Failed to get tunnel: ${response.status}") } return response.bodyAsText() } } ``` -------------------------------- ### Get Tunnel Details (Java) Source: https://zuplo.com/docs/api/tunnels Example of how to get tunnel details using Java. This snippet demonstrates making a GET request using Apache HttpClient. ```java import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class TunnelClient { public String getTunnel(String accountName, String tunnelId) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet request = new HttpGet(String.format("https://dev.zuplo.com/v1/accounts/%s/tunnels/%s", accountName, tunnelId)); try (var response = client.execute(request)) { if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) { return EntityUtils.toString(response.getEntity()); } else { throw new IOException("Failed to get tunnel: " + response.getStatusLine()); } } } } } ``` -------------------------------- ### Get Tunnel Details (Python) Source: https://zuplo.com/docs/api/tunnels Example of how to get tunnel details using Python. This snippet demonstrates making a GET request using the 'requests' library. ```python import requests def get_tunnel(account_name, tunnel_id): url = f"https://dev.zuplo.com/v1/accounts/{account_name}/tunnels/{tunnel_id}" response = requests.get(url) response.raise_for_status() # Raise an exception for bad status codes return response.json() ``` -------------------------------- ### Initialize a New Zuplo API Project Source: https://zuplo.com/docs/cli/create-zuplo-api The basic command to start the creation process for a new Zuplo API. This command will prompt the user for necessary information to set up the project. ```bash npx create-zuplo-api@latest ``` -------------------------------- ### Get Tunnel Teardown Status (C#) Source: https://zuplo.com/docs/api/tunnels Example of how to get the teardown status of a tunnel using C#. This snippet demonstrates making a GET request using HttpClient. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class TunnelClient { private readonly HttpClient _httpClient; public TunnelClient(HttpClient httpClient) { _httpClient = httpClient; } public async Task GetTeardownStatusAsync(string accountName, string tunnelId, string operationId) { var response = await _httpClient.GetAsync($"https://dev.zuplo.com/v1/accounts/{accountName}/tunnels/{tunnelId}/teardown-operations/{operationId}"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } ``` -------------------------------- ### Get Tunnel Details (Go) Source: https://zuplo.com/docs/api/tunnels Example of how to get tunnel details using Go. This snippet demonstrates making a GET request using the standard 'net/http' package. ```go package main import ( "fmt" "io/ioutil" "net/http" ) func getTunnel(accountName string, tunnelId string) (string, error) { url := fmt.Sprintf("https://dev.zuplo.com/v1/accounts/%s/tunnels/%s", accountName, tunnelId) resp, err := http.Get(url) if err != nil { return "", fmt.Errorf("failed to make request: %w", err) } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return "", fmt.Errorf("request failed with status: %d", resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("failed to read response body: %w", err) } return string(body), nil } ``` -------------------------------- ### Get Tunnel Teardown Status (Kotlin) Source: https://zuplo.com/docs/api/tunnels Example of how to get the teardown status of a tunnel using Kotlin. This snippet demonstrates making a GET request using Ktor Client. ```kotlin import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* object TunnelClient { private val client = HttpClient() suspend fun getTeardownStatus(accountName: String, tunnelId: String, operationId: String): String { val response = client.get("https://dev.zuplo.com/v1/accounts/$accountName/tunnels/$tunnelId/teardown-operations/$operationId") if (!response.status.isSuccess()) { throw Exception("Failed to get teardown status: ${response.status}") } return response.bodyAsText() } } ``` -------------------------------- ### Define Zudoku Configuration Source: https://zuplo.com/docs/dev-portal/migration Example of the zudoku.config.ts file used to define site metadata and navigation structure. ```typescript import type { ZudokuConfig } from "zudoku"; const config: ZudokuConfig = { site: { title: "My API", }, metadata: { favicon: "https://www.example.org/favicon.ico", }, navigation: [ { type: "category", label: "Documentation", items: [] } ] }; ``` -------------------------------- ### Get Tunnel Teardown Status (Java) Source: https://zuplo.com/docs/api/tunnels Example of how to get the teardown status of a tunnel using Java. This snippet demonstrates making a GET request using Apache HttpClient. ```java import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class TunnelClient { public String getTeardownStatus(String accountName, String tunnelId, String operationId) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet request = new HttpGet(String.format("https://dev.zuplo.com/v1/accounts/%s/tunnels/%s/teardown-operations/%s", accountName, tunnelId, operationId)); try (var response = client.execute(request)) { if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) { return EntityUtils.toString(response.getEntity()); } else { throw new IOException("Failed to get teardown status: " + response.getStatusLine()); } } } } } ``` -------------------------------- ### Application Configuration Source: https://zuplo.com/docs/dev-portal/zudoku/components/syntax-highlight XML configuration file defining application settings and module status for the Zudoku project. ```xml ``` -------------------------------- ### Get Tunnel Teardown Status (Python) Source: https://zuplo.com/docs/api/tunnels Example of how to get the teardown status of a tunnel using Python. This snippet demonstrates making a GET request using the 'requests' library. ```python import requests def get_teardown_status(account_name, tunnel_id, operation_id): url = f"https://dev.zuplo.com/v1/accounts/{account_name}/tunnels/{tunnel_id}/teardown-operations/{operation_id}" response = requests.get(url) response.raise_for_status() return response.json() ``` -------------------------------- ### Define and Manage User Objects Source: https://zuplo.com/docs/dev-portal/zudoku/components/syntax-highlight This snippet demonstrates how to define a user data structure, instantiate it, and display its properties. It covers the use of structs in Common Lisp and classes in PowerShell. ```lisp (defstruct user id name email) (defun create-user (id name email) (make-user :id id :name name :email email)) (defun display-user (user) (format t "User: ~A (ID: ~A)~%" (user-name user) (user-id user))) ;; Usage (let ((user (create-user 1 "Alice" "alice@example.com"))) (display-user user)) ``` ```powershell class User { [int]$Id [string]$Name [string]$Email User([int]$id, [string]$name, [string]$email) { $this.Id = $id $this.Name = $name $this.Email = $email } [void]Display() { Write-Host "User: $($this.Name) (ID: $($this.Id))" } } # Usage $user = [User]::new(1, "Alice", "alice@example.com") $user.Display() ``` -------------------------------- ### Get Tunnel Teardown Status (JavaScript) Source: https://zuplo.com/docs/api/tunnels Example of how to get the teardown status of a tunnel using JavaScript. This snippet demonstrates making a GET request to the teardown operations endpoint. ```javascript async function getTeardownStatus(accountName, tunnelId, operationId) { const response = await fetch(`https://dev.zuplo.com/v1/accounts/${accountName}/tunnels/${tunnelId}/teardown-operations/${operationId}`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.json(); } ``` -------------------------------- ### Get Tunnel Teardown Status (Go) Source: https://zuplo.com/docs/api/tunnels Example of how to get the teardown status of a tunnel using Go. This snippet demonstrates making a GET request using the standard 'net/http' package. ```go package main import ( "fmt" "io/ioutil" "net/http" ) func getTeardownStatus(accountName string, tunnelId string, operationId string) (string, error) { url := fmt.Sprintf("https://dev.zuplo.com/v1/accounts/%s/tunnels/%s/teardown-operations/%s", accountName, tunnelId, operationId) resp, err := http.Get(url) if err != nil { return "", fmt.Errorf("failed to make request: %w", err) } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return "", fmt.Errorf("request failed with status: %d", resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("failed to read response body: %w", err) } return string(body), nil } ``` -------------------------------- ### Create a New Zuplo API with Default Template Source: https://zuplo.com/docs/cli/create-zuplo-api Initializes a new Zuplo API project using the default template. After execution, you will be prompted for project name, ESLint, and Prettier configurations. It's recommended to run `npm run dev` after setting up the project. ```bash npx create-zuplo-api@latest my-api cd my-api npm run dev ``` -------------------------------- ### Implement Advanced Syntax Highlighting Source: https://zuplo.com/docs/dev-portal/zudoku/markdown/overview Shows how to use Shiki features like line highlighting, word highlighting, line numbers, and file titles. ```tsx import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ; } ``` -------------------------------- ### Get Who Am I (Swift) Source: https://zuplo.com/docs/api/~endpoints Retrieves basic information about the caller using their API key via Swift's URLSession. This example demonstrates a GET request to the /v1/who-am-i endpoint. ```swift import Foundation func getWhoAmI() { guard let url = URL(string: "https://dev.zuplo.com/v1/who-am-i") else { return } let task = URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { print("Error: \(error.localizedDescription)") return } guard let data = data else { return } if let responseString = String(data: data, encoding: .utf8) { print(responseString) } } task.resume() } ``` -------------------------------- ### Get Who Am I (Objective-C) Source: https://zuplo.com/docs/api/~endpoints Retrieves basic information about the caller using their API key via Objective-C's NSURLSession. This example demonstrates a GET request to the /v1/who-am-i endpoint. ```objectivec #import - (void)getWhoAmI { NSURL *url = [NSURL URLWithString:@"https://dev.zuplo.com/v1/who-am-i"]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"Error: %@", error.localizedDescription); return; } NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", responseString); }]; [task resume]; } ``` -------------------------------- ### Complete Site Configuration Example - TSX Source: https://zuplo.com/docs/dev-portal/zudoku/configuration/site A comprehensive example demonstrating the configuration of title, logo (with light/dark variants and width), and a dismissible banner with a specified color. ```tsx { site: { title: "My API Documentation", logo: { src: { light: "/images/logo-light.svg", dark: "/images/logo-dark.svg" }, alt: "Company Logo", width: "100px", }, banner: { message: "Welcome to our documentation!", color: "info", dismissible: true }, } } ``` -------------------------------- ### Example llms.txt Output Source: https://zuplo.com/docs/dev-portal/zudoku/configuration/llms This is an example of the `llms.txt` file generated by the Dev Portal when the `llmsTxt` option is enabled. It provides a summarized list of documentation pages with direct links, facilitating easy navigation for LLMs. ```markdown # Documentation - [Quickstart](/dev-portal/zudoku/quickstart.md): Get started with Dev Portal - [Writing](/dev-portal/zudoku/writing.md): A guide to writing documentation ``` -------------------------------- ### Get Who Am I (PHP) Source: https://zuplo.com/docs/api/~endpoints Retrieves basic information about the caller using their API key via PHP's cURL functions. This example performs a GET request to the /v1/who-am-i endpoint. ```php ``` -------------------------------- ### Get Who Am I (Kotlin) Source: https://zuplo.com/docs/api/~endpoints Retrieves basic information about the caller using their API key via Kotlin's http-client. This example shows a basic GET request to the /v1/who-am-i endpoint. ```kotlin import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.client.* import kotlinx.coroutines.runBlocking fun main() = runBlocking { val client = HttpClient() try { val response: HttpResponse = client.get("https://dev.zuplo.com/v1/who-am-i") println(response.bodyAsText()) } catch (e: Exception) { println("Error: ${e.message}") } finally { client.close() } } ``` -------------------------------- ### Create and deploy a new environment via Git Source: https://zuplo.com/docs/articles/branch-based-deployments Demonstrates how to create a new Git branch and push it to the repository to trigger an automatic deployment of a new Zuplo environment. ```bash git checkout -b my-new-feature git push -u origin my-new-feature ``` -------------------------------- ### Get Who Am I (C#) Source: https://zuplo.com/docs/api/~endpoints Retrieves basic information about the caller using their API key via C#'s HttpClient. This example demonstrates an asynchronous GET request to the /v1/who-am-i endpoint. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class WhoAmIClient { public static async Task GetWhoAmIAsync() { using (HttpClient client = new HttpClient()) { try { HttpResponseMessage response = await client.GetAsync("https://dev.zuplo.com/v1/who-am-i"); response.EnsureSuccessStatusCode(); // Throw if HTTP status code is not 2xx string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } } } } ``` -------------------------------- ### Initialize StreamingZoneCache Source: https://zuplo.com/docs/programmable-api/streaming-zone-cache Demonstrates how to instantiate the StreamingZoneCache using a ZuploContext or custom CacheOptions. ```ts new StreamingZoneCache(name: string, context: ZuploContext) new StreamingZoneCache(name: string, options: CacheOptions) ``` -------------------------------- ### Get Who Am I (Go) Source: https://zuplo.com/docs/api/~endpoints Retrieves basic information about the caller using their API key via Go's net/http package. This example performs a GET request to the /v1/who-am-i endpoint. ```go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { resp, err := http.Get("https://dev.zuplo.com/v1/who-am-i") if err != nil { fmt.Println("Error making request:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response body:", err) return } fmt.Println(string(body)) } ``` -------------------------------- ### Initialize Zuplo Runtime Extensions Source: https://zuplo.com/docs/programmable-api/runtime-extensions This code snippet shows the basic structure for initializing runtime extensions in Zuplo. It imports `RuntimeExtensions` and defines the `runtimeInit` function, which is the entry point for global gateway configuration. Any errors thrown here will prevent the gateway from starting. ```typescript import { RuntimeExtensions } from "@zuplo/runtime"; export function runtimeInit(runtime: RuntimeExtensions) { // Extensions go here } ``` -------------------------------- ### Get Who Am I (Java) Source: https://zuplo.com/docs/api/~endpoints Retrieves basic information about the caller using their API key via Java's HttpURLConnection. This example demonstrates a basic GET request to the /v1/who-am-i endpoint. ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; try { URL url = new URL("https://dev.zuplo.com/v1/who-am-i"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } ``` -------------------------------- ### Publish Plan API Request Examples Source: https://zuplo.com/docs/api/metering-plans Examples of how to publish a plan using the Zuplo API. This includes cURL and various programming language SDKs. The request targets the metering endpoint to publish a specific plan within a bucket. ```shell curl --request POST \ --url https://dev.zuplo.com/v3/metering/:bucketId/plans/:planId/publish ``` ```javascript fetch('https://dev.zuplo.com/v3/metering/:bucketId/plans/:planId/publish', { method: 'POST' }).then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` ```python import requests url = "https://dev.zuplo.com/v3/metering/:bucketId/plans/:planId/publish" response = requests.post(url) print(response.json()) ``` ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class PublishPlan { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://dev.zuplo.com/v3/metering/:bucketId/plans/:planId/publish")) .POST(HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } } ``` ```go package main import ( "fmt" "net/http" "io/ioutil" ) func main() { url := "https://dev.zuplo.com/v3/metering/:bucketId/plans/:planId/publish" resp, err := http.Post(url, "", nil) if err != nil { fmt.Println("Error:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response body:", err) return } fmt.Println(string(body)) } ``` ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class PublishPlan { public static async Task Main(string[] args) { using (var client = new HttpClient()) { var url = "https://dev.zuplo.com/v3/metering/:bucketId/plans/:planId/publish"; var response = await client.PostAsync(url, null); var responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } } ``` ```kotlin import java.net.HttpURLConnection import java.net.URL fun main() { val url = URL("https://dev.zuplo.com/v3/metering/:bucketId/plans/:planId/publish") with(url.openConnection() as HttpURLConnection) { requestMethod = "POST" val responseCode = responseCode val responseBody = inputStream.bufferedReader().use { it.readText() } println("Response Code: $responseCode") println("Response Body: $responseBody") } } ``` ```objectivec #import int main(int argc, const char * argv[]) { @autoreleasepool { NSURL *url = [NSURL URLWithString:@"https://dev.zuplo.com/v3/metering/:bucketId/plans/:planId/publish"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"Error: %@\n", error); return; } NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Response: %@\n", responseString); }]; [task resume]; // Keep the main thread alive to allow the network request to complete [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5]]; } return 0; } ``` ```php ``` ```ruby require 'net/http' require 'uri' uri = URI.parse("https://dev.zuplo.com/v3/metering/:bucketId/plans/:planId/publish") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true # if your URL is HTTPS request = Net::HTTP::Post.new(uri.request_uri) response = http.request(request) puts response.body ``` ```swift import Foundation let url = URL(string: "https://dev.zuplo.com/v3/metering/:bucketId/plans/:planId/publish")! var request = URLRequest(url: url) request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Error: \(error)\n") return } if let httpResponse = response as? HTTPURLResponse { print("Status Code: \(httpResponse.statusCode)\n") } if let data = data, let dataString = String(data: data, encoding: .utf8) { print("Response: \(dataString)\n") } } task.resume() ```