> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.runtype.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.runtype.com/_mcp/server.

# Ensure collection (config-as-code converge)

POST https://api.runtype.com/v1/collections/ensure
Content-Type: application/json

Idempotently converge a repo-defined record collection (display fields, schema and validationMode) onto the platform. Identity is slug + account scope. Hash-only probes skip the payload in the steady state (a miss is a normal 200 `definitionRequired` response); full requests create the collection or update it when the canonical content hash differs. Schema changes follow the same rules as PATCH: they bump schemaVersion and append history, and a breaking change is rejected while the resulting mode is `enforce`. Set dryRun to plan without writing (CI drift gate), and onConflict: "overwrite" to converge over dashboard/API edits. Ensure never deletes a collection and never touches records.

Reference: https://docs.runtype.com/api-reference/runtype-api/collections/ensure-collection-config-as-code-converge

## Authentication

- `Authorization` header (bearer token, required) — API key or Clerk session token

## Servers

- `https://api.runtype.com` (Production, default)
- `https://api.runtype-staging.com` (Staging)

## Request

### Body (application/json)

This endpoint expects an object.

- `slug` (string, required)
- `contentHash` (string, optional)
- `definition` (V1CollectionsEnsurePostRequestBodyContentApplicationJsonSchemaDefinition, optional)
- `dryRun` (boolean, optional)
- `expectedRemoteHash` (string, optional)
- `onConflict` (enum, optional)
  - Allowed values: `error`, `overwrite`

## Response

### 200

Converge result: unchanged | created | updated | definitionRequired (hash miss — retry with the full definition) | plan (dryRun)

- `CollectionEnsureResponse`

## Errors

### 400 Bad Request Error

Invalid slug or schema, or a breaking schema change while enforcing (BREAKING_SCHEMA_CHANGE_REQUIRES_WARN_MODE)

- `error` (string, required)
- `details` (list of V1CollectionsEnsurePostResponsesContentApplicationJsonSchemaDetailsItems, optional)
- `code` (string, optional)

### 401 Unauthorized Error

Unauthorized

- `error` (string, required)
- `details` (list of ErrorDetailsItems, optional)

### 403 Forbidden Error

Insufficient permissions

- `error` (string, required)
- `details` (list of ErrorDetailsItems, optional)

### 409 Conflict Error

Conflict: external_modification (last write was not ensure; pass onConflict: "overwrite") or remote_changed (expectedRemoteHash guard)

- `code` (enum, required)
  - Allowed values: `external_modification`, `remote_changed`
- `error` (string, required)
- `currentHash` (string, optional, nullable)
- `lastModifiedSource` (string, optional)
- `modifiedAt` (string, optional, nullable)

### 422 Unprocessable Entity Error

Submitted contentHash does not match the server-recomputed canonical hash

- `code` (enum, required)
  - Allowed values: `content_hash_mismatch`
- `contentHash` (string, required) — The server-computed canonical hash of the submitted definition.
- `error` (string, required)

### 500 Internal Server Error

Internal server error

- `error` (string, required)
- `details` (list of ErrorDetailsItems, optional)

## Types

### V1CollectionsEnsurePostRequestBodyContentApplicationJsonSchemaDefinition

- `displayName` (string, required)
- `slug` (string, required)
- `description` (string, optional, nullable)
- `icon` (string, optional, nullable)
- `schema` (map from string to any, optional, nullable) — Constrained JSON Schema dialect: root object with string/number/boolean/array/object properties, one nesting level, no $ref/oneOf/pattern
- `validationMode` (enum, optional)
  - Allowed values: `off`, `warn`, `enforce`

### CollectionEnsureResponse0

- `collectionId` (string, required)
- `contentHash` (string, required) — Server-computed canonical content hash. Clients should echo this hash in probes.
- `result` (enum, required)
  - Allowed values: `unchanged`, `created`, `updated`
- `enforceCheck` (CollectionEnsureResponseOneOf0EnforceCheck, optional) — Present when this ensure moved validationMode to enforce: a bounded dry-run of existing records against the schema, as PATCH reports.
- `schemaChange` (CollectionEnsureResponseOneOf0SchemaChange, optional)

### CollectionEnsureResponse1

- `result` (enum, required)
  - Allowed values: `definitionRequired`

### CollectionEnsureResponse2

- `changedKeys` (list of string, required)
- `changes` (enum, required)
  - Allowed values: `none`, `create`, `update`
- `contentHash` (string, required)
- `result` (enum, required)
  - Allowed values: `plan`
- `collectionId` (string, optional)
- `remoteHash` (string, optional)
- `schemaChange` (CollectionEnsureResponseOneOf2SchemaChange, optional) — How the schema would change. A breaking change is rejected when the resulting validationMode is enforce.

### V1CollectionsEnsurePostResponsesContentApplicationJsonSchemaDetailsItems

- `message` (string, required)
- `code` (string, optional) — Stable Runtype validation code (e.g. MISSING_REQUIRED_FIELD, INVALID_ENUM).
- `path` (string, optional) — Dotted JSON path to the offending field.
- `suggestion` (string, optional) — Actionable hint (allowed values, accepted range, …).

### ErrorDetailsItems

- `message` (string, required)
- `code` (string, optional) — Stable Runtype validation code (e.g. MISSING_REQUIRED_FIELD, INVALID_ENUM).
- `path` (string, optional) — Dotted JSON path to the offending field.
- `suggestion` (string, optional) — Actionable hint (allowed values, accepted range, …).

### CollectionEnsureResponseOneOf0EnforceCheck

Present when this ensure moved validationMode to enforce: a bounded dry-run of existing records against the schema, as PATCH reports.

- `checked` (integer, required)
- `failed` (integer, required)
- `truncated` (boolean, required)

### CollectionEnsureResponseOneOf0SchemaChange

- `breakingChanges` (list of string, required)
- `kind` (enum, required)
  - Allowed values: `additive`, `breaking`

### CollectionEnsureResponseOneOf2SchemaChange

How the schema would change. A breaking change is rejected when the resulting validationMode is enforce.

- `breakingChanges` (list of string, required)
- `kind` (enum, required)
  - Allowed values: `additive`, `breaking`

## Examples

**Request**

```json
{
  "slug": "string"
}
```

**Response**

```json
{
  "collectionId": "string",
  "contentHash": "string",
  "enforceCheck": {
    "checked": 1,
    "failed": 1,
    "truncated": true
  },
  "result": "unchanged",
  "schemaChange": {
    "breakingChanges": [
      "string"
    ],
    "kind": "additive"
  }
}
```

**SDK Code**

```python
import requests

url = "https://api.runtype.com/v1/collections/ensure"

payload = { "slug": "string" }
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.runtype.com/v1/collections/ensure';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"slug":"string"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.runtype.com/v1/collections/ensure"

	payload := strings.NewReader("{\n  \"slug\": \"string\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.runtype.com/v1/collections/ensure")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"slug\": \"string\"\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.runtype.com/v1/collections/ensure")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"slug\": \"string\"\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.runtype.com/v1/collections/ensure', [
  'body' => '{
  "slug": "string"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.runtype.com/v1/collections/ensure");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"slug\": \"string\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["slug": "string"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.runtype.com/v1/collections/ensure")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```