Devmachinist /Docs
Sign in Start
All docs

Data API (REST)

Every API you design in the API tab is served live at /_api/<apiId>. Each model gets list, get, create, update and delete endpoints, backed by the API's own SQLite database. Your published site, your native apps, other websites and your own servers all call the same endpoints.

This page is the HTTP reference. Inside a project you usually call it through the generated JavaScript client instead of writing requests yourself. Designing models and rules is covered in API builder.

Base URL #

http
https://devmachinist.com/_api/<apiId>

An API id is 14 lowercase letters and digits, for example mhx3q9zk4f7p2a. You find it in the API tab under Use in App, and in the BASE line of your project's src/api/<slug>.js.

The /_api path is answered on every host the server serves, not just the main one. A published site on its own subdomain or custom domain can call /_api/<apiId> on its own address, and the request reaches the same API. That is what the generated client does: it uses a relative URL.

Native builds have no web origin of their own, so the client reads a global first:

js
// From the generated src/api/<slug>.js
export const BASE = (globalThis.__PB_API_ORIGIN__ || '') + '/_api/mhx3q9zk4f7p2a'

Android, desktop and server-built app exports put <script>window.__PB_API_ORIGIN__ = "https://devmachinist.com"</script> at the top of the built index.html, so the same code reaches https://devmachinist.com/_api/<apiId>. On the web the global is unset and requests stay on the site's own origin.

A first request #

bash
curl https://devmachinist.com/_api/mhx3q9zk4f7p2a/product?_limit=2
json
{
  "data": [
    { "id": 1, "name": "Linen apron", "price": 34, "stock": 12, "featured": true, "category_id": 2 },
    { "id": 2, "name": "Oak board", "price": 48.5, "stock": 3, "featured": false, "category_id": 1 }
  ],
  "total": 17,
  "page": 1,
  "limit": 2,
  "pageCount": 9
}
js
const res = await fetch('https://devmachinist.com/_api/mhx3q9zk4f7p2a/product?_limit=2')
const { data, total } = await res.json()

CORS, cookies and request bodies #

The runtime is open to every origin and never uses cookies, so a page on any domain can call it.

HeaderValue
Access-Control-Allow-Origin*
Access-Control-Allow-MethodsGET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-HeadersContent-Type, Authorization, X-API-Key, X-PB-Device
Access-Control-Max-Age600

Preflight OPTIONS requests get 204 No Content. Send bodies as JSON with Content-Type: application/json (up to 20 MB). URL-encoded form bodies are accepted too.

Country access settings on the server don't apply to /_api, so visitors from anywhere can use your app's data.

Signing in #

Models that need a signed-in person read a token from the Authorization header:

http
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

You get the token from POST /_api/<apiId>/auth/login or /auth/register. Tokens are per API and last 7 days unless the API sets another session length. Sign-up, sign-in, providers and account routes are documented in App sign-in.

Discover an API #

GET /_api/<apiId> describes the API: its name, which sign-in methods are on, and every model with its path and fields. It needs no token.

bash
curl https://devmachinist.com/_api/mhx3q9zk4f7p2a
json
{
  "api": "Shop",
  "auth": { "enabled": true, "password": true, "providers": [] },
  "resources": [
    {
      "name": "Product",
      "path": "/product",
      "fields": [
        { "name": "id", "type": "id", "required": false, "ref": null },
        { "name": "name", "type": "string", "required": true, "ref": null },
        { "name": "price", "type": "float", "required": false, "ref": null },
        { "name": "category_id", "type": "reference", "required": false, "ref": { "model": "Category", "field": "id" } }
      ]
    }
  ]
}

Resources and paths #

A model's path is its name in lower case with anything other than letters, digits and underscores removed: Product is /product, BlogPost is /blogpost, order_item is /order_item. The match is case-insensitive.

MethodPathDoesRule checked
GET/_api/<apiId>/<model>List rowsread
GET/_api/<apiId>/<model>/<id>Get one rowread
POST/_api/<apiId>/<model>Add a rowcreate
PATCH/_api/<apiId>/<model>/<id>Change the fields you sendwrite
PUT/_api/<apiId>/<model>/<id>Replace every fieldwrite
DELETE/_api/<apiId>/<model>/<id>Delete a rowwrite

A row's id is its id field (type id), which the database numbers for you. Other methods get 405.

Responses from the runtime are plain JSON: a row, a list object, or { "error": "…" }. They don't carry the ok flag the platform API uses.

List rows #

http
GET /_api/<apiId>/<model>?<filters>&_sort=&_order=&_limit=&_page=&_offset=&_q=&_expand=

