drift Docs
Pages
drift Docs
Start
What is Drift?
The tour, if you are new here.
Use cases
Whether Drift does your thing.
Getting started
Nothing to deployed, in one command.
Architecture
How a slice is put together.
What it costs
The free grant, four unit prices, two rules.
Moving off Azure
Estimate, snapshot and transform a resource group.
Build
Canvas
Static sites, same origin as your API.
Tools
Operate
Auth
Route gates, API keys and your account.
Teams
More than one person on one account.
Security
Boundaries, sandboxing and hardening.
Troubleshooting
Error codes
What went wrong, and what to do about it.
Legal
Acceptable use
What a slice may not be used for.
Data processing
The DPA, and every sub-processor.

Write a function

A function is an ordinary function in your source, plus one function block in your Driftfile naming it. Nothing in the code marks it: no decorator, no magic comment, no base class. Here's an endpoint that saves an item, in Go, with a validate helper beside it:

atomic/items.go
package main

import drift "github.com/ondrift/cloud/sdk/go"

// validate is a plain helper. The Driftfile never names it,
// so it never counts as one of your functions.
func validate(body map[string]any) bool {
    return body["name"] != nil
}

func PostItems(body map[string]any, req drift.Request) (int, string, any, map[string]string) {
    if !validate(body) {
        return 400, "Bad Request", map[string]any{"error": "name required"}, nil
    }
    id, _ := drift.Backbone.NoSQL.Collection("items").Insert(body)
    return 201, "Created", map[string]any{"id": id}, nil
}

And the block that turns PostItems into an endpoint:

Driftfile
slice "items" {}

atomic {
  backend "default" {
    function "POST /items" {
      handler = "PostItems"
      memory  = "32MiB"
    }
  }
}

A handler returns the status code, a short status message and the payload (serialised to JSON for you), plus, in Go only, a fourth value: a map of response headers, nil when you have none. Python, Node, Ruby and PHP return exactly three values, and a fourth raises an unpack error at the first request, so those four cannot set a response header.

Rust sets headers differently. Its entry point destructures a fixed-size tuple, so a fourth value there would stop every existing handler compiling; call drift_sdk::set_response_header(name, value) instead and the return stays three values.

To return a body with no envelope, declare the shape.

By default a JSON payload reaches the caller wrapped as {"status": …, "message": …, "payload": …}. Add response to the function block to change that, see What an entry declares below. Setting a Content-Type that isn't JSON also writes the payload straight to the wire, but declare response = "raw" instead so the shape is stated rather than inferred.

Handlers that take a body (post, put, delete, patch and queue handlers) are called as (body, req). A get handler is called as (req).

Pay for what you expose, not what you write.

The function block is the line between a billable endpoint and free scaffolding. A function the Driftfile names is one of your function slots, booked at the memory its block states, so it counts toward your plan and your bill. Every other function in your source (helpers, validation, shared logic) is free and doesn't count. Structure your code however you like; you only pay for the surface you choose to expose.

What an entry declares

Each function block is the whole declaration for one function, inside the backend whose folder holds its source (backend "default" is the flat files in atomic/). The label and two attributes are required and the rest have defaults:

Label or attribute Meaning
the labelIts trigger and, for HTTP, its path: "GET /items", "POST /groups/:id", with the method in capitals (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS). "QUEUE orders" names the queue the slice invokes it from, a Backbone queue rather than an HTTP request. The label is the identity Drift books, prices and meters.
handlerRequired. The callable that serves it.
memoryRequired. Its own pool, whole MiB from 8MiB to 256MiB (16MiB or more in a compiled language), written "32MiB". No default, see Memory and concurrency.
authAn auth { api_key = env("NAME") } block to require an API key. Without it the function is public. See Authentication.
stream"sse" or "ws" to hold the connection open. See Streaming.
responseThe shape of this function's replies: "envelope" (default), "json" or "raw". See below.
secretsThe Backbone secrets this one function may read, a list of names: ["STRIPE_KEY"].
envPlain configuration injected into its environment, a map: { LOG_LEVEL = "debug" }.
concurrenttrue when the handler is safe to run in parallel. See Memory and concurrency.
cronA five-field schedule it fires on in addition to its own trigger. See Triggers.
dirThe folder its handler is in, when it is not its backend's.

