# Create Function Trigger

`POST /functions/{name}/triggers` · Core · Compute & Automation

Attaches an EVENT trigger to the named function: it fires on writes to a collection.

Body (camelCase):

- `collection` (required)
- `events` (one or more of `insert`, `update`, `delete`, `upsert`)
- an optional `filter` in the JSON-policy grammar (for example `{"eq": ["resource.status", "active"]}`) limits invocations to matching records; `null` fires on every matching write
- `enabled` (default true)
- `logOkInvocations` (default false)

Scheduled triggers are not created here: use `POST /@{projectSlug}/forge/schedules`.

Errors:

- `404 K9O_FUNCTION_NOT_FOUND` when the function does not exist or is retired
- `404 K9O_COLLECTION_NOT_FOUND` when the collection does not exist
- `400 K9O_POLICY_UNKNOWN_OPERATOR` for a filter operator outside the grammar

Requires `PROJECT_ADMIN`.

## Parameters

| Name | In | Required | Description |
|---|---|---|---|
| `name` | path | yes | The function's name. A module's operation is named `<module>:<operation>`. Example: `"greet"`. |
| `projectSlug` | path | yes | The project's slug: the path segment after `@`. It is unique within the org. Example: `"storefront"`. |

## Request body

| Field | Type | Required | Description |
|---|---|---|---|
| _one of_ | | |  |
| `collection` | string | yes | The collection whose writes fire the trigger. It must exist. |
| `events` | array of enum ("insert", "update", "delete", "upsert") | yes | The kinds of write that fire the trigger, 1 to 4 of `insert`, `update`, `delete` and `upsert`. |
| `filter` | object | no | A condition on the written record, as a JSON predicate in the policy grammar: `{"<operator>": [arg, ...]}` with `eq`, `neq`, `gt`, `lt`, `gte`, `lte`, `contains`, `not_contains`, `in`, `not_in`, `and`, `or` and `not`. `resource.<field>` reads a field of the record. The trigger fires only when it matches. Null or absent fires on every matching event. |
| _one of_ | | |  |
| _or_ | | |  |
| `enabled` | boolean | no | Whether the trigger fires. Default true. |
| `logOkInvocations` | boolean | no | Whether successful invocations are logged as well as failed ones. Default false. |
| _or_ | | |  |
| `bucket` | string | yes | The bucket whose objects fire the trigger. It must exist and must not be a system bucket, and you must be able to read it. |
| `events` | array of enum ("object.created", "object.deleted", "object.expired") | yes | The object events that fire the trigger, 1 to 3 of `object.created` (an upload, an overwrite included), `object.deleted` (a delete through the API) and `object.expired` (removed by the bucket's `deleteAfterDays`). A function that receives `object.deleted` or `object.expired` can't read the object any more. |
| `filter` | object | no | Conditions on the object event, all of which must hold: `pathPrefix`, a literal prefix of the object's path (no wildcards); `contentType`, an exact type such as `image/png` or a family such as `image/*`; `sizeBytes`, an inclusive `{ min, max }` range. Null or absent fires on every matching event. |
| _one of_ | | |  |
| `filter.pathPrefix` | string | no | Fire only for objects whose path starts with this, compared literally. |
| `filter.contentType` | string | no | Fire only for this content type, or this family when it ends in `/*`. |
| `filter.sizeBytes` | object | no | Fire only for objects whose size is in this inclusive range, in bytes. |
| `filter.sizeBytes.min` | integer | no | The smallest size that fires, in bytes, inclusive. |
| `filter.sizeBytes.max` | integer | no | The largest size that fires, in bytes, inclusive. |
| _or_ | | |  |
| `enabled` | boolean | no | Whether the trigger fires. Default true. |
| `logOkInvocations` | boolean | no | Whether successful invocations are logged as well as failed ones. Default false. |

```json
{
  "collection": "products",
  "events": [
    "insert",
    "update"
  ],
  "filter": {
    "eq": [
      "resource.status",
      "active"
    ]
  },
  "enabled": true,
  "logOkInvocations": false
}
```

## Responses

- **201**: Created

| Field | Type | Required | Description |
|---|---|---|---|
| `data` | object | yes | A function trigger: the function runs when a matching write lands in the collection, or a matching object event happens in the bucket. |
| `data.id` | string (uuid) | yes | The trigger's id, a UUID. |
| `data.functionName` | string | yes | The function the trigger runs. |
| `data.collection` | object | yes | The collection whose writes fire the trigger; null on a bucket trigger. |
| _one of_ | | |  |
| _or_ | | |  |
| `data.bucket` | object | yes | The bucket whose object events fire the trigger; null on a collection trigger. |
| _one of_ | | |  |
| _or_ | | |  |
| `data.events` | array of object | yes | The events that fire the trigger: `insert`, `update`, `delete` and `upsert` on a collection; on a bucket, `object.created` (an upload, an overwrite included), `object.deleted` (a delete through the API) and `object.expired` (removed by the bucket's `deleteAfterDays`). A function that receives `object.deleted` or `object.expired` can't read the object any more. |
| _one of_ | | |  |
| _or_ | | |  |
| `data.filter` | object | yes | The condition an event must match: a record predicate on a collection trigger, object conditions on a bucket trigger. Null when the trigger fires on every matching event. |
| _one of_ | | |  |
| _or_ | | |  |
| `data.enabled` | boolean | yes | Whether the trigger fires. |
| `data.logOkInvocations` | boolean | yes | Whether successful invocations are logged as well as failed ones. |
| `data.createdAt` | string (date-time) | yes | When the trigger was created. |
| `meta` | object | yes |  |


## Errors

| HTTP | Code | When |
|---|---|---|
| 401 | `K9O_UNAUTHENTICATED` | The caller presented no authenticated session. |
| 400 | `K9O_INVALID_FIELD_VALUE` | The project slug, the function name or the collection name is not a valid identifier. |
| 400 | `K9O_POLICY_UNKNOWN_OPERATOR` | The filter uses an operator outside the JSON-policy grammar. |
| 403 | `K9O_ACCESS_DENIED` | The caller has no access to this project. |
| 403 | `K9O_IAM_POLICY_DENIED` | The bound IAM policy ceiling denies creating function triggers; the default floor is PROJECT_ADMIN. |
| 404 | `K9O_FUNCTION_NOT_FOUND` | No function with that name exists in this project, or it is retired. |
| 404 | `K9O_COLLECTION_NOT_FOUND` | The collection named for the trigger does not exist in this project. |

## Code samples

### cURL

```bash
curl -X POST 'https://<org>.api-<region>.k9o.io/@storefront/functions/<name>/triggers' \
  -H 'Authorization: Bearer $K9O_TOKEN' \
  -H 'Content-Type: application/json' \
  -d '{
  "collection": "products",
  "events": [
    "insert",
    "update"
  ],
  "filter": {
    "eq": [
      "resource.status",
      "active"
    ]
  },
  "enabled": true,
  "logOkInvocations": false
}'
```

### fetch

```javascript
const res = await fetch('https://<org>.api-<region>.k9o.io/@storefront/functions/<name>/triggers', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.K9O_TOKEN}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
  "collection": "products",
  "events": [
    "insert",
    "update"
  ],
  "filter": {
    "eq": [
      "resource.status",
      "active"
    ]
  },
  "enabled": true,
  "logOkInvocations": false
}),
});
const { data, meta } = await res.json();
```

### k9o CLI

```bash
k9o function trigger create <function> --collection <name> --events <e1,e2,...>
```

### @k9o/core

```typescript
// const k9o = new K9o({ orgSlug: 'playground', projectSlug: 'storefront', apiKey: 'k9o_…' })
const { data } = await k9o.functions.triggers.create('greet', {
  collection: 'products',
  events: ['insert', 'update'],
  filter: {
    eq: ['resource.status', 'active']
  },
  enabled: true,
  logOkInvocations: false
})
```

### k9o

```python
# k9o = create_client(org_slug="playground", project_slug="storefront", api_key="k9o_…")
response = k9o.functions.triggers.create("greet", {
    "collection": "products",
    "events": ["insert", "update"],
    "filter": {
        "eq": ["resource.status", "active"]
    },
    "enabled": True,
    "logOkInvocations": False
})
```

### sdk-go

```go
// ctx := context.Background()
// client, _ := k9o.NewClient(k9o.ClientOpts{OrgSlug: "playground", ProjectSlug: "storefront", APIKey: "k9o_…"})
data, _, kerr := client.Functions.Triggers.Create(ctx, "greet", map[string]any{"collection": "products", "events": []any{"insert", "update"}, "filter": map[string]any{"eq": []any{"resource.status", "active"}}, "enabled": true, "logOkInvocations": false})
```

### k9o

```rust
// let k9o = Client::new(ClientOpts { org_slug: "playground".into(), project_slug: "storefront".into(), api_key: "k9o_…".into() })?;
let resp = k9o.functions.triggers.create("greet", json!({"collection": "products", "events": ["insert", "update"], "filter": json!({"eq": ["resource.status", "active"]}), "enabled": true, "logOkInvocations": false})).await?
```

### dev.k9o:core

```java
// K9o k9o = K9o.createClient(K9o.Opts.builder().orgSlug("playground").projectSlug("storefront").apiKey("k9o_…").build());
var response = k9o.functions().triggers().create("greet", Map.of("collection", "products", "events", List.of("insert", "update"), "filter", Map.of("eq", List.of("resource.status", "active")), "enabled", true, "logOkInvocations", false))
```

### K9o.Core

```c#
// var k9o = K9oClient.Create(new K9oOptions { OrgSlug = "playground", ProjectSlug = "storefront", ApiKey = "k9o_…" });
var response = await k9o.Functions.Triggers.CreateAsync("greet", new Dictionary<string, object> { ["collection"] = "products", ["events"] = new object[] { "insert", "update" }, ["filter"] = new Dictionary<string, object> { ["eq"] = new object[] { "resource.status", "active" } }, ["enabled"] = true, ["logOkInvocations"] = false })
```

### k9o

```ruby
# k9o = K9o.create_client(org_slug: "playground", project_slug: "storefront", api_key: "k9o_…")
response = k9o.functions.triggers.create("greet", { collection: "products", events: ["insert", "update"], filter: { eq: ["resource.status", "active"] }, enabled: true, logOkInvocations: false })
```

### k9o/sdk

```php
// $k9o = K9oClient::create(['org_slug' => 'playground', 'project_slug' => 'storefront', 'api_key' => 'k9o_…']);
$response = $k9o->functions->triggers->create('greet', ['collection' => 'products', 'events' => ['insert', 'update'], 'filter' => ['eq' => ['resource.status', 'active']], 'enabled' => true, 'logOkInvocations' => false])
```


Canonical page: https://docs.kilimanjaro.dev/api-playground/core/create-function-trigger