The response always has the same shape:

FieldMeaning
dataThe rows on this page
totalHow many rows match the filters, across all pages
pageThe _page you asked for (1 when you didn't)
limitRows per page after clamping
pageCounttotal divided by limit, rounded up

Rows only contain the fields the model defines. Booleans come back as true or false and JSON fields as parsed JSON.

Filters #

Any query parameter that names a field filters on it. Add a suffix for other comparisons. Parameters that start with _ are options, and names that aren't fields are ignored.

ParameterMatches rows where
field=valuethe field equals the value
field_ne=valuethe field is not the value
field_gt=valuethe field is greater than the value
field_gte=valuegreater than or equal
field_lt=valueless than
field_lte=valueless than or equal
field_like=textthe field contains the text (case-insensitive for plain letters)
field_in=a,b,cthe field is one of the comma-separated values

Filters combine with AND. Values are converted to the field's type first, so featured=true matches a boolean field and price_lt=20 compares numbers. Dates are stored as text, so published_at_gte=2026-01-01 compares ISO dates correctly.

bash
# Products under 20 in category 2 or 5, that are in stock
curl "https://devmachinist.com/_api/mhx3q9zk4f7p2a/product?price_lt=20&category_id_in=2,5&stock_gt=0"

_q looks for the text anywhere in the model's string, text, email, url and enum fields (any one of them may match). It combines with filters.

bash
curl "https://devmachinist.com/_api/mhx3q9zk4f7p2a/product?_q=linen&featured=true"

Sorting #

_sort takes a field name and _order takes asc (the default) or desc. A _sort that isn't a field is ignored, and without one the order isn't guaranteed. To get newest first, sort by id:

bash
curl "https://devmachinist.com/_api/mhx3q9zk4f7p2a/product?_sort=id&_order=desc"

Paging #

ParameterDefaultNotes
_limit50Clamped to 1 to 1000
_page11-based
_offsetnoneSkips this many rows; when set it wins over _page
js
async function allProducts() {
  const rows = []
  for (let page = 1; ; page++) {
    const r = await fetch(`https://devmachinist.com/_api/mhx3q9zk4f7p2a/product?_limit=200&_page=${page}&_sort=id`).then(r => r.json())
    rows.push(...r.data)
    if (page >= r.pageCount) return rows
  }
}

Expanding references #

_expand takes a comma-separated list of reference fields. Each listed field adds <field>_expanded to every row: the referenced row, or null when it doesn't exist or you may not read it. It works on lists and on single rows. The linked model's own rules apply: its read rule, its owner rows and its visibleWhen, so expanding never shows a row you couldn't read directly.

bash
curl "https://devmachinist.com/_api/mhx3q9zk4f7p2a/product/1?_expand=category_id"
json
{
  "id": 1,
  "name": "Linen apron",
  "price": 34,
  "category_id": 2,
  "category_id_expanded": { "id": 2, "name": "Kitchen" }
}
Expanded rows are read straight from the referenced model: its own read rule and hidden-row condition are not applied to them. Don't point a public model at a model whose rows must stay private.

Get one row #

bash
curl https://devmachinist.com/_api/mhx3q9zk4f7p2a/product/1

Returns the row, or 404 {"error":"Not found"}. _expand works here too.

Add a row #

bash
curl -X POST https://devmachinist.com/_api/mhx3q9zk4f7p2a/product \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"name":"Clay mug","price":18,"stock":40,"featured":false,"category_id":2}'
json
{ "id": 18, "name": "Clay mug", "price": 18, "stock": 40, "featured": false, "category_id": 2 }

The answer is 201 Created with the stored row, id included. Fields you leave out get their default value when the field has one, otherwise null. Fields the model doesn't have are ignored. An empty body adds a row of defaults.

js
const res = await fetch('https://devmachinist.com/_api/mhx3q9zk4f7p2a/message', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Ada', email: 'ada@example.com', body: 'Hello!' }),
})
if (!res.ok) throw new Error((await res.json()).error)
const saved = await res.json()

Change a row #

PATCH changes only the fields in the body and returns the whole row.

bash
curl -X PATCH https://devmachinist.com/_api/mhx3q9zk4f7p2a/product/18 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"stock":38}'