Run drift file explain atomic.backend.function for the CLI's own description of each.

The shape of a reply

Most endpoints answer other code you wrote, and the envelope is what the SDKs expect. An endpoint a third party parses usually cannot take it: a wallet, an OAuth client or a webhook sender wants your keys at the top level, in the shape its own spec names. response says which you are building.

What reaches the callerContent-Type
  • "envelope" (default)
    What reaches the caller
    {"status": …, "message": …, "payload": …}
    Content-Type
    application/json
  • "json"
    What reaches the caller
    your payload, serialised: the whole body
    Content-Type
    application/json, unless you set one
  • "raw"
    What reaches the caller
    your payload as bytes, base64-decoded first
    Content-Type
    yours, and required

An OAuth token endpoint is the case this exists for. The spec pins it to application/json, which is also the envelope's own type, so nothing about the response itself can distinguish them:

Driftfile
slice "oauth" {}

atomic {
  backend "default" {
    function "POST /token" {
      handler  = "PostToken"
      memory   = "32MiB"
      response = "json"
    }
  }
}
Node.js
async function PostToken(body, req) {
  return [200, "OK", { access_token: "…", token_type: "Bearer", expires_in: 3600 }];
}

reaches the caller as {"access_token":"…","token_type":"Bearer","expires_in":3600} and nothing else.

Use "raw" for a body that isn't text at all (an image, a PDF, a signed token) and set your own Content-Type alongside it. Your payload is base64 there, because bytes have to survive a JSON hop to get to Drift.

How a handler is found

Drift looks for handler in the backend's directory (atomic/ for the default backend, atomic/<backend> for a named one) and nowhere else. Two backends can each have a handle; within one backend the name has to be unique.

The backend's directory is also the whole of what gets deployed.

Drift archives that one folder and ships it. A file your handler imports from outside it, such as ../dist/bundle.js, a sibling lib/, or a config at the repo root, exists on your machine and is simply not there at runtime, which surfaces as a module-not-found or ENOENT in the deployed function rather than as a deploy error. Bundle what you need into the backend, or give the shared code its own backend.

The callable has to be reachable from outside its own file, because the entry point Drift generates imports it by name:

Language Shape
Gofunc PostItems(…), exported, capital first letter
Pythondef post_items(…):
Nodefunction postItems(…), a named declaration; an arrow assigned to a const is not matched
Rubydef post_items(…)
PHPfunction postItems(…)
Rustpub fn post_items(…), where pub is required

The name is yours to choose. A handler the Driftfile names and the source doesn't have fails the deploy before anything is built, and the error lists the callables that directory does declare. drift file lint runs the same check offline.

Node means JavaScript. Drift discovers .js, .mjs and .cjs; there is no TypeScript compiler in the deploy path, so a .ts file in a backend is never looked at and its handlers are never found. Compile or bundle to JavaScript first (a pre_deploy hook is the usual place) and ship the output.

Routing

A function's address is the method and path from its label: function "POST /items" answers only POST /api/items. The method is part of the identity, not a detail. A request with a different method to the same path doesn't fall through to this function, it 404s. There's nothing to branch on inside the handler: you were routed here because you're the POST handler, so drift.Request deliberately doesn't expose the method.

So function "GET /users" (list) and function "POST /users" (create) are two functions with two handlers, two blocks and two billing units. The path /users is a human grouping, not the unit; the unit is the function.

The /api space is shared across every backend, so two blocks declaring the same method and path collide wherever they live. drift plan, drift apply and drift file lint refuse the whole file and name where both are:

the function "post:items" is declared 2 times (in the backends default and ml); a booking key is unique across the whole slice, not per backend, so declare it once

Method-and-path identity is why most CLI commands that address a single function take --method: without it, get:users and post:users (the booking keys the CLI prints, method then path) are indistinguishable by name.