# Invoke Function

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

Invokes the named function with a caller-supplied `payload`. By default the call is synchronous: the response (200 OK) contains the function's return value under `data` plus `meta` fields including `functionName`, `version`, `durationMs`, and `invocationId`.

With `background: true` the call is stored and answered `202` with `data.invocationId`; the function runs afterwards at most once, and is never retried after it starts. An accepted call can end without running: the invocation's status and reason say so.

A background invocation runs for at most 15 minutes. It has no plain egress, and a credentialed send it makes can happen up to 15 minutes after the call was accepted. Its status and result are read by that id, by the caller who started it, through `GET /@{projectSlug}/functions/{name}/invocations/{invocationId}` or the MCP `get_invocation` tool.

Errors:

- `404 K9O_FUNCTION_NOT_FOUND` for absent or retired functions
- `409 K9O_FUNCTION_NOT_READY` while deploying
- `422 K9O_FUNCTION_DEPLOYMENT_FAILED` on a failed deployment
- `503 K9O_FUNCTION_MEMORY_EXCEEDED` when the function exceeds its tier memory limit
- `504 K9O_FUNCTION_TIMEOUT` on execution time exceeded
- `422 K9O_FUNCTION_RUNTIME_ERROR` on unhandled exception

## Parameters

| Name | In | Required | Description |
|---|---|---|---|
| `name` | path | yes | The name of the function to call. 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 |
|---|---|---|---|
| `payload` | object | no | The input passed to the function, any JSON value. The function reads it as its request body. Default null. |
| `approval` | object | no | Runs a call that was held for approval and has since been approved: send the same function and the same `payload` again with this. A call parked for the platform to run (`parked: true`) can't be redeemed this way. |
| `approval.id` | string | yes | The `approvalId` from the held call's 202 response (`apr_...`). |
| `approval.bindingNonce` | string | yes | The `bindingNonce` from the same 202 response. |
| `approvalWindowSeconds` | number | no | If the call is held for approval, how long approvers have to decide, in seconds. At least 60. It can only shorten the window, which stays within the project's maximum (and 72 hours for a parked call). |
| `background` | boolean | no | Set to true to run the call in the background: the response is 202 with an `invocationId` and the function runs later. Default false, which runs it now and returns its result. |
| `delegation` | object | no | Run the call scoped to one end user, on the strength of a delegation token. Use at most one of `delegation`, `onBehalfOf` and `confinedTo`. |
| `delegation.token` | string | yes | A signed delegation token naming the end user (`sub`) the call acts for and the acting party (`act`). The signature is what authorizes it. |
| `delegation.invokeSessionId` | string | no | A session id the token is bound to, used only to match the token to this call. |
| `onBehalfOf` | string | no | An end user id (`eu_...`) whose data the call reads, for a background or system call with no end-user token. Your credential must hold an on-behalf-of grant. Use at most one of `delegation`, `onBehalfOf` and `confinedTo`. |
| `confinedTo` | string | no | An end user id (`eu_...`) to confine the call to: it may read and write only that user's rows. Your credential must hold an `invoke_confined_to` grant. Use at most one of `delegation`, `onBehalfOf` and `confinedTo`. |

```json
{
  "payload": null,
  "background": false
}
```

## Responses

- **200**: Success

| Field | Type | Required | Description |
|---|---|---|---|
| `data` | object | yes | What the function returned, parsed as JSON. Null when it returned nothing. Output that isn't JSON comes back as `{"_binary_base64": "<base64>"}`. |
| `meta` | object | yes | Request metadata plus the invocation's: `functionName`, `version`, `tier`, `runtime`, `durationMs`, `invocationId`, `artifactBytes`, `resultBytes`, `fuelConsumed` and `executor`. |

- **202**: Accepted

| Field | Type | Required | Description |
|---|---|---|---|
| `data` | object | yes | The function has not run yet: a background call was accepted, or the call is held or parked for approval. |
| _one of_ | | |  |
| `data.invocationId` | string | yes | The id of the background invocation. Its outcome is recorded under this id. |
| _or_ | | |  |
| `data.approvalId` | string | yes | The approval case the call waits on (`apr_...`). |
| `data.status` | enum ("pending_approval") | yes | Always `pending_approval`: the function has not run. |
| `data.payloadHash` | string | yes | The SHA-256 (hex) binding this function version, its code and your payload to the approval. Approvers see it. |
| `data.bindingNonce` | string | yes | A secret you send back, with `approvalId`, to run the call once it is approved. |
| `data.functionVersion` | string | yes | The function version that was approved for. A redeploy before the call runs voids the approval. |
| `data.expiresAt` | string (date-time) | yes | When the case expires if no one decides it. |
| _or_ | | |  |
| `data.approvalId` | string | yes | The approval case the call waits on (`apr_...`). |
| `data.status` | enum ("pending_approval") | yes | Always `pending_approval`: the function has not run. |
| `data.payloadHash` | string | yes | The SHA-256 (hex) binding this function version, its code and your payload to the approval. Approvers see it. |
| `data.bindingNonce` | string | yes | A secret you send back, with `approvalId`, to run the call once it is approved. |
| `data.functionVersion` | string | yes | The function version that was approved for. A redeploy before the call runs voids the approval. |
| `data.expiresAt` | string (date-time) | yes | When the case expires if no one decides it. |
| `data.callId` | string | yes | The id to read the outcome by once the platform has run the call. The same value as `approvalId`. |
| `data.parked` | enum (true) | yes | Always true: the platform runs this call itself once it is approved. |
| `meta` | object | yes | Request metadata. For a held or parked call, `approval.status` is `pending_approval`. |


## Errors