PUT replaces the row: every field you leave out is set to null (defaults don't apply). A required field left out makes the request fail with a NOT NULL constraint failed error. Prefer PATCH unless you mean to clear fields. A body with no known fields returns the row unchanged.

Both answer 404 {"error":"Not found"} when the id doesn't exist.

Delete a row #

bash
curl -X DELETE https://devmachinist.com/_api/mhx3q9zk4f7p2a/product/18 \
  -H "Authorization: Bearer $TOKEN"
json
{ "ok": true, "deleted": "18" }

deleted is the id from the URL, as text. Rows in other models that referenced it are left as they are.

Field types #

TypeStored asSend and receive
idinteger, numbered automaticallynumber; ignored on writes
string, texttextstring
integerintegernumber; decimals are cut off
floatrealnumber
boolean0 or 1true or false; the strings "false" and "0" count as false
date, datetimetextstring, ideally ISO 8601 such as 2026-11-13
uuid, email, urltextstring
enumtextone of the field's values
referenceintegerthe id of a row in the referenced model
jsontextany JSON value, returned parsed

Validation #

The runtime checks these before writing:

  • Required fields. A create without a required field (and no default) answers 400 with Field "name" is required.
  • Numbers and references. Text in an integer, float or reference field answers 400 naming the field, for example Field "price" must be a number or Field "category_id" must be the id of a Category (a number).
  • JSON shapes. A json field can declare the shape the app relies on (jsonShape). A value of another shape answers 400.
  • Unique fields. A duplicate value answers 400 with the database's message, for example UNIQUE constraint failed: product.sku.
jsonShapeAcceptsError says
listany arraymust be a list
objecta plain objectmust be an object
mapan object whose values are strings or numbers, such as {"Color":"Black","Size":"M"}must be an object of text values
optionList[{"name":"Size","kind":"text","values":[{"label":"M"}]}]; kind may be color or text, and a value may carry a swatchmust be a list of options like …
The runtime does not check that an enum value is one of the field's values, that an email or url looks right, or that a reference points at a row that exists. Check those in your form, or in code that reads the data.

Access rules #

Each model has three rules, set in API → Auth:

RuleApplies toShown in the API tab as
readGET lists and single rowsread
createPOSTadd
writePATCH, PUT, DELETEedit

A model without its own rule uses the API's default rule (__default), and then public. A missing create rule falls back to the model's write rule, then the default create, then the default write.

Each rule is one of these words, or a custom role name:

RuleWho passesWithout a valid tokenWith the wrong account
publicanyoneallowedallowed
authany signed-in account (Signed in)401not possible
ownerthe account the row belongs to, and admins401404 Not found
adminaccounts with the role admin401403 Admins only
nonenobody over HTTP; only the API's owner in the builder403403
a custom role, such as editorthat role and admins401403 Only editor accounts
With sign-in off for the API, nobody can sign in, so every model is open to everyone — except none (builder-only) rules and visibleWhen, which hold either way. Anyone can read, add, change and delete rows of every other model. Turn sign-in on before you publish an app that stores anything people shouldn't change.

Roles are read from the database on every request, so promoting or demoting someone takes effect at once, even for a token issued earlier.

Rows people own #

Under owner, the server links rows to accounts through an owner field. It is the field named in the model's ownerField setting, otherwise the first field called user_id, userid, owner, owner_id, ownerid, author, created_by or createdby (any case). Make it a string field: account ids are text such as mhx40b1c9a2kd3.

For someone who isn't an admin:

  • Lists only return their rows. The owner filter replaces any value you pass for that field.
  • Creating stamps their account id into the owner field, whatever the body says.
  • Getting, changing or deleting another account's row answers 404 Not found, so ids of other people's rows aren't revealed.

Admins see and change every row. A model with an owner rule but no owner field only requires sign-in.

bash
# A signed-in customer's own orders
curl https://devmachinist.com/_api/mhx3q9zk4f7p2a/order -H "Authorization: Bearer $TOKEN"

Changing a row (PUT or PATCH) as someone who isn't an admin keeps their account id in the owner field: a change can neither clear the owner nor hand the row to someone else.

Hidden rows #

A model can have a visibleWhen condition, such as the blog's { "status": "published" }. Anyone who isn't an admin only ever reads rows that match it: lists are filtered, and a single row that doesn't match answers 404. Only fields the model has count. It applies whether or not sign-in is on. Admins (with their token) read everything, drafts included.

Memberships and metered reads #

When an API sells memberships, one model holds the paid content (the blog's Post, field body, by default). Reads of that model change for anyone who isn't a member or an admin:

  • Lists return the paid field as null in every row, so lists carry excerpts only.
  • A single row costs one of the free reads per month. Reading the same row again that month costs nothing.
  • When the free reads are used up, the paid field is null and the row has "_locked": true.
  • Every single row carries _meter with the allowance and what's left.
  • Free rows: a row with free: true or premium: false is never counted, and its _meter has "unlimited": true.
json
{
  "id": 7,
  "title": "Winter menu",
  "body": null,
  "_locked": true,
  "_meter": { "free": 3, "used": 3, "left": 0, "signedIn": false }
}

Signed-in readers are counted per account. Signed-out readers are counted per device: send a stable random id in the X-PB-Device header (the generated client does). Without it the server uses the network address and browser. Signed-out readers on one network also share a cap of five times the free allowance a month.

Plans, GET /membership and subscribing are covered in Payments.

Errors #

Errors are JSON with an error message:

json
{ "error": "Authentication required" }
StatusWhenerror
400A required field is missing, a value has the wrong type or shape, a unique value is taken, or the database refused the writethe reason, naming the field
401The rule needs sign-in and the token is missing, expired, for another API, older than the account's last password change, or for a deleted accountAuthentication required
403The rule is noneNot readable through the public API (reads) or Managed by the site owner (writes)
403The rule is admin and the account isn't oneAdmins only
403The rule is a custom role the account doesn't haveOnly <role> accounts
404No API with that idAPI not found
404No model with that pathUnknown resource "<name>"
404No row with that id, a hidden row, or another account's row under ownerNot found
405Any other methodMethod <METHOD> not allowed
429Rate limit reachedToo many requests — try again in <n>s
503The data store isn't available on this serverInternal data store unavailable

The 429 body is { "ok": false, "error": "…" } and comes with a Retry-After header in seconds.

js
async function call(path, options) {
  const res = await fetch('https://devmachinist.com/_api/mhx3q9zk4f7p2a' + path, options)
  const body = await res.json().catch(() => null)
  if (res.status === 429) throw new Error(`Slow down, retry in ${res.headers.get('Retry-After')}s`)
  if (!res.ok) throw new Error(body?.error || `HTTP ${res.status}`)
  return body
}

Rate limits #

Limits are counted per client IP address, in fixed windows:

LimitApplies to
300 requests a minuteeverything under /_api, across all APIs
1200 requests a minuteevery request to the server
30 per 10 minutessign-up, sign-in, changing your name or password and deleting your account (shared)
30 per 10 minutesstarting a checkout
120 per 10 minutesuploading and deleting app files

A server that calls the API for many people counts as one client. Keep server-side calls light, or cache them.

OpenAPI spec #

Each API has an OpenAPI 3.0.3 spec: open the API in the builder and choose Spec. It lists every model's paths, request and response schemas, the paging and search parameters and the _like, _gt, _lt and _in filters, with /_api/<apiId> as the server URL. The _gte, _lte and _ne filters work as well, though the spec doesn't list them.

The spec is part of the builder, not the public runtime: no /_api route serves it.

Other routes under /_api #

These share the /_api/<apiId> prefix and are documented on their own pages.

PathWhatPage
/auth/...sign-up, sign-in, the current account, providers, robot checkApp sign-in
/files, /files/<name>files uploaded by the app's usersFiles
/payments, /checkout, /membership, /storethe store's Stripe checkout, memberships and shippingPayments
/track, /admin/traffic, /admin/users, /admin/membershippage views and the app's own admin tools (admins only for /admin)App sign-in
/integrationsposting to accounts the owner linked (admins only)JavaScript client
These routes are matched before your models. Don't name a model Auth, Files, Payments, Checkout, Membership, Store, Track, Admin, Integrations, Storage or Proxy: some or all of its endpoints would never reach it.

The API's file folder and connections #

Older APIs can have a file folder and connections (S3-style storage, a Supabase or Elasticsearch proxy) set up in the API tab. Their runtime routes are locked down:

RouteWho may call it
GET /_api/<apiId>/_files/<path>Anyone: one file, served inert (no scripts run, pages and SVG download as attachments)
GET /_api/<apiId>/_files, PUT and DELETE /_api/<apiId>/_files/<path>One of the API's signed-in admins
GET /_api/<apiId>/storage/<connection>/<key>Anyone: one object, served inert
Listing, PUT and DELETE under /_api/<apiId>/storage/<connection>One of the API's signed-in admins
Anything under /_api/<apiId>/proxy/<connection>One of the API's signed-in admins, because the connection's credentials act for the caller

Admin calls send the admin's token as Authorization: Bearer <token> and need sign-in on for the API. For files your app's users upload, use App file storage instead.

bash
curl -X PUT https://devmachinist.com/_api/mhx3q9zk4f7p2a/_files/price-list.pdf \
  -H "Authorization: Bearer $ADMIN_TOKEN" --data-binary @price-list.pdf

Every /_api answer carries Content-Security-Policy: default-src 'none'; sandbox, so nothing it serves can run as a page on the app's address.