Developer Tools

Endpoints in Code

With the CLI, each backend endpoint of a project is one TypeScript file, a route file under app/api/ named after the endpoint's path. Ubex compiles the file into a workflow, the same workflow you see on the canvas, and runs that. You write the endpoint in code, and you or Vira can still open it on the canvas, and the other way round.

app/api/orders/get/route.ts export default route({ method: "GET", path: "/orders/get", access: { jwt: "JWT_SECRET" }, }, async ({ input, jwt }) => { const { id } = input; // @find · Find the caller's order const order = await prisma.orders.findFirst({ where: { _id: id, customerId: jwt.sub }, }); if (!order) { // @found · Order found? // @missing · 404: not found return Response.json({ error: "Not found" }, { status: 404 }); } return Response.json({ order }); // @ok · 200 }); API Trigger GET /orders/get · JWT Find the caller's order @find · Table · findFirst Order found? @found · Condition yes no 200: order @ok 404: not found @missing
One file, one workflow. Each // @id · label comment names a step, and the label is what the canvas shows on it.

Every pulled project has the full reference in .ubex/workflow-guide.md, with the tables, buckets, AI models, other workflows and secrets that this project's code can use. Read it before writing an endpoint, and point your AI editor at it. Ubex compiles only what the guide describes, and refuses anything else with the line it is on.

The shape of a route file

import { prisma } from "@/ubex/prisma";
import { route } from "@/ubex/runtime";

export default route({
  method: "POST",
  path: "/profile/update",
  access: { jwt: "JWT_SECRET" },
}, async ({ input, jwt }) => {
  const { name } = input;
  const user = await prisma.users.update({  // @save · Save the new name
    where: { _id: jwt.sub },
    data: { name },
  });
  return Response.json({ user });  // @ok · 200: the user
});

The file sits where its path says: path: "/orders/create" is app/api/orders/create/route.ts, and path: "/orders/:id" is app/api/orders/[id]/route.ts. To move an endpoint, change its path: the next push saves it and moves the file. One route per file. Plain helper functions can go below the route.

route() settings

Setting What it does
method "GET", "POST", "PUT", "PATCH" or "DELETE", or several: ["GET", "POST"]
path The endpoint's address under /api
access Who may call it: "public", "api-key", or { jwt: "JWT_SECRET" } for signed-in users, naming the vault secret their tokens are signed with
rateLimitPerMinute Optional: calls per minute per caller. Give one to public endpoints that send email, search the web or ask a model
corsOrigins Optional: other sites allowed to call it from a browser, such as ["https://www.example.com"]. Your own app's address needs no entry
uploadFields The request fields that take a file upload. The compiler fills it in for you

What the handler gets

The handler receives one object. Take only what you read from it:

Name What it is
input The request's fields: the query parameters and the JSON body merged (the body's win). Read them by name: const { email, password } = input;
jwt On a { jwt } endpoint, the caller's verified token claims: jwt.sub (their user id), jwt.email and the rest. The gateway has already refused calls without a valid token
secrets The workspace's secrets from the Vault: secrets.JWT_SECRET
_trigger The request's details, such as _trigger.method when the route allows several methods

Answer with Response.json(body) for a 200, Response.json(body, { status: 404 }) for any other status, or new Response(text, { status: 200, headers: { "Content-Type": "text/html" } }) for text. Return the response where you make it.

Steps and their comments

Each await, each if, each return, and each run of plain computation between them is one step, one node on the canvas. Name a step with a comment at the end of its first line:

const user = await prisma.users.findFirst({ where: { email } });  // @find_user · Find the user by email
if (!user) {  // @user_found · User found?
  return Response.json({ error: "not found" }, { status: 404 });  // @not_found · 404: not found
}

The id after @ (letters, digits and _) is the step's name, and the words after · are its label on the canvas. For a step that spans several lines, put the comment alone on the line above it. Keep these comments on lines you don't change: they tie each line to its step, with its settings and its place on the canvas.

When a workflow was changed elsewhere, on the canvas or by Vira, ubex pull brings the file back in Ubex's own words, with a // @ comment on each step.

Validating the request

Check all the request's fields in one step with validate, a JSON Schema written out as an object, then the if on its result:

import { route, validate } from "@/ubex/runtime";
// ...
const check = validate({ email, password, name }, {  // @check · Valid sign-up?
  type: "object",
  required: ["email", "password"],
  properties: {
    email: { type: "string", format: "email" },
    password: { type: "string", minLength: 8 },
    name: { type: "string", maxLength: 100 },
  },
});
if (!check.valid) {
  return Response.json({ error: check.error }, { status: 400 });
}

Keywords: type, required, properties, minLength, maxLength, pattern, format (email, uri, date, date-time, uuid), minimum, maximum, enum, items, minItems, maxItems, additionalProperties. check.error is a message for the caller, such as Missing required field: password. It repeats the rejected value, so answer with your own words for a secret like a password.

Tables

Each table in db/tables.json is a model on prisma, with Prisma Client's methods. A row has _id, its columns by name, created_at and updated_at.

Method Gives
findFirst({ where, orderBy, select, include, skip }) The row or null
findUnique({ where: { _id } }) The row or null. Also by a unique column, or a unique combination: where: { email_projectId: { email, projectId } }
findMany({ where, orderBy, select, include, take, skip }) A list of rows
count({ where }) A number
groupBy({ by, where, _count, _sum, _avg, _min, _max, having, orderBy }) A list of groups
aggregate({ where, _count, _sum, _avg, _min, _max }) One object of totals
create({ data }) / createMany({ data: [...] }) The row / { count }
update({ where: { _id }, data }) / updateMany({ where, data }) The row (error P2025 if none) / { count }
upsert({ where, create, update }) The row
delete({ where: { _id } }) / deleteMany({ where }) The row / { count }
createManyAndReturn, updateManyAndReturn The rows written
prisma.$transaction([...]) Several writes, all or none, up to 1,000
  • Filters: a value, or { equals, not, in, notIn, lt, lte, gt, gte, contains, startsWith, endsWith, mode: "insensitive" }, with AND, OR and NOT. A multiselect column takes { has, hasSome, hasEvery, isEmpty }, a json column { path: ["key"], equals, string_contains, array_contains }.
  • Dates: created_at, updated_at and datetime columns are ISO strings in the workspace's time zone. Compare them as moments, new Date(a) < new Date(b), never as text.
  • Write each column by name: data: { name: profile.name, status }, never data: profile. A number column takes { increment: n } in an update.
  • List filters the caller may leave out: findMany({ where: { status, category } }, { optional: ["status", "category"] }) drops a filter whose value is empty.
  • Sorting the caller chooses: findMany({ orderBy: { [sort]: dir } }, { sortable: ["name", "created_at"] }).
  • Linked rows: a column with links_to lets you include the linked row, and _count the rows that point to it.

What else an endpoint can use

Import only what you use:

Import For
prisma from @/ubex/prisma Reading and writing the project's tables
axios from axios Calling other services: axios.get, post, put, patch, delete. Read res.status, res.data and res.body
mail from @/ubex/mail Sending email through the workspace's SMTP server: mail.send({ to, subject, html })
storage from @/ubex/storage Files in buckets: writeFile, readFile, appendFile, rename, unlink, and storage.extractText(path) for the text of a PDF, DOCX, XLSX, CSV or TXT
pdf from @/ubex/pdf Printing HTML or a public page into a PDF saved in a bucket
images from @/ubex/images resize, crop, rotate, flip and convert an image
openai / anthropic from @/ubex/openai / @/ubex/anthropic Asking an AI model, with any model your workspace offers. openai.images.generate makes images
agent, tools from @/ubex/agent An AI agent that answers, using your tables and nodes as tools
web from @/ubex/web web.search (Google results) and web.scrape (a page as text, Markdown, HTML or JSON)
realtime from @/ubex/realtime Pushing a message to the people in a WebSocket room
approval from @/ubex/approval Pausing the run until a person approves
mcp from @/ubex/mcp Calling a tool of a connection you added under Apps: mcp.call("GitHub", "create_issue", { ... })
sql from @/ubex/sql Running SQL on an external PostgreSQL or MySQL connection, with values passed safely
workflows from @/ubex/workflows Running another workflow of the project. Or import it by name from @/workflows/<folder>
route, validate and helpers from @/ubex/runtime bcryptHash, bcryptVerify, jwtSign, jwtVerify, uuid, urlEncode, urlDecode, retry, sleep, parallel, streamResponse

A sign-in endpoint, for example:

import { prisma } from "@/ubex/prisma";
import { route, validate, bcryptVerify, jwtSign } from "@/ubex/runtime";

export default route({
  method: "POST",
  path: "/auth/login",
  access: "public",
  rateLimitPerMinute: 20,
}, async ({ input, secrets }) => {
  const { email, password } = input;
  const check = validate({ email, password }, {  // @check · Valid request?
    type: "object",
    required: ["email", "password"],
    properties: { email: { type: "string", format: "email" }, password: { type: "string" } },
  });
  if (!check.valid) {
    return Response.json({ error: "Enter your email and password." }, { status: 400 });
  }
  const user = await prisma.users.findUnique({ where: { email } });  // @find · Find the user
  if (!user || !bcryptVerify(password, user.password_hash)) {  // @match · Password matches?
    return Response.json({ error: "Wrong email or password." }, { status: 401 });
  }
  const token = jwtSign({ sub: user._id, email: user.email }, secrets.JWT_SECRET);  // @sign · Sign the token
  return Response.json({ token, user: { _id: user._id, email: user.email } });
});

Running things at the same time

Calls that don't need each other's results run together with Promise.all:

const [user, orders] = await Promise.all([  // @load · Load the user and their orders
  prisma.users.findFirst({ where: { _id: jwt.sub } }),
  prisma.orders.findMany({ where: { customerId: jwt.sub } }),
]);

For longer branches that run side by side, use parallel(async () => { ... }, async () => { ... }) from @/ubex/runtime.

Errors, retries and waits

  • try { ... } catch (error) { ... }: read the error as error.message. A table error's message includes its Prisma code, such as P2025.
  • await retry(3, async () => { ... }, { delay: "1s", backoff: "exponential" }) runs the function again while it throws.
  • throw new Error("...") stops the run there.
  • await sleep("5s") waits. Over 10 seconds it pauses the run and resumes it later, so in an endpoint keep waits short.

Loops

for (const row of rows) { ... } with an await inside runs its block once per item, up to 1,000 items. Write several rows at once with createMany or prisma.$transaction rather than a loop of awaited writes.

Writing code the platform can run

The compiler is strict, so the workflow it makes is one you can read on the canvas. The rules that matter most:

  • Each await on a statement of its own, not inside expressions or callbacks such as .map.
  • A variable set again later is declared with let and set on a line of its own. Don't change an earlier step's value in place (x.push(...)): make a new one, const next = [...x, item].
  • No {{ or {% in strings: Ubex reads those as its own templates.
  • Tie user data to the caller. Behind a login, the caller is jwt.sub. Put it in the where of every read or write of a user's own rows, where: { _id: id, customerId: jwt.sub }, and answer 404 when no row matches. Check a role the request sends against the values allowed before writing it.
  • Never return password hashes or secrets.

Workflows that aren't endpoints

A file can hold another kind of trigger. It exports trigger and run instead of a route:

export const trigger = { type: "schedule", cron: "0 9 * * 1-5" };
export async function run(request) {  // @start · On weekdays at 9
  // ...
}
Trigger Settings
schedule cron (minute, hour, day of month, month, day of week) and an optional timezone, such as "Europe/Bucharest"
manual testInput, the fields a test run starts with
chat welcomeMessage. The reply is what run returns
websocket customPath and invokeFlowOnMessage

Workflows that the code cannot express are kept as workflows/*.json, which you can read but change only in the Ubex app.

Push, test and deploy

ubex push                                   # compiles; errors come back as file:line
ubex call POST /api/orders/create '{"productId":"...","qty":2}'
ubex deploy                                 # publishes the drafts with the site

ubex push --run also runs each endpoint it saves once, which writes real rows. Deleting a route file does not delete its workflow: delete workflows in the Ubex app. See Ubex CLI for drafts, tables and conflicts.

We update these pages often. Spotted something out of date? Tell us

AI AssistantPowered by Ubex
Beta
Ask me anything about Ubex workflows, nodes, or the API.