| HTTP | Code | When |
|---|---|---|
| 400 | `K9O_INVALID_FIELD_VALUE` | approvalWindowSeconds is not a whole number of seconds of at least 60 (a held call's window; above the project's maximum it is held to it). |
| 401 | `K9O_INVALID_CREDENTIALS` | Your credentials are missing or invalid; authenticate before invoking a function. |
| 403 | `K9O_ACCESS_DENIED` | Your account does not have sufficient permission to invoke functions on this project. |
| 403 | `K9O_FORBIDDEN` | An extension called by another extension (its token carries the hop marker) asked for a background invocation; one hop only, so it may not start an asynchronous dispatch. Answered before the 501. |
| 403 | `K9O_FORBIDDEN` | This call can't run in the background: the caller is an extension, a sandbox or playground session, or not a person or service token; the call carries an approval or a signed delegation; or the project isn't on platform-managed custody. Call the function without `background`. |
| 409 | `K9O_STATE_CONFLICT` | The function changed while a background invocation was being accepted; nothing was queued. Retry. |
| 429 | `K9O_RATE_LIMITED` | This project already has the maximum number of background invocations waiting; `context.limit` names it. Retry once some have run. |
| 503 | `K9O_ENVELOPE_KEK_UNAVAILABLE` | The payload of a background invocation couldn't be sealed for storage; nothing was queued. Retry. |
| 404 | `K9O_FUNCTION_NOT_FOUND` | No function with that name exists in this project, or it has been retired. |
| 409 | `K9O_FUNCTION_NOT_READY` | The function exists but is still deploying; wait for deployment to complete before invoking. |
| 422 | `K9O_FUNCTION_DEPLOYMENT_FAILED` | The function's most recent deployment failed; redeploy the function before invoking. |
| 422 | `K9O_FUNCTION_RUNTIME_ERROR` | The function threw an unhandled exception during execution. |
| 504 | `K9O_FUNCTION_TIMEOUT` | The function exceeded its maximum execution time limit. |
| 422 | `K9O_FUNCTION_MEMORY_EXCEEDED` | The function exceeded its memory limit and was terminated. |

## Code samples

### cURL

```bash
curl -X POST 'https://<org>.api-<region>.k9o.io/@storefront/functions/<name>/invoke' \
  -H 'Authorization: Bearer $K9O_TOKEN' \
  -H 'Content-Type: application/json' \
  -d '{
  "payload": null,
  "background": false
}'
```

### fetch

```javascript
const res = await fetch('https://<org>.api-<region>.k9o.io/@storefront/functions/<name>/invoke', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.K9O_TOKEN}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
  "payload": null,
  "background": false
}),
});
const { data, meta } = await res.json();
```

### k9o CLI

```bash
k9o function invoke <name>
```

### @k9o/core

```typescript
// const k9o = new K9o({ orgSlug: 'playground', projectSlug: 'storefront', apiKey: 'k9o_…' })
const { data } = await k9o.functions.invoke('greet', {
  payload: null,
  background: false
})
```

### k9o

```python
# k9o = create_client(org_slug="playground", project_slug="storefront", api_key="k9o_…")
response = k9o.functions.invoke("greet", {
    "payload": None,
    "background": False
})
```

### sdk-go

```go
// ctx := context.Background()
// client, _ := k9o.NewClient(k9o.ClientOpts{OrgSlug: "playground", ProjectSlug: "storefront", APIKey: "k9o_…"})
data, _, kerr := client.Functions.Invoke(ctx, "greet", map[string]any{"payload": nil, "background": false})
```

### k9o

```rust
// let k9o = Client::new(ClientOpts { org_slug: "playground".into(), project_slug: "storefront".into(), api_key: "k9o_…".into() })?;
let resp = k9o.functions.invoke("greet", json!({"payload": null, "background": false})).await?
```

### dev.k9o:core

```java
// K9o k9o = K9o.createClient(K9o.Opts.builder().orgSlug("playground").projectSlug("storefront").apiKey("k9o_…").build());
var response = k9o.functions().invoke("greet", Map.of("payload", null, "background", false))
```

### K9o.Core

```c#
// var k9o = K9oClient.Create(new K9oOptions { OrgSlug = "playground", ProjectSlug = "storefront", ApiKey = "k9o_…" });
var response = await k9o.Functions.InvokeAsync("greet", new Dictionary<string, object> { ["payload"] = null, ["background"] = false })
```

### k9o

```ruby
# k9o = K9o.create_client(org_slug: "playground", project_slug: "storefront", api_key: "k9o_…")
response = k9o.functions.invoke("greet", { payload: nil, background: false })
```

### k9o/sdk

```php
// $k9o = K9oClient::create(['org_slug' => 'playground', 'project_slug' => 'storefront', 'api_key' => 'k9o_…']);
$response = $k9o->functions->invoke('greet', ['payload' => null, 'background' => false])
```

### K9o

```swift
// let k9o = try K9o.createClient(orgSlug: "playground", projectSlug: "storefront", apiKey: "k9o_…")
let result = try await k9o.functions.invoke("greet", {
  payload: null,
  background: false
})
```

### core-kotlin

```kotlin
// val k9o = createClient { orgSlug = "playground"; projectSlug = "storefront"; apiKey = "k9o_…" }
val result = k9o.functions.invoke("greet", {
  payload: null,
  background: false
})
```

### k9o (Flutter)

```dart
// final k9o = K9o.createClient(orgSlug: 'playground', projectSlug: 'storefront', apiKey: 'k9o_…');
final result = await k9o.functions.invoke('greet', {
  payload: null,
  background: false
})
```

### @k9o/react-native

```javascript
// const k9o = createClient({ orgSlug: 'playground', projectSlug: 'storefront', apiKey: 'k9o_…' })  // RN, secure storage
const { data } = await k9o.functions.invoke('greet', {
  payload: null,
  background: false
})
```


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