bknd-custom-endpoint
Use when creating custom API endpoints in Bknd. Covers HTTP triggers with Flows, plugin routes via onServerInit, request/response handling, sync vs async modes, accessing request data, and returning custom responses.
What this skill does
# Custom Endpoint
Create custom API endpoints beyond Bknd's auto-generated CRUD routes.
## Prerequisites
- Running Bknd instance
- Basic understanding of HTTP methods and REST APIs
- Familiarity with TypeScript/JavaScript
## When to Use UI Mode
Custom endpoints require code configuration. No UI approach available.
## When to Use Code Mode
- Creating webhooks for external services
- Building custom business logic endpoints
- Adding endpoints that combine multiple operations
- Integrating with third-party APIs
- Creating public endpoints without entity CRUD
## Two Approaches
Bknd offers two ways to create custom endpoints:
| Approach | Best For | Complexity |
|----------|----------|------------|
| **Flows + HTTP Triggers** | Business logic, webhooks, multi-step processes | Medium |
| **Plugin Routes** | Simple endpoints, middleware, direct Hono access | Low |
## Approach 1: Flows with HTTP Triggers
### Step 1: Create a Basic Flow Endpoint
```typescript
import { App, Flow, HttpTrigger, LogTask } from "bknd";
// Define a flow with tasks
const helloFlow = new Flow("hello-endpoint", [
new LogTask("log", { message: "Hello endpoint called!" }),
]);
// Attach HTTP trigger
helloFlow.setTrigger(
new HttpTrigger({
path: "/api/custom/hello",
method: "GET",
})
);
// Register in app config
const app = new App({
flows: {
flows: [helloFlow],
},
});
```
**Test:**
```bash
curl http://localhost:7654/api/custom/hello
# Returns: { "success": true }
```
### Step 2: Create Endpoint with Response
Use `setRespondingTask()` to return data from a specific task:
```typescript
import { App, Flow, HttpTrigger, FetchTask } from "bknd";
const fetchTask = new FetchTask("fetch-data", {
url: "https://api.example.com/data",
method: "GET",
});
const apiFlow = new Flow("external-api", [fetchTask]);
// This task's output becomes the response
apiFlow.setRespondingTask(fetchTask);
apiFlow.setTrigger(
new HttpTrigger({
path: "/api/custom/external",
method: "GET",
response_type: "json", // "json" | "text" | "html"
})
);
```
### Step 3: Handle POST with Request Body
Access request data in tasks:
```typescript
import { App, Flow, HttpTrigger, Task } from "bknd";
import { s } from "bknd/utils";
// Custom task to process request
class ProcessTask extends Task<typeof ProcessTask.schema> {
override type = "process";
static override schema = s.strictObject({
// Define expected params (can use template syntax)
});
override async execute(input: Request) {
// input is the raw Request object
const body = await input.json();
return {
received: body,
processed: true,
timestamp: new Date().toISOString(),
};
}
}
const processTask = new ProcessTask("process-input", {});
const postFlow = new Flow("process-data", [processTask]);
postFlow.setRespondingTask(processTask);
postFlow.setTrigger(
new HttpTrigger({
path: "/api/custom/process",
method: "POST",
response_type: "json",
})
);
```
**Test:**
```bash
curl -X POST http://localhost:7654/api/custom/process \
-H "Content-Type: application/json" \
-d '{"name": "test", "value": 42}'
```
### Step 4: Sync vs Async Mode
```typescript
// Sync (default): Wait for flow completion, return result
new HttpTrigger({
path: "/api/custom/sync",
method: "POST",
mode: "sync", // Wait for completion
});
// Async: Return immediately, process in background
new HttpTrigger({
path: "/api/custom/async",
method: "POST",
mode: "async", // Fire and forget
});
// Returns: { "success": true } immediately
```
**Use async for:**
- Long-running operations
- Webhook receivers
- Background jobs
### Step 5: Multi-Task Flow with Connections
```typescript
import { Flow, HttpTrigger, FetchTask, LogTask, Condition } from "bknd";
const validateTask = new FetchTask("validate", {
url: "https://api.example.com/validate",
method: "POST",
});
const successTask = new LogTask("success", {
message: "Validation passed!",
});
const failTask = new LogTask("fail", {
message: "Validation failed!",
});
const flow = new Flow("validation-flow", [
validateTask,
successTask,
failTask,
]);
// Connect tasks with conditions
flow.task(validateTask)
.asInputFor(successTask, Condition.success())
.asInputFor(failTask, Condition.error());
flow.setRespondingTask(successTask);
flow.setTrigger(
new HttpTrigger({
path: "/api/custom/validate",
method: "POST",
})
);
```
### HTTP Trigger Options Reference
```typescript
type HttpTriggerOptions = {
path: string; // URL path (must start with /)
method?: string; // "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
response_type?: string; // "json" | "text" | "html" (default: "json")
mode?: string; // "sync" | "async" (default: "sync")
};
```
## Approach 2: Plugin Routes (Direct Hono)
For simpler endpoints, use plugins with `onServerInit`:
### Step 1: Create Plugin with Routes
```typescript
import { App, createPlugin } from "bknd";
import type { Hono } from "hono";
const customRoutes = createPlugin({
name: "custom-routes",
onServerInit: (server: Hono) => {
// Simple GET endpoint
server.get("/api/custom/status", (c) => {
return c.json({ status: "ok", timestamp: Date.now() });
});
// POST endpoint with body
server.post("/api/custom/echo", async (c) => {
const body = await c.req.json();
return c.json({ echo: body });
});
// With path parameters
server.get("/api/custom/users/:id", (c) => {
const id = c.req.param("id");
return c.json({ userId: id });
});
// With query parameters
server.get("/api/custom/search", (c) => {
const query = c.req.query("q");
const limit = c.req.query("limit") || "10";
return c.json({ query, limit: parseInt(limit) });
});
},
});
const app = new App({
plugins: [customRoutes],
});
```
### Step 2: Access App Context in Plugin Routes
```typescript
import { App, createPlugin } from "bknd";
const apiPlugin = createPlugin({
name: "api-plugin",
onServerInit: (server, { app }) => {
server.get("/api/custom/posts-count", async (c) => {
// Access data API
const em = app.modules.data?.em;
if (!em) {
return c.json({ error: "Data module not available" }, 500);
}
const count = await em.repo("posts").count();
return c.json({ count });
});
server.post("/api/custom/create-post", async (c) => {
const body = await c.req.json();
const em = app.modules.data?.em;
const post = await em.repo("posts").insertOne({
title: body.title,
content: body.content,
});
return c.json({ created: post }, 201);
});
},
});
```
### Step 3: Protected Plugin Routes
```typescript
import { createPlugin } from "bknd";
const protectedPlugin = createPlugin({
name: "protected-routes",
onServerInit: (server, { app }) => {
// Middleware for auth check
const requireAuth = async (c, next) => {
const auth = app.modules.auth;
const user = await auth?.authenticator?.verify(c.req.raw);
if (!user) {
return c.json({ error: "Unauthorized" }, 401);
}
c.set("user", user);
return next();
};
// Protected endpoint
server.get("/api/custom/profile", requireAuth, (c) => {
const user = c.get("user");
return c.json({ user });
});
// Admin-only endpoint
server.delete("/api/custom/admin/clear-cache", requireAuth, async (c) => {
const user = c.get("user");
if (user.role !== "admin") {
return c.json({ error: "Forbidden" }, 403);
}
// Clear cache logic...
return c.json({ cleared: true });
});
},
});
```
### Step 4: Plugin with Sub-Router
```typescript
import { createPlugin } from "bknd";
import { Hono } from "hono";
const webhooksPlugin = createPlugin({
name: "webhooks",
onServerInit: (server) => {
const webhooks = new Hono();
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.