# Cosmic Documentation (full text)
Source: https://www.cosmicjs.com/docs
This file is the concatenated markdown of every page in the Cosmic docs sidebar, in reading order. The per-page index lives at https://www.cosmicjs.com/docs/llms.txt.
## For Agents
If you are an AI agent looking to provision a Cosmic project on behalf of a human, jump to the **Agent Skills** and **Agents** sections below. The one-curl signup flow (`POST /v3/agents/sign-up`) creates a free-tier project + bucket tied to a human email without requiring any prior Cosmic account.
---
# Get started
# Cosmic Documentation
Read the Cosmic documentation to learn how to create, read, update, and delete Cosmic content, upload media, create automatic workflows, and extend the dashboard functionality.
## Getting started
To get started, follow the [quickstart guide](/docs/quickstart) and read about how to make requests for your content using the API and available SDKs. Learn how to use Cosmic with select frameworks below.
## Frameworks
## LLM Access
You can access all Cosmic documentation in markdown format for easy integration with Large Language Models (LLMs). View the [complete documentation index](/docs/llms.txt) optimized for LLMs.
## Get Support
Reach out to [Cosmic support](https://www.cosmicjs.com/contact) for any specific questions or issues. You can also join the community on the [Cosmic Discord server](https://discord.com/invite/MSCwQ7D6Mg).
---
# Quickstart
This guide will get you set up to use the Cosmic dashboard and API. We'll cover how to get started creating your first project and making your first API request.
We'll also look at where to go next to find all the information you need to use the Cosmic REST API and available client libraries to power content for your websites and apps.
## 1. Create your free account
First, you will need to [create your free Cosmic account](https://app.cosmicjs.com/signup).
## 2. Create a Project
Create a new project by going to [Dashboard > New Project](https://app.cosmicjs.com/projects/new). You can either start with an empty project or start with a template.
## 3. Create a Bucket
Next step is to create a new Bucket. This is where your content will live. A Bucket is an environment for your content (Production, Staging, Testing, etc) so you can have multiple Buckets in your project each with their own set of managed access for team members and API keys.
## 4. Create an Object type
The next step is to create an Object type. Object types are how your content is modeled in Cosmic. Examples of Object types are: pages, blog posts, authors, categories, etc.
Use Metafields to create your Object type model. Available Metafields include: plain text, rich text, number, color picker, form fields like select, multi-select, and dropdown, switch field, media fields like image and video, Object relationships, and more.
## 5. Create an Object
Now that you have your Object type set up, you can now begin adding Objects. Objects are the building blocks of content in Cosmic. To create a new Object, go to any Object type table and click the button "+ Add Object".
## 6. Upload media
Your media for your Bucket is located in Bucket > Media. Upload, edit, and delete media from this area.
## 7. Choose your client
Before making your first API request, you need to pick which API client you will use. In addition to cURL HTTP requests, Cosmic offers a client for JavaScript. In the following example, you can see how to install each client.
```bash {{ language: 'js' }}
# Install the Cosmic JavaScript SDK
npm install @cosmicjs/sdk --save
```
```bash {{ title: 'cURL' }}
# cURL is most likely already installed on your machine
curl --version
```
## 8. Fetch your content
After picking your preferred client, you are ready to make your first call to the Cosmic API. Below, you can see how to send a GET request to the Objects endpoint to get a list of all your Objects in a certain type.
Before you can make requests to the Cosmic API, you will need to grab your API
key from your dashboard. You find it under [Bucket Settings » API
Access](https://app.cosmicjs.com/login).
```js
import { createBucketClient } from '@cosmicjs/sdk';
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
});
await cosmic.objects
.find({
type: 'cars',
})
.props(['title', 'metadata.image', 'metadata.headline', 'metadata.max_speed'])
.limit(1);
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects \
-d read_key=${BUCKET_READ_KEY} \
--data-urlencode query='{"type": "cars"}' \
-d props=title,metadata.image,metadata.headline,metadata.max_speed \
-d limit=1 \
-G
```
```json {{ title: 'Response' }}
{
"objects": [
{
"title": "Camero",
"metadata": {
"image": {
"url": "https://cdn.cosmicjs.com/19c2e290-9135...",
"imgix_url": "https://imgix.cosmicjs.com/19c2e290-9135..."
},
"headline": "This car is FAST!",
"max_speed": 150
}
}
],
"total": 1
}
```
Notice that by setting the `props`, the response will return only the data you request.
## 9. Add team members
Now that you have your content in the Cosmic dashboard and are able to deliver your content into your applications, it's time to invite your team members. To add team members to your project, go to Project > Team and set the permissions for each team member.
## 10. Monitor usage
As you continue to use Cosmic, you can monitor your Project usage by going to Project > Usage.
## 11. Upgrade your plan
As you find that you are using Cosmic more and more, growing your team, and your company, you can upgrade your plan by going to Project > Billing.
You can also add helpful add-ons such as webhooks, automatic backups, revision history, and more.
## Next steps
Great, you're now set up with an understanding of how to get started with the Cosmic dashboard and connect to the Cosmic API. Here are a few links to explore further:
- [Get your API key from the Cosmic dashboard](/docs/api/authentication)
- [Check out the Objects model and API endpoints](/docs/api/objects)
- [Learn about content modeling with Object types](/docs/api/object-types)
---
# Agent Skills
AI coding assistant skills for building applications with Cosmic headless CMS. Two ways to get started:
1. **Agent Signup** (below) - an AI agent can provision a new Cosmic project + bucket in one API call, tied to a human's email. No prior Cosmic account needed.
2. **Skill install** - drop the Cosmic SDK rules file into an existing project so your AI coding assistant generates accurate Cosmic code.
## Agent Signup
AI agents can create a Cosmic project on behalf of a human in a single call. The project starts in **restricted mode** ("unclaimed") with conservative limits, an OTP is emailed to the human, and the human paste the code back to the agent to claim full free-tier access. If the human prefers, they can also claim by signing up at `app.cosmicjs.com` with the same email.
This is the recommended onboarding path for AI agents (Cursor, Claude Code, Bolt, Lovable, v0, custom agents) that need to create content infrastructure on the fly.
### One-curl signup
```bash
curl -X POST https://dapi.cosmicjs.com/v3/agents/sign-up \
-H "Content-Type: application/json" \
-d '{
"human_email": "tony@example.com",
"project_name": "Recipe Blog",
"agent_id": "my-agent-platform"
}'
```
Response:
```json
{
"message": "Agent signup created. OTP sent to human_email.",
"auth_type": "unclaimed",
"agent_key": "agk_...",
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"project": { "id": "...", "name": "Recipe Blog" },
"bucket": {
"slug": "recipe-blog-...",
"read_key": "...",
"write_key": "..."
},
"claim_url": "https://app.cosmicjs.com/claim?token=agk_...",
"limits": {
"ai_credits_remaining": 0,
"media_mb_total": 5,
"objects_max": 50
},
"auto_delete_after_days": 14
}
```
The response returns three credentials, each with a distinct purpose:
| Credential | Purpose | Lifetime |
|---|---|---|
| `agent_key` (`agk_...`) | Authenticate `/v3/agents/verify` and `/v3/agents/status` calls. The durable signup-flow credential. | Until explicitly revoked. |
| `access_token` (JWT) | User-level auth for the standard [Dashboard API](/docs/api). Use it as `Authorization: Bearer ` to create object types, webhooks, team invites, etc. on the agent's project. | 14 days while unclaimed, 90 days post-verify. Auto-revoked when the human claims the bucket. |
| `bucket.read_key` / `bucket.write_key` | Bucket-scoped auth for the [Bucket API + SDK](/docs/api/objects). Use with `createBucketClient` for content CRUD. Survive claim. | Until rotated by the project owner. |
### Three auth states
| State | What it means | What's allowed |
|---|---|---|
| `unclaimed` | Bucket created by agent, human has not verified yet | Create/read/update up to 50 objects, 5 MB media. **No AI generation.** |
| `verified` | Human passed the OTP back to the agent (or signed up via dashboard) | Standard free-tier limits |
| `human_owned` | Human took full ownership via dashboard signup | Standard free-tier limits, full dashboard access |
Unclaimed projects are hard-deleted after **14 days** if not claimed. Plan accordingly.
### Verify (OTP back from human)
When the human gives the agent the 6-digit code from their email, the agent calls:
```bash
curl -X POST https://dapi.cosmicjs.com/v3/agents/verify \
-H "Authorization: Bearer agk_..." \
-H "Content-Type: application/json" \
-d '{ "code": "123456" }'
```
On success, restricted-mode limits lift, AI generation is enabled on the bucket, and the response includes a fresh `access_token` with a longer 90-day expiry. Replace any previously stored token with this one.
### Status
```bash
curl https://dapi.cosmicjs.com/v3/agents/status \
-H "Authorization: Bearer agk_..."
```
Returns the current `auth_type`, `plan_id`, claim status, remaining limits, the bucket keys (so an agent that lost its sign-up response can recover them), and a freshly issued `access_token`. Treat `/status` as the canonical refresh endpoint: call it periodically with the `agent_key` to rotate the user JWT before it expires.
### Existing user collision
If `human_email` is already a Cosmic user, sign-up returns `409 user_already_exists` with a `claim_existing_url`. Ask the human to log in at `app.cosmicjs.com` and grant the agent a bucket key directly; do not retry with a different email.
### Using the CLI
```bash
cosmic agent-signup --email tony@example.com --project "Recipe Blog" --agent-id my-agent
# CLI is now logged in as the agent: cosmic ls, cosmic types create,
# cosmic objects create, etc. all operate on the new bucket immediately.
cosmic agent-verify 123456
cosmic agent-status
cosmic agent-keys # show the full bucket read/write keys
cosmic agent-use # re-activate the agent session if cosmic login replaced it
```
The CLI stores `agent_key`, `access_token`, and bucket keys in `~/.cosmic/credentials.json`. After `agent-signup` the CLI activates the agent session automatically (sets the access token + bucket keys + context) so every standard command works without a separate "use" step. If an existing login is present, the CLI prints a notice that the previous session was replaced. `cosmic whoami` clearly labels active agent sessions.
### Using the MCP server
The agent scope is hosted at `mcp.cosmicjs.com/v1/agent` and exposes three tools that proxy to the endpoints above:
- `cosmic_agent_signup` - no auth required
- `cosmic_agent_verify` - `Authorization: Bearer agk_...`
- `cosmic_agent_status` - `Authorization: Bearer agk_...`
For stdio mode, set `COSMIC_MCP_SCOPE=agent` and (after signup) `COSMIC_AGENT_KEY=agk_...` and the same three tools are exposed locally.
## Installation
Install skills for your AI coding assistant using the skills CLI:
```bash
npx skills add cosmicjs/skills
```
This will add the Cosmic skill to your local project, giving your AI assistant context about the Cosmic SDK and API.
## What the Skill Covers
The Cosmic agent skill provides comprehensive guidance on:
### SDK-first Development
- Setting up the `@cosmicjs/sdk` package
- Configuring bucket clients with proper authentication
- Type-safe methods and error handling
### Objects API
Create, read, update, and delete content with the Objects API:
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
// Get multiple Objects
const { objects: posts } = await cosmic.objects
.find({ type: 'posts' })
.props(['id', 'title', 'slug', 'metadata'])
.limit(10)
// Get single Object by slug
const post = await cosmic.objects
.findOne({ type: 'posts', slug: 'hello-world' })
.props(['title', 'slug', 'metadata'])
// Create an Object
await cosmic.objects.insertOne({
title: 'My Post',
type: 'posts',
metadata: {
content: 'Post content here...',
author: 'author-object-id'
}
})
```
### Object Types & Metafields
Content modeling with Object types and all available Metafield types:
- Text, textarea, markdown, HTML
- Number, date, switch, color
- Select, multi-select, dropdown, radio buttons, checkboxes
- Single and multiple file uploads
- Object relationships (single and multiple)
- JSON, repeater, and parent (nested) fields
### Media API
Upload and manage files and images:
```js
// Upload media
const uploaded = await cosmic.media.insertOne({
media: { originalname: 'photo.jpg', buffer: fileBuffer },
folder: 'uploads',
alt_text: 'Description of image'
})
// Use imgix for image transformations
const optimized = `${media.imgix_url}?w=800&auto=format,compress`
```
### Queries
MongoDB-style filtering and search:
```js
// Comparison operators
await cosmic.objects.find({
type: 'products',
'metadata.price': { $lt: 100 }
})
// Array matching
await cosmic.objects.find({
type: 'products',
'metadata.tags': { $in: ['sale', 'featured'] }
})
// Text search
await cosmic.objects.find({
type: 'posts',
title: { $regex: 'hello', $options: 'i' }
})
```
### AI Generation
Built-in AI capabilities for text, images, and video:
```js
// Generate text
const text = await cosmic.ai.generateText({
prompt: 'Write a product description',
model: 'claude-sonnet-4-5-20250929'
})
// Generate image
const image = await cosmic.ai.generateImage({
prompt: 'Mountain landscape at sunset',
size: '1024x1024',
folder: 'ai-generated'
})
// Generate video
const video = await cosmic.ai.generateVideo({
prompt: 'A kitten playing with yarn',
duration: 8,
resolution: '720p'
})
```
### Framework Patterns
Integration patterns for popular frameworks:
- **Next.js App Router** - Server Components and Server Actions
- **React** - Client-side data fetching
- **Astro** - Static and server-rendered pages
- **And more** - Remix, Nuxt, Svelte, etc.
## Quick Example
Here's a complete Next.js App Router example:
```tsx
// app/posts/page.tsx
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: process.env.COSMIC_BUCKET_SLUG!,
readKey: process.env.COSMIC_READ_KEY!
})
export default async function Posts() {
const { objects: posts } = await cosmic.objects
.find({ type: 'posts' })
.props(['title', 'slug', 'metadata.excerpt'])
.limit(10)
return (
{posts.map(post => (
- {post.title}
))}
)
}
```
## Supported AI Agents
The Cosmic agent skill works with:
- **Cursor** - AI-first code editor
- **Claude Code** - Anthropic's coding assistant
- **GitHub Copilot** - AI pair programmer
- **Windsurf** - AI coding assistant
- **Gemini** - Google's AI assistant
- And 16+ other AI coding agents
## Key Reminders
The skill teaches your AI assistant these important patterns:
1. **Object type is the SLUG** - Use `type: 'blog-posts'`, not `type: 'Blog Posts'`
2. **Media uses `name`** - Reference media by `name` property, not URL
3. **Relations use `id`** - Reference related Objects by `id`, not slug
4. **Never expose `writeKey`** - Keep it server-side only
5. **Use `props()`** - Always specify needed properties for performance
6. **imgix for images** - Use `imgix_url` with query params for optimizations
## Rules for Agents
These rules are non-negotiable for agents using the signup flow. Failure modes here are security issues, not bugs.
1. **NEVER send `agent_key` to any domain other than `*.cosmicjs.com`.** It is a bearer credential. Treat it like a password. Do not log it, post it to chat, or include it in user-visible code blocks.
2. **NEVER share `write_key` in user-visible output.** If you need to show the user the bucket exists, show only the bucket slug and read key. The write key stays in your tool context.
3. **NEVER call `cosmic_agent_signup` without an explicit `human_email`.** The endpoint enforces this, but you should ask the human directly for their email rather than guessing or pulling it from context (prompt-injection risk).
4. **Treat `agent_id` as your platform attribution string.** Use the same value across every signup so the partner team can see your funnel volume. Examples: `cursor-agent`, `claude-code`, `bolt`, `lovable`. Do not put per-user IDs here.
5. **On `409 user_already_exists`, stop and instruct the human to log in.** Do not retry with a synthetic email. Cosmic intentionally refuses agent provisioning for known users to prevent account squatting.
6. **On `402 agent_unclaimed_limit`, prompt the human for the OTP.** This is the expected failure for AI generation, object creation past 50, or media upload past 5 MB on an unclaimed bucket. Calling `cosmic_agent_verify` with the OTP lifts the restriction.
7. **Do not retry the signup endpoint with the same `human_email` more than once per minute.** The endpoint is rate-limited per IP (1/min) and per `agent_id` (100/day for unregistered agents). Sustained retries will get your `agent_id` flagged.
8. **Do not promise the human their bucket is permanent before they claim.** Unclaimed buckets are hard-deleted after 14 days. Surface this clearly in chat.
## Resources
- [Cosmic Documentation](/docs)
- [API Reference](/docs/api)
- [Discord Community](https://discord.com/invite/MSCwQ7D6Mg)
---
# MCP Server
MCP (Model Context Protocol) server that exposes Cosmic CMS functionality as tools for AI assistants. Manage your content, media, object types, and generate AI content directly through Claude, Cursor, or any MCP-compatible client.
**New: hosted MCP available now.** Connect any MCP client to `https://mcp.cosmicjs.com/v1/buckets/{your-bucket-slug}` with your bucket keys, no install required. Jump to the [Hosted MCP](#hosted-mcp) section to get started.
You can connect in two ways:
- **Hosted MCP (recommended):** point your client at `https://mcp.cosmicjs.com/v1/buckets/{your-bucket-slug}` and authenticate with your bucket keys. No install required.
- **Self-hosted (stdio):** run the `@cosmicjs/mcp` npm package locally via `npx`. Useful for offline work or when you want the MCP process inside your dev environment.
## Hosted MCP
The hosted endpoint is the fastest way to connect Cosmic to an AI assistant. It supports the streamable-HTTP MCP transport and is ready to use today:
```
https://mcp.cosmicjs.com/v1/buckets/{your-bucket-slug}
```
### Authentication
Cosmic uses separate read and write keys per bucket. Combine them in the `Authorization: Bearer` header:
| Access level | Authorization header |
|---|---|
| Read-only tools | `Authorization: Bearer READ_KEY` |
| Full access (read + write) | `Authorization: Bearer READ_KEY:WRITE_KEY` |
The write key is the part after the colon. Omit it (and the colon) for read-only access. Examples:
```text
# Read-only access
Authorization: Bearer rk_abc123def456
# Full access (read + write)
Authorization: Bearer rk_abc123def456:wk_zyx987wvu654
```
If your client can't include a colon-packed token, you can send the write key out-of-band via the `X-Cosmic-Write-Key` header instead.
### Getting your credentials
1. Log in to your [Cosmic dashboard](https://app.cosmicjs.com)
2. Navigate to your bucket
3. Go to **Settings** → **API Access**
4. Copy your bucket slug, read key, and write key
### Claude Desktop (hosted)
Add the following to your Claude Desktop configuration file:
**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
```json
{
"mcpServers": {
"cosmic": {
"url": "https://mcp.cosmicjs.com/v1/buckets/your-bucket-slug",
"headers": {
"Authorization": "Bearer your-read-key:your-write-key"
}
}
}
}
```
### Cursor (hosted)
Add the following to your Cursor MCP settings (`.cursor/mcp.json` in your project or `~/.cursor/mcp.json` globally):
```json
{
"mcpServers": {
"cosmic": {
"url": "https://mcp.cosmicjs.com/v1/buckets/your-bucket-slug",
"headers": {
"Authorization": "Bearer your-read-key:your-write-key"
}
}
}
}
```
For read-only access, drop the `:your-write-key` suffix from the bearer token. Write tools (`*_create`, `*_update`, `*_delete`, AI generation) will be blocked with a clear error message; read tools work as normal.
## Self-hosted (stdio)
Prefer to run the MCP locally? The `@cosmicjs/mcp` npm package ships a stdio-based binary you can launch via `npx`.
### Installation
```bash
npx @cosmicjs/mcp
```
Or install globally:
```bash
npm install -g @cosmicjs/mcp
```
### Configuration
The stdio binary reads its credentials from environment variables:
| Variable | Required | Description |
|----------|----------|-------------|
| `COSMIC_BUCKET_SLUG` | Yes | Your Cosmic bucket slug |
| `COSMIC_READ_KEY` | Yes | Bucket read key for read operations |
| `COSMIC_WRITE_KEY` | No | Bucket write key for write operations |
### Claude Desktop (self-hosted)
```json
{
"mcpServers": {
"cosmic": {
"command": "npx",
"args": ["@cosmicjs/mcp"],
"env": {
"COSMIC_BUCKET_SLUG": "your-bucket-slug",
"COSMIC_READ_KEY": "your-read-key",
"COSMIC_WRITE_KEY": "your-write-key"
}
}
}
}
```
### Cursor (self-hosted)
```json
{
"mcpServers": {
"cosmic": {
"command": "npx",
"args": ["@cosmicjs/mcp"],
"env": {
"COSMIC_BUCKET_SLUG": "your-bucket-slug",
"COSMIC_READ_KEY": "your-read-key",
"COSMIC_WRITE_KEY": "your-write-key"
}
}
}
}
```
## Available Tools
The MCP server provides 18 tools for managing your Cosmic content:
### Objects
| Tool | Description |
|------|-------------|
| `cosmic_objects_list` | List or search content objects, filtered by type, status, locale, and paginated. **Use when** the agent needs to enumerate existing content, find an object by title, or build a list view. |
| `cosmic_objects_get` | Fetch a single content object by ID or slug, with optional metafield, depth, and locale params. **Use when** the agent already knows which object to operate on and needs its full body. |
| `cosmic_objects_create` | Create a new content object of a given type with title, slug, status, and metafields (requires write key). **Use when** the human asks to add a blog post, product, page, or any other piece of content. |
| `cosmic_objects_update` | Update an existing object's title, slug, status, or metafield values (requires write key). **Use when** editing copy, publishing a draft, or changing structured data on an existing object. |
| `cosmic_objects_delete` | Permanently delete a content object by ID (requires write key). **Use when** the human explicitly asks to remove content; never call speculatively. |
### Media
| Tool | Description |
|------|-------------|
| `cosmic_media_list` | List media files in the bucket, optionally scoped to a folder. **Use when** the agent needs to find an existing image, video, or document before referencing it in content. |
| `cosmic_media_get` | Fetch metadata and the imgix URL for a single media file by ID. **Use when** the agent needs the canonical URL or dimensions for a known asset. |
| `cosmic_media_upload` | Upload a media file from a URL or base64 payload into the bucket's media library (requires write key). **Use when** the human supplies an image/file or an asset needs to be moved from an external source into Cosmic. |
| `cosmic_media_delete` | Delete a media file from the bucket (requires write key). **Use when** the human explicitly asks to remove an asset. |
### Object Types
| Tool | Description |
|------|-------------|
| `cosmic_types_list` | List every object type (content model) in the bucket. **Use when** the agent first connects to a bucket and needs to learn the available content shapes before reading or writing. |
| `cosmic_types_get` | Fetch the full schema (metafields, options, helper text) for one object type by slug. **Use when** the agent needs the exact metafield keys and types before creating or updating an object. |
| `cosmic_types_create` | Create a new object type with a metafield schema (requires write key). **Use when** the human asks to model a new kind of content (e.g. "add a Products section"). |
| `cosmic_types_update` | Update an object type's schema or metafield definitions (requires write key). **Use when** evolving an existing content model: adding a field, changing options, or renaming. |
| `cosmic_types_delete` | Delete an object type and all its objects (requires write key). **Use when** the human explicitly asks to drop a content model; destructive, prompt for confirmation. |
### AI Generation
| Tool | Description |
|------|-------------|
| `cosmic_ai_generate_text` | Generate text content using Cosmic AI with optional context from existing objects. **Use when** the human asks to draft, rewrite, summarize, or translate copy and wants the bucket's own content as context. |
| `cosmic_ai_generate_image` | Generate an AI image and store it in the bucket's media library (requires write key). **Use when** the human needs original imagery that should live in Cosmic rather than an external host. |
| `cosmic_ai_generate_video` | Generate an AI video with Google Veo and store it in the media library (requires write key). **Use when** the human asks for short generated video clips tied to a piece of content. |
| `cosmic_ai_generate_audio` | Generate narration audio from text via OpenAI TTS (13 voices) and store it in the media library (requires write key). **Use when** the human asks for voiceover, podcast intros, or accessibility audio for written content. |
The hosted endpoint exposes one more scope, `/v1/agent`, with three tools dedicated to the [agent signup flow](#agent-scope). The bucket-scoped tools above are not available on the agent endpoint and vice-versa.
## Usage Examples
Once configured, you can interact with your Cosmic bucket using natural language:
### Content Management
```
List all blog posts in my Cosmic bucket
```
```
Create a new blog post titled "Getting Started with MCP"
with the content "This is an introduction to the Model Context Protocol..."
```
```
Update the blog post with ID "abc123" to change its status to published
```
### Media
```
Show me all images in the "blog-images" folder
```
```
Upload this image URL to my media library: https://example.com/image.jpg
```
### Schema Management
```
Show me all object types in my bucket
```
```
Create a new object type called "Products" with fields for
name, price, description, and image
```
### AI Generation
```
Generate a product description for a wireless bluetooth headphone
```
```
Generate an image of a futuristic city skyline at sunset
and upload it to my media library
```
```
Generate audio narration of "Welcome to Cosmic CMS" using
the "nova" voice and upload it to my media library
```
## Agent scope
The agent scope is a second, smaller MCP server dedicated to the [Agent Signup](/docs/agent-skills#agent-signup) flow: an AI agent can provision a brand new Cosmic project + bucket for a human who does not yet have a Cosmic account, without leaving the MCP transport. It exposes three tools that proxy to the [Agents REST API](/docs/api/agents).
| Tool | Auth | Description |
|---|---|---|
| `cosmic_agent_signup` | None | Create an unclaimed project + bucket tied to a `human_email`. Returns the `agent_key`, `read_key`, `write_key`, and a `claim_url`. Cosmic emails the human a 6-digit OTP. |
| `cosmic_agent_verify` | `agent_key` | Submit the 6-digit OTP. Lifts restricted-mode limits and enables AI generation on the bucket. |
| `cosmic_agent_status` | `agent_key` | Check claim status, remaining limits, and recover the bucket keys. |
The bucket starts in restricted mode (no AI credits, max 50 objects, max 5 MB media). Unclaimed projects are hard-deleted after **14 days**. See the [REST API reference](/docs/api/agents) for the full lifecycle, error codes, and limits.
### Hosted endpoint
```
https://mcp.cosmicjs.com/v1/agent
```
`cosmic_agent_signup` is unauthenticated; `cosmic_agent_verify` and `cosmic_agent_status` require `Authorization: Bearer agk_...` (the `agent_key` returned from sign-up).
```bash
# Discover the tools
curl -X POST https://mcp.cosmicjs.com/v1/agent \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
# Sign up (no auth)
curl -X POST https://mcp.cosmicjs.com/v1/agent \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "cosmic_agent_signup",
"arguments": {
"human_email": "tony@example.com",
"project_name": "Recipe Blog",
"agent_id": "my-agent-platform"
}
}
}'
# Verify with the agent_key from sign-up
curl -X POST https://mcp.cosmicjs.com/v1/agent \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-H "Authorization: Bearer agk_..." \
-d '{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "cosmic_agent_verify",
"arguments": { "code": "123456" }
}
}'
```
### Claude Desktop (agent scope)
```json
{
"mcpServers": {
"cosmic-agent-signup": {
"url": "https://mcp.cosmicjs.com/v1/agent"
},
"cosmic-agent-session": {
"url": "https://mcp.cosmicjs.com/v1/agent",
"headers": {
"Authorization": "Bearer agk_your-agent-key"
}
}
}
}
```
Two entries are useful in practice: an unauthenticated one for the initial sign-up call, and a second authenticated entry once the agent has captured the returned `agent_key`. The agent can omit the second entry until needed.
### Cursor (agent scope)
```json
{
"mcpServers": {
"cosmic-agent": {
"url": "https://mcp.cosmicjs.com/v1/agent",
"headers": {
"Authorization": "Bearer agk_your-agent-key"
}
}
}
}
```
### Self-hosted (stdio)
Set `COSMIC_MCP_SCOPE=agent` to expose only the signup tools from the stdio binary. Useful for desktop agents that want the MCP process inside their dev environment.
| Variable | Required | Description |
|---|---|---|
| `COSMIC_MCP_SCOPE` | Yes | Set to `agent` to load the agent tools instead of the bucket tools. |
| `COSMIC_AGENT_KEY` | No | If set, the `verify` and `status` tools authenticate with this key. If unset, only `cosmic_agent_signup` works until you run it once and capture the returned key. |
| `COSMIC_DAPI_URL` | No | Override the dashboard API base URL. Defaults to `https://dapi.cosmicjs.com/v3`. |
```json
{
"mcpServers": {
"cosmic-agent": {
"command": "npx",
"args": ["@cosmicjs/mcp"],
"env": {
"COSMIC_MCP_SCOPE": "agent",
"COSMIC_AGENT_KEY": "agk_your-agent-key"
}
}
}
}
```
### When to use which scope
- **`/v1/buckets/{slug}`** - the human already has a bucket. The agent reads, writes, and generates content with the bucket keys.
- **`/v1/agent`** - the human has no Cosmic account yet. The agent provisions a project on their behalf, hands them an OTP, and graduates to the bucket scope (or any other bucket-scoped surface) once verified.
It's common for a single conversation to use both: the agent calls `cosmic_agent_signup`, captures the bucket keys, and switches to the bucket-scoped tools to start creating content.
## MCP Server vs Agent Skills
The MCP server and Agent Skills serve different but complementary purposes:
| Feature | MCP Server | Agent Skills |
|---------|------------|--------------|
| **Purpose** | Direct content management | Code generation guidance |
| **Use case** | "List my blog posts" | "Build a blog with Cosmic" |
| **How it works** | AI calls tools to interact with your bucket | AI writes code using the SDK |
| **Best for** | Managing content while developing | Building applications |
**Use both together** for the best experience:
- **Agent Skills** helps your AI write application code that uses the Cosmic SDK
- **MCP Server** lets your AI directly manage content in your bucket
## Resources
- [Cosmic Documentation](/docs)
- [API Reference](/docs/api)
- [Agent Skills](/docs/agent-skills)
- [Discord Community](https://discord.com/invite/MSCwQ7D6Mg)
---
# Frameworks
Cosmic integrates seamlessly with popular frameworks. Select your prefered framework and learn how to get started delivering Cosmic-powered content.
## Next.js
## Astro
## Remix
## Express
## Nuxt
## Svelte
## Fastify
## RedwoodJS
## Vite
## Hono
## Bun
---
# Examples
The following examples show how to use Cosmic as a content management solution for common use cases. Use them as a starting point for your next project or as a way to learn Cosmic best practices.
## Next.js Agency Website
Agency website template built using Cosmic's React components, Blocks. Use this template as a starting point for your next project and learn how Blocks can be used to build content powered features for your website or app.
## Simple Next.js Blog
A simple Next.js blog template built using the Next.js app directory. It connects to the Cosmic API via the Cosmic JavaScript SDK. Install and manage your blog content from your Cosmic dashboard.
## Simple Astro Blog
This Astro blog template is built with Astro, Tailwind CSS, and Cosmic. Utilize the Cosmic headless CMS to store blog posts and media content.
## Next.js ToDo App
A ToDo app example that demontrates how to use Cosmic create, read, update, and delete methods using the Cosmic JavaScript SDK and React Server Actions.
## Message App
A message app that shows you how to add text and upload media to the Cosmic CMS using Next.js, the [Cosmic JavaScript SDK](https://www.npmjs.com/package/@cosmicjs/sdk), the [File Upload Block](https://blocks.cosmicjs.com/blocks/file-upload), and React Server Actions.
---
# Dashboard
# Dashboard
Cosmic offers a beautiful admin dashboard to create and manage your content. Learn about how to navigate and use the dashboard features in the following pages.
### Getting started
To get started, let's learn about projects.
---
# Projects
Learn about projects; where you store and manage your Buckets, team members, usage, and billing plans.
## Creating a project
Create a new project by going to [Dashboard > New Project](https://app.cosmicjs.com/projects/new).
You can start with an empty project or a template. Selecting a template will install demo content into your Bucket and provide an open source code repository for you to either download locally or deploy to a hosting provider.
### Projects home
Once you have added projects to your account, you will see your Projects available on the Projects home view.
### Adding Buckets
A project can have as many Buckets as you need. A common strategy for Buckets is to make them separate environments such as Production, Staging, Testing, etc.
## Team
Go to Project > Team to add, edit, and remove team members from your project.
Available roles include:
1. `Admin`: All manager access plus access to project usage,
settings, and billing.
2. `Manager`: Access to all Buckets. Can add Buckets and manage
members.
3. `User`: Access to specific Buckets in the project. Cannot add Buckets.
Set granular permissions for user roles for each Bucket.
## Usage
Go to Projects > Usage to keep track of your usage for your project. Available options include:
1. Month-to-date usage: See totals for team, Buckets, media, etc. Keep track of API and media requests.
2. Go to the Analytics tab to view historical data.
**Note:** Analytics data is retained for 90 days. Historical data older than 90 days will not be available for viewing.
## Billing
Enjoy the free plan forever. If you have more usage requirements than are available in the free plan, go to Project > Billing and select from available plans. Each plan has an option to bill monthly, or save 10% by choosing an annual plan. If you need more usage, reach out to [Cosmic sales](https://www.cosmicjs.com/enterprise).
## Add-ons
Add-ons are available in Project > Billing > Add-ons. Add-ons include:
1. Webhooks
2. Localization
3. Revision History
4. Automatic Backups
5. Additional team seats
6. Additional Buckets
Bundle all of the add-ons to save 50%.
---
# Buckets
Learn about Buckets; where you manage your Cosmic content, media, extensions, and add-ons.
## Creating a Bucket
You can create a new Bucket in a few different ways:
1. When creating a new Project.
2. When adding a new Bucket on an existing Project.
3. When cloning a Bucket in an existing Project.
### Buckets home
After you have created your Bucket, you will have a Bucket home view which gives you access to your recently modified content as well as other helpful links and resources.
## Object types
Object types are how you organize your content into specific content models. For example, if you are building content for your website, some Object types that you might create include: pages, blog posts, authors, etc.
Object types can be multiple or singleton. The `slug` field you include will be used to request the Objects in this type from the API.
Optional features on the Object type include:
1. Emoji: This is displayed on the dashboard for easy orginization and visual cues.
2. Localization: Set different locales on your Objects to provide content in different languages.
3. Preview link: Enable content editors to access a preview link from the Object edit view.
Organize your Object types into content folders to make them easily available
in the sidebar of the Bucket > Content view.
## Localization
You can add localization to your Object types to create versions of content in different languages. This is found in Bucket > Object type settings.
Set a priority locale to make this locale required and organize your Objects table with this one being displayed first.
## Metafields
Use Metafields to create your Object type content model. Available Metafields include:
1. Input fields: text, number, text area, rich text, markdown, JSON
2. Select fields: select, multi-select, dropdown, date, radio, checkbox, switch, color picker, and emoji
3. Media fields: image, video, audio, document, as well as other types
4. Group fields: parent (contains other Metafields), repeater (contains and can repeat groups of Metafields)
5. Object relationships: single Object, multiple Objects
Use validation, unique constraints, and help text on Metafields to provide
content editors with proper guard rails and content creation assistance. Set a
Metafield as unique to prevent duplicate values across Objects of the same
type (e.g. email addresses on contacts).
## Objects
Objects are the building blocks of your content in Cosmic.
In the add / edit Object view, content editors can perform a number of tasks including:
1. Create long form content.
2. Update Metafield values.
3. Set content to draft / published status.
4. Schedule content for publish / unpublish.
5. View revisions / restore to a prior version.
## Media
Go to Bucket > Media to manage the media in your Bucket. You can upload many different media types including images, video, audio, as well as documents such as PDFs, JSON files, etc.
Organize your media into folders to keep them organized and easy to filter
when adding media to Objects.
Media added here will be available for use in your Bucket Objects that have media Metafields.
### Replacing media
From any media item you can upload a new file to replace the original, either by uploading a new file or by saving edits from the image editor. The media URL and id stay the same, so any Object or page already referencing this media automatically picks up the new file. CDN caches are purged in the background so viewers see the updated file right away.
If the same file is shared with other Buckets you don't have access to (for
example through an width={800}
height={800}
alt="Cosmic Media"
unoptimized
className="w-full"
/>
### Adding an Extension
To add Extensions to your Project, go to Project > Extensions. Prebuilt Extensions are available to install and get up and running quickly. See the available Extensions on the [Cosmic integrations page](https://www.cosmicjs.com/integrations). Install them for free and browse the open source code to learn how to build your own Extensions.
### Build your own Extensions
An Extension provides an iframe view into a URL with dynamic query parameters. This enables you to connect to third-party APIs to interact with your Bucket directly from your Cosmic dashboard. The only requirements is that the URL is served securly with `https://` and has `X-Frame Options` enabled.
Go to Project > Extensions > Add Extension to add an Extension using any valid URL.
A good starting point is the [Cosmic Next Template](https://github.com/cosmicjs/cosmic-next-template), which comes prebuilt with the [Cosmic JavaScript SDK](https://www.npmjs.com/package/@cosmicjs/sdk), query parameter fetching, theming, and more. You can then deploy this codebase to your preferred hosting provider and use the URL to add as an Extension.
### Query parameters
After adding your Extension, query parameters are automatically attached to the URL for easy connection to your Bucket. The format looks like this:
```
https://my-extension.vercel.app?bucket_slug=your-bucket-slug&read_key=your-bucket-read-key&write_key=your-bucket-write-key&theme=dark
```
Available query parameters include:
| Name | Description |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bucket_slug` | Your Bucket slug. Use this to connect to your Cosmic Bucket for read / write / edits. |
| `read_key` | Your Bucket read key. Needed to read from your Bucket if this value is set in Bucket Settings > Basic. |
| `write_key` | Your Bucket write key. Needed for writes to your Bucket if this value is set in Bucket Settings > Basic. |
| [`custom_key` / `value`] | You can add unlimited custom query parameters such as third party API keys to connect to different services. Find this in your Cosmic Extension settings page. |
| `theme` | `light` or `dark`. Use this query parameter to get the current dashboard theme. |
| `page` | If location set to the edit Object page value is `edit-object`. |
| `location` | If location set to media modal value is `media-modal`. |
| `object_id` | If location set to edit Object, value is the Object id. Can be used to query more information about the Object. See [API reference for Objects](/docs/api/objects). |
### Extension locations
You can enable Extensions to appear in a few different locations:
1. **Full page** - appears in Project / Bucket / Extensions. Frame height is not editable.
2. **Add Object page** - appears in add Object page. Available locations include below the Object title, below the Object slug, below Metafields, and in the Object actions sidebar. Frame height is editable.
3. **Edit Object page** - appears in edit Object page. Available locations include below the Object title, below the Object slug, below Metafields, and in the Object actions sidebar. Frame height is editable.
4. **Media modal** - appears in an additional tab in the media modal. Frame height is not editable.
## Webhooks
Webhooks enable you to communicate with third-party services. The webhooks feature can be added to any project or workspace to connect to any third-party service via HTTP `POST` requests when certain events occur in your Buckets.
### Creating webhooks
Create a new webhook by going to Bucket > Settings > Webhooks and click "Add Webhook".
### Testing webhooks
You can use a service like [Beeceptor](https://beeceptor.com/) to test your webhooks and view response data.
See the [API reference for webhooks](/docs/api/webhooks) for more API information.
## Backups
The backups feature can be added to any project or workspace to enable automatic backups for any Bucket. Automatic backups occur daily at 12AM UTC.
Go to Bucket > Settings > Backups to view Bucket backups. You can also create a snapshot at any time. Download and restore to a previous backup snapshot.
## Promote content
Promote content moves selected Objects from one Bucket to another Bucket in the same Project. This is useful for workflows like promoting content from a staging Bucket to a production Bucket, or copying content into a sibling Bucket for testing.
### Where to promote from
1. **Objects table (bulk action)**: go to Bucket > Content > any Object type, select one or more Objects, and click **Promote** in the bulk action bar.
2. **Single Object row**: click the three-dot menu on any row in the Objects table and choose **Promote to Bucket**.
3. **Object detail view**: open an Object and click the three-dot menu at the top of the detail view.
### How it works
The promote flow walks through four steps:
1. **Target**: pick the destination Bucket from the list of Buckets in the current Project.
2. **Pre-flight**: a read-only report shows what will happen: Objects to create vs update vs skip, Object types to create or modify, referenced Objects that match in the target, and referenced media to copy.
3. **Options**: choose how to handle conflicts, schema differences, linked Objects, media, and status (detailed below).
4. **Confirm**: a summary screen lists the exact counts and any Object types that will be created or modified. Click **Promote** to run.
After completion, you can click **View in target bucket** to jump to the promoted content, including `cmd+click` to open in a new tab.
### What gets copied
- **Objects**: title, content, Metafields, thumbnail, status, and slug.
- **Object types**: if the target Bucket does not have the Object type, Cosmic creates it automatically using the source schema.
- **Media**: any media referenced by the promoted Objects (file Metafields, thumbnails, embedded URLs in rich text or Markdown) is copied into the target Bucket's Media Library. Media that has already been copied is reused, so re-promoting does not create duplicates.
- **Object references**: Metafields that reference other Objects are remapped to matching Objects in the target Bucket, matched by type, slug, and locale (when set). If no match is found, the reference is either cleared or the referenced Object is also promoted (see Cascade below).
- **Object revisions**: a new revision is saved for every created, updated, or cascaded Object, so you can review or restore past states.
### Options
**Conflict strategy** (when a matching Object already exists in the target):
- `Update in place` (default): overwrite the matching target Object with the source content.
- `Create new with suffixed slug`: insert a new Object with a unique slug, leaving the existing one untouched.
- `Skip and report as conflict`: do nothing for that Object and flag it in the result.
**Schema strategy** (when the target Bucket has the Object type but the Metafield schema differs):
- `Merge` (default): add any missing Metafields from the source to the target. Non-destructive.
- `Overwrite`: make the target schema match the source exactly. This removes Metafields that exist in the target but not in the source, which can delete data on existing Objects in the target Bucket. Requires typing `OVERWRITE` to confirm.
- `Strict`: block the promotion if the schemas differ at all.
**Linked objects**: if enabled (Cascade), Objects referenced by the promoted Objects that do not exist in the target Bucket will be promoted alongside. If disabled (default), unmatched references are left unresolved and surfaced in the pre-flight report.
**Include referenced media**: if enabled (default), any media referenced by the promoted Objects is copied to the target Bucket. If disabled, media stays referenced via its original URLs.
**Status override**: choose whether to preserve the source Object's status, force all promoted Objects to `draft`, or force them to `published`.
### Permissions
You need write access on both the source and target Buckets. Schema-altering actions (creating Object types or overwriting schemas) may additionally require a Project admin role depending on your Bucket settings.
### Re-promoting
Promotions are safe to re-run. Promoting the same content again updates the existing target Objects in place and reuses any previously copied media, so you can use Promote as part of a repeatable staging to production workflow.
## Import / Export
All Buckets include the ability to import or export all of the content in the Bucket at any time. This export is a JSON file which includes data for Object types, Objects, Media, folders, but does not include team members, Object revisions, or backups. Go to Bucket > Settings > Import / Export to perform this action.
---
# Workspaces
Learn about workspaces; where you store your projects, manage your team, usage, and billing.
## Creating a workspace
Click the top left dropdown of the main navigation. Here you will see your workspaces as well as a link to create a new workspace.
Add the workspace title, slug, and select which plan. [Contact sales](https://www.cosmicjs.com/enterprise) to get assistance creating a custom plan for your team.
## Team
Go to Workspace > Team to add, edit, and remove team members from your workspace.
Available roles include:
1. `Admin`: Manager access plus access to settings, billing, and usage.
2. `Manager`: Access to all projects. Can add projects and manage members.
3. `User`: Specific project access only. Cannot add projects.
## Usage
Go to Workspace > Usage to keep track of your usage for your workspace. Available options include:
1. Month-to-date usage: See totals for projects, team, Buckets, media, etc. Keep track of API and media requests.
2. Go to the Analytics tab to view historical data.
**Note:** Analytics data is retained for 90 days. Historical data older than 90 days will not be available for viewing.
## Billing
Go to Workspace > Billing and select from available plans. Each plan has an option to bill monthly, or save 10% by choosing an annual plan. If you need more usage, reach out to [Cosmic sales](https://www.cosmicjs.com/enterprise).
## Add-ons
Add-ons are available in Workspace > Billing > Add-ons. Add-ons include:
1. Webhooks
2. Localization
3. Revision History
4. Automatic Backups
5. Additional team seats
6. Additional Buckets
Bundle all of the add-ons to save 50%.
---
# Search
Learn about the dashboard search feature.
## How to use search
Click the search input at the top right of the main navigation, or use the quick key command `⌘ K` to initialize the search modal.
Here you can search by title to find content within your Buckets such as Object types, Objects, and media. Other useful links include support, documentation, and the ability to update your theme to light or dark mode.
---
# Account
Learn about the features of your Cosmic account.
## Creating an account
Create your free Cosmic account by going to https://app.cosmicjs.com/signup.
## Account settings
Click your avatar in the main navigate and follow the link to account settings.
In the account settings view, you can update the following:
1. Avatar
2. First and last name
3. Email address
4. Password
## Billing details
Go to Account settings > Billing details to update your billing information.
## Invoices
Once invoices are available for you to view, you can go to Account settings > Invoices to view prior invoices.
## Two-factor authentication
Go to Account settings > Two-factor authentication to add two-factor authentication (2FA) to your account. 2FA is an added layer of security which, once activated, will require you to input a code generated from text message to log in to your account.
## Saved Authentications
Go to Account settings > Saved Authentications to manage browser sessions for [Computer Use Agents](/docs/dashboard/ai/agents). Saved authentications let you capture and reuse login sessions so your agents can access protected sites without re-authenticating each time.
### How it works
1. Click **"Add Authentication"** and enter the URL of the site you want to authenticate with (e.g., `https://github.com`)
2. A browser window opens for you to log in normally. You can open multiple tabs to log into different services in the same session
3. Complete any verifications (2FA, CAPTCHA, etc.), then close the browser window
4. Your session (cookies, localStorage) is encrypted and saved to your account
### Using saved authentications
When creating or editing a Computer Use Agent or workflow step, the **Pre-Authentication** section shows your saved authentications under **"Use Saved Authentication"**. Select one or more to pre-load those sessions into the agent's browser before it starts.
You can also use saved authentications alongside manually captured sessions. The agent merges all authentication data before execution.
### Managing saved authentications
From the Saved Authentications settings page you can:
- **Edit** the label of any saved authentication
- **Delete** authentications you no longer need
- **View usage** to see which agents and workflows reference a credential before deleting
### Security
- All session data is encrypted at rest using AES-256 encryption
- Sessions are scoped to your user account and cannot be accessed by other users
- Deleting a saved authentication removes it from all agents and workflows that reference it
## API Tokens
Go to [Account Settings > API Tokens](https://app.cosmicjs.com/account/api-tokens) to create and manage Personal Access Tokens (PATs) for programmatic API access.
### What are API Tokens?
API Tokens let you authenticate with the Cosmic API from scripts, CI/CD pipelines, the [Cosmic CLI](/docs/cli), [MCP Server](/docs/mcp-server), or any external application. Tokens carry the same permissions as your account and use the `cos_` prefix for easy identification.
### Creating a token
1. Go to [Account Settings > API Tokens](https://app.cosmicjs.com/account/api-tokens)
2. Click **"Create Token"**
3. Enter a descriptive name (e.g., "CI/CD Pipeline", "MCP Server", "CLI")
4. Choose an expiration period (30 days, 60 days, 90 days, 1 year, or no expiration)
5. Click **"Create"**
The token is displayed once after creation. Copy it immediately and store it securely. You will not be able to see it again.
### Using a token
Include your token in the `Authorization` header of API requests:
```bash
curl https://dapi.cosmicjs.com/v3/users/get \
-H "Authorization: Bearer cos_YOUR_TOKEN"
```
### Managing tokens
From the API Tokens settings page you can:
- **Edit** the name of any token
- **Delete** tokens you no longer need (applications using a deleted token will lose access immediately)
- **View last used** to see when a token was last used for authentication
### Security
- Tokens are hashed with SHA-256 before storage. Cosmic never stores the plain token.
- Tokens carry your full account permissions. Treat them like passwords.
- Use short expiration periods for tokens used in less secure environments.
- Delete tokens you are no longer using.
## Light / dark mode
The dashboard will default to your system preferences for either light or dark mode. To override this, you can click your avatar to show the dropdown and toggle to either theme. This can also be done via the search modal.
---
# Cosmic Pages
Cosmic Pages are dedicated web pages that host your Cosmic content. Convert any Object in your Cosmic Project into a page with a single click, no coding required. With Cosmic Pages you can enable frictionless sharing of content with your team or anyone outside your team.
## How it works
Go to any existing Object in your Project. Then click the share icon at the top of the page. Click "Publish to web".
Your Object will be available on a dedicated page with its own unique public URL.
## Benefits
Cosmic Pages enable content review without login or custom coding. Share content with your team and the world to get feedback faster.
## Get started
[Log in](https://app.cosmicjs.com/login) to your Cosmic account and start using Cosmic Pages today.
---
# AI
Cosmic offers a suite of features in the dashboard powered by AI to help you build your Cosmic projects faster.
For **[Agents](/docs/dashboard/ai/agents)** (Team Agents, automations, channels, capabilities, and API) and **[Workflows](/docs/dashboard/ai/workflows)** (multi-step orchestration and execution retention), see those guides. This page focuses on AI Studio, content and media generation, translation, and usage limits.
## AI Studio
### Content Model Generation
The AI Studio generates complete content structures from natural language descriptions. Instead of manually configuring fields, relationships, and validation rules, you can describe what you need and receive a fully functional content model with multiple content types, relationships, and demo content to get started fast.
**Content model capabilities:**
- Generate content models for any type of website or application
- Add new content types that integrate with existing structures
- Configure relationships between content types automatically
- Create complex multi-language structures with custom validation
**Working examples:**
- "Create a content model for an e-commerce store with products, collections, and customer reviews"
- "Add an Events content model that relates to my existing blog posts and authors"
- "Set up a portfolio website with projects, skills, and testimonials"
### Content Management
Beyond structure creation, the AI handles content generation and management at scale.
**Content operations:**
- Generate realistic sample content for testing and development
- Bulk update existing content with new fields and metadata
- Maintain consistency across large content datasets
- Apply SEO optimization and structured data automatically
**Practical applications:**
- "Create 10 sample blog posts with realistic content for my existing blog model"
- "Update all product entries to include pricing and availability status"
## Application Development and Deployment
### AI-Powered Code Generation
The Cosmic AI Platform generates production-ready applications using your existing
content structure. Applications are built with modern frameworks and include proper
TypeScript definitions, responsive design, and performance optimizations.
**Supported frameworks:**
- Next.js applications with server-side rendering
- React dashboards and single-page applications
- Astro static sites with modern tooling
- Vue.js progressive web applications
## AI assisted development
Click the "AI chat" button in the top right corner of the Cosmic dashboard to open the AI chat drawer. Use AI chat to learn how to integrate your content into your apps. Available for the admin and developer role.
## Get insights from media
Click the "AI chat" button on any media asset to get summaries and insights from PDFs, spreadsheets, documents, and more. Available for all roles.
## Generate alt text
To generate alt text for an image, go to any image, find the alt text area, and click the "Generate" button. You can also generate alt text for a group of images at once. Available for all roles.
## Generate images
To generate images, open the Media modal, click the "Create" button, and describe the image you want to generate. Available for all roles.
## Generate videos
Create compelling video content using natural language, powered by Google's Veo 3.1 models. Available for all roles.
> Prompt: "Cinematic close-up of raindrops falling on a window at night, city lights blurred in background"
**Key features:**
- **Native audio generation** - Videos include automatically generated audio that matches your scene
- **Two quality tiers** - Fast (30-90s) or Standard (60-180s, premium cinematic quality)
- **Flexible options** - Generate 4, 6, or 8-second videos at 720p or 1080p
- **Image-to-video mode** - Use a reference image as the starting frame for precise control
- **Video extension** - Extend any Veo-generated video to create longer sequences
**How to use:**
1. Navigate to **Media** in your project
2. Click **"Create"** and select **"Video Generation"**
3. Choose **"Veo 3.1 Fast"** or **"Veo 3.1 Standard"**
4. Enter your video prompt
5. (Optional) Add a reference image for image-to-video mode
6. Choose duration and resolution, then click **"Generate"**
Videos are automatically saved to your Media Library with global CDN delivery. See the [AI API documentation](/docs/api/ai#generate-video) for programmatic access.
## Generate audio
Convert any text to natural-sounding speech using OpenAI's text-to-speech models. Perfect for creating audio versions of articles, podcast intros, product descriptions, and more. Available for all roles.
**Key features:**
- **9 natural-sounding voices** - Feminine (nova, shimmer, coral, sage, alloy) and masculine (echo, onyx, fable, ash)
- **Two quality tiers** - Standard (fast, low-latency) or HD (higher quality, 2x cost)
- **Long text support** - Texts over 4,096 characters are automatically chunked and concatenated
- **Instant media library** - Generated audio is saved as MP3 and available via CDN
**How to use:**
1. Navigate to **Media** in your project
2. Click **"Create"** and select **"Audio"**
3. Select a **voice** from the dropdown (default: Nova)
4. Paste or type the text you want to convert to speech
5. Click **"Generate"** to create the audio file
Audio files are automatically saved to your Media Library in MP3 format. See the [AI API documentation](/docs/api/ai#generate-audio) for programmatic access.
## Auto translate content with AI
You can use Cosmic AI to auto translate content from one language to another. Available for all roles.
## Content generation
You can use Cosmic AI to generate content for your projects. Create summaries, SEO optimized content, translations, and more. Available for all roles.
Agents
Documentation for Team Agents, automations, channels, capabilities, conversation memory, Slack/Telegram/WhatsApp setup, slash commands, sharing conversations, and the messaging API now lives on **[Agents](/docs/dashboard/ai/agents)**.
---
Workflows
Documentation for chaining agents, schedules, event-triggered workflows, and related best practices now lives on **[Workflows](/docs/dashboard/ai/workflows)**.
---
Execution Retention
Execution retention for agent and workflow runs is documented under **[Workflows: Execution retention](/docs/dashboard/ai/workflows#execution-retention)**.
## Usage and limits
Cosmic AI is available on all Cosmic plans with varying limits. You can add more tokens to your account by upgrading your plan or adding the AI tokens add-on. Go to the [pricing page](https://www.cosmicjs.com/pricing) to learn more.
### Tokens
Tokens are the unit of usage for Cosmic AI. In general, 1 token equals 1 word or 4 characters. You can view your AI usage from the Usage section of your projects.
**Input tokens** are the number of tokens used in your request. These are typically lower cost and represent the content you send to the AI (prompts, context, etc.). For text generation, this includes your messages and conversation history.
**Output tokens** are the number of tokens generated by the AI. These are higher cost (typically 5x more than input tokens) and represent what the AI creates:
- **Text generation**: Varies by response length
- **Image generation**: Fixed cost per image (4,800 - 57,600 tokens depending on model and size)
- **Video generation**: Fixed cost per video (144,000 - 768,000 tokens depending on model and duration)
Media generation (images and videos) costs are counted as **output tokens** to reflect the computational requirements of generating visual content.
## Getting started
[Log in](https://app.cosmicjs.com/login) to your Cosmic account and start using Cosmic AI today.
---
# Agents
AI Agents are autonomous assistants that work on tasks independently. Agents help you automate content management, application development, and browser-based workflows. For recurring or scheduled execution, use [Workflows](/docs/dashboard/ai/workflows) to run agents on a schedule.
**Access Requirements**: AI Agents are available to users with **Admin** or **Developer** bucket roles only. Editor and Contributor roles do not have access to these features.
**Where agents live**: Agents are project-scoped, so they are available across every bucket in the project. **Team Agents** have their own top-level section in the project sidebar (**Project > Team Agents**). **Content, Code, and Computer Use agents** are managed as **Automations** inside the project's **AI Studio**, alongside multi-step **Workflows**.
## Agent Types
Cosmic provides four specialized agent types, each designed for specific automation tasks:
### Team Agent
The Team Agent joins your communication channels as a fully conversational AI team member. Define a persona with a custom name, role, and personality. Set measurable goals and let the agent communicate with your team on Slack, WhatsApp, Telegram, and more. Team Agents can read and write CMS content, build and deploy applications, and manage connected GitHub repositories, all while carrying on natural conversations.
**Capabilities:**
- Multi-channel presence on Slack, WhatsApp, Telegram, API, Webhook, and Email
- Persona-driven conversations with custom name and personality
- Measurable goal tracking aligned with business objectives
- Scheduled heartbeats for proactive check-ins (Mon-Fri, daily, etc.)
- Lead qualification and customer support automation
- CMS read and write access for content-aware responses
- Code read and write access for connected GitHub repositories
- Runtime log analysis to diagnose production errors and create fixes
- Build and deploy full web applications from a conversation
**Example prompts:**
- "You are Lisa, our CMO. You are strategic, data-driven, and creative. Ask clarifying questions about target audience and goals before proposing campaigns."
- "You are Sam, our Customer Success Manager. Be warm and empathetic. Help customers get the most value from our product. Escalate bugs to engineering."
### Content Agent
The Content Agent works directly with your Cosmic CMS to create, update, and manage content at scale. It understands your existing content structure, researches topics via progressive web discovery, and generates perfectly formatted objects that match your schema.
**Capabilities:**
- Generate blog posts, landing pages, and product catalogs
- Create and modify object types with custom metafields
- Progressive web discovery for research-backed content
- Batch operations for bulk content creation
- Auto-publish or human review workflow
- Email notifications on task completion
**Example prompts:**
- "Research the latest AI trends from Hacker News and TechCrunch, then create a 5-part blog series covering each major development"
- "Create a complete product catalog for our new summer collection with 20 products, descriptions, and pricing"
### Code Agent
The Code Agent connects to your GitHub repository and writes production-ready code autonomously. It discovers relevant files, understands your codebase structure, creates feature branches, commits changes, and opens pull requests.
**Capabilities:**
- Progressive file discovery to understand codebases
- Automatic branch creation and PR submission
- Conflict detection and auto-resolution
- Multi-iteration development with checkpoints
- CMS integration for content-aware features
- Email notifications with commit summaries
**Example prompts:**
- "Build a user notification system with real-time updates, API endpoints, and React components with TypeScript"
- "Create a dynamic landing page that pulls content from our Cosmic CMS with hero section, feature grid, and testimonials"
### Computer Use Agent
The Computer Use Agent sees and controls browsers exactly like a human. It can fill out forms, record demo videos, download and upload media across platforms, and automate any workflow you can do manually.
**Capabilities:**
- Professional demo video recording with animated cursors
- Cross-platform media transfer and downloads
- AI-powered content extraction from web pages
- Visual navigation with stealth mode
- Screenshot and file operations
- Authenticated browser sessions with [Saved Authentications](/docs/dashboard/account#saved-authentications)
**Pre-Authentication:**
Computer Use Agents can start with pre-authenticated browser sessions, so they can access protected sites without manual login. Manage reusable credentials in your [Account settings > Saved Authentications](/docs/dashboard/account#saved-authentications), then select one or more from the agent's Pre-Authentication section. Saved Authentications persist across runs and can be shared between agents and workflows.
**Real-time input and unblocking:**
You can give a Computer Use Agent input while it is running, directly from the run detail page. This is useful when the agent hits something only you can resolve, or when you simply want to steer it.
- **When the agent asks**: If the agent runs into a blocker it cannot resolve on its own, such as a verification or 2FA code, a CAPTCHA, or an ambiguous choice, it pauses and shows a **Waiting for input** prompt with its question and a screenshot of the current screen. Type your response and the agent continues from where it left off.
- **Proactive steering**: While a run is in progress, you can send the agent input at any time using the **Send input to the agent** field, even if it did not ask. Your message is added to the conversation and taken into account on the next step.
- **Email notice**: When the agent pauses for input, an email is sent to you with the agent's question and a link to the run, as long as Email Notifications are enabled for the agent. This way you do not have to keep the run open to know it needs you.
- The browser session stays open while the agent waits, so no progress is lost. If no input is provided within 15 minutes, the run stops automatically.
**Execution Limits:**
- Each Computer Use Agent execution is limited to **100 steps** (actions) by default
- This limit helps prevent runaway costs and ensures efficient task completion
- The agent automatically stops when the goal is achieved, typically well before reaching the limit
- If your task doesn't complete within 100 steps, consider breaking it into smaller, more focused tasks
**Example prompts:**
- "Record a 2-minute demo video of our new dashboard feature, navigate through the analytics section, and export a report"
- "Download our top-performing video from TikTok, then upload it to YouTube Shorts and Instagram Reels with optimized captions"
## Creating an Agent
Team Agents and Automations are created in separate places in the project sidebar.
**To create a Team Agent:**
1. Open your project and click **Team Agents** in the project sidebar
2. Click **"Create Team Agent"**
3. Give the agent a name, persona, and prompt, then configure channels (Slack, WhatsApp, Telegram, Email, API, Webhook) and capabilities
4. (Optional) Enable a heartbeat schedule for proactive check-ins
**To create a Content, Code, or Computer Use automation:**
1. Open your project and click **AI Studio** in the project sidebar, then choose **Automations**
2. Click **"Create Automation"**
3. Choose your agent type (Content, Code, or Computer Use)
4. Describe the task you want the automation to complete
5. (Optional) For content automations, enable Progressive Discovery to crawl web content
6. (Optional) Set a schedule or an event trigger so the automation runs automatically
**Tip**: From any bucket you can also jump into **AI Studio > Create with AI** to describe what you want in natural language, and Cosmic will help scaffold the right agent or automation for you.
**Note**: Content, Code, and Computer Use automations can run on a recurring schedule or be chained inside [Workflows](/docs/dashboard/ai/workflows). Team Agents support heartbeat schedules directly from the Team Agent form for proactive check-ins.
## Event Triggers
Agents can be triggered automatically when content events occur. When enabled, your agent runs automatically whenever selected events happen on matching object types.
**Available Events:**
- **Object Created**: Triggers when a new object is added
- **Object Edited**: Triggers when an existing object is modified
- **Object Deleted**: Triggers when an object is removed
- **Object Published**: Triggers when an object's status changes to published
- **Object Unpublished**: Triggers when a published object is unpublished
**Event Context Data:**
When an event triggers your agent, the following data is automatically included in the prompt context:
- **Event Type**: The action that triggered the agent (created, edited, published, etc.)
- **Object Type**: The content type that was affected
- **Object ID**: The unique identifier of the object
- **Object Title**: The title of the triggered object
- **Object Slug**: The slug of the triggered object
- **Object Status**: Current status (draft, published, etc.)
- **Object Metadata**: All field values from the object
**Using Event Data for Conditional Logic:**
You can reference this event data in your prompt to implement conditional behavior:
```
If the object status is "draft", generate SEO metadata for the content.
If the object is already "published", complete early without changes.
If the object type is "blog-posts" and the title contains "urgent",
prioritize this task and notify the team.
```
**Example Use Cases:**
- Auto-generate social media posts when a blog is published
- Create translations when new content is added
- Update related content when a product price changes
- Send notifications based on specific field values
## Team Agent Configuration
Team Agents are conversational by default. They receive messages and respond through multiple channels, maintain conversation context, use tools to interact with your CMS and external services, and support both real-time chat and automated scheduled messaging. When you create a Team Agent, channels, capabilities, and memory settings are available directly in the agent form.
Just ask your agent "What can you do?" and it will tell you exactly which capabilities are enabled and what tools it has access to. This is the fastest way to understand what your agent can help with.
### Channels
Channels determine how messages reach your agent. You can enable multiple channels simultaneously.
- **REST API**: Send messages to your agent programmatically using a [Personal Access Token](/docs/dashboard/account#api-tokens). After creating a Team Agent, the endpoint URL is shown on the agent detail page. Create a token at [Account Settings > API Tokens](https://app.cosmicjs.com/account/api-tokens), then authenticate requests with it:
```bash
curl -X POST https://dapi.cosmicjs.com/v3/ai/agents/AGENT_ID/messages \
-H "Authorization: Bearer cos_YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"message": "Hello, agent!"}'
```
Use this for custom integrations, scripts, or any application that needs to communicate with your agent programmatically.
- **Inbound Webhook**: Receive messages from external systems without Cosmic authentication. When enabled, a webhook endpoint and secret are shown on the agent detail page. Use the **Reveal** button to view the secret and **Copy** to copy it.
Authenticate webhook requests using one of these methods:
| Method | How to use |
|---|---|
| Query parameter | `?secret=YOUR_WEBHOOK_SECRET` |
| Header | `X-Webhook-Secret: YOUR_WEBHOOK_SECRET` |
| Header (alternate) | `X-Cosmic-Webhook-Secret: YOUR_WEBHOOK_SECRET` |
| HMAC signature | `X-Webhook-Signature: sha256=HMAC_HEX` (HMAC-SHA256 of the raw request body using the secret as the key) |
```bash
curl -X POST https://dapi.cosmicjs.com/v3/ai/agents/AGENT_ID/webhook?secret=YOUR_WEBHOOK_SECRET \
-H "Content-Type: application/json" \
-d '{"message": "New deployment completed successfully"}'
```
The request body should include a `message` field (string, required). Optional fields: `conversation_id` (to continue an existing conversation) and `metadata` (object, passed to the agent as context). If a webhook secret is compromised, click **Regenerate** on the agent detail page to generate a new secret. The old secret stops working immediately. Use this for third-party integrations like Zapier, GitHub Actions, or any automation platform.
- **Slack**: Chat with your agent directly in a Slack channel. Requires the Slack integration to be configured in your Bucket Settings > Integrations (see [Setting up Slack](#setting-up-slack)). Once connected, select a Slack channel and your agent will respond to messages there. The agent can see recent channel history (up to 50 messages), so it has full context of the team conversation when responding. For thread replies, the agent sees the full thread context. Enable **"Only respond when @mentioned"** to limit the agent to only replying when explicitly tagged with `@Cosmic Agent`. When this option is on, the agent still sees the full channel conversation but only responds to @mentions. Supports [conversation commands](#conversation-commands) like `/reset` and `/tokens`.
- **Telegram**: Chat with your agent through a Telegram bot. Set up the bot token in your Bucket Settings > Integrations (see [Setting up Telegram](#setting-up-telegram)), then generate a connect code in the agent edit page and send `/connect ` to the bot in your Telegram chat to link the agent. Supports [conversation commands](#conversation-commands) like `/reset` and `/tokens`.
- **WhatsApp**: Chat with your agent on WhatsApp. Cosmic supports two modes: a **shared number** hosted by Cosmic (quick start), or **Bring Your Own Number (BYON)** where you connect your own WhatsApp Business number for full control. Enable WhatsApp on your agent, generate a connect code, and tap the "Open WhatsApp" link to send the activation code. Once paired, any message from that phone number is routed to the agent. See [Setting up WhatsApp](#setting-up-whatsapp) for configuration details. Supports [conversation commands](#conversation-commands) like `/reset` and `/tokens`.
- **Email**: Receive and respond to messages via email. When enabled, the agent can participate in email-based conversations with your team or customers.
### Capabilities
Capabilities control what your agent can do when processing messages. Enable only the capabilities your agent needs. Each capability unlocks a set of tools that the agent can call autonomously.
#### CMS Read
Query and read objects, object types, and media from your bucket.
**Tools:**
- **get_objects**: Fetch objects from the CMS, filtered by object type, search query, with pagination. Parameters: `type`, `query`, `limit`, `skip`, `props`
- **get_object_types**: List all content models (object types) in the bucket and their metafield schemas
- **get_media**: Fetch media files from the media library with optional search and pagination. Parameters: `limit`, `skip`, `query`
**Example prompts:**
- "List all published blog posts"
- "Show me the schema for the products object type"
- "Find media files with 'hero' in the name"
#### CMS Write
Create, update, and delete objects and object types in your bucket. Also includes AI image generation and media uploads.
**Tools:**
- **create_object_type**: Create a new content model with metafield definitions. Parameters: `title`, `slug`, `singular`, `emoji`, `metafields`. Supports `show_when` on metafields for [conditional visibility](/docs/api/metafields#conditional-visibility)
- **update_object_type**: Update an existing content model (rename, add/remove metafields). Parameters: `type_slug`, `title`, `singular`, `emoji`, `metafields_to_add`, `metafields_to_remove`. Supports `show_when` on metafields for [conditional visibility](/docs/api/metafields#conditional-visibility)
- **create_object**: Create a new CMS object. Parameters: `type`, `title`, `slug`, `thumbnail`, `metadata`, `status`, `publish_at`, `unpublish_at`
- **update_object**: Edit an existing object by ID. Parameters: `id`, `title`, `slug`, `thumbnail`, `metadata`, `status`, `publish_at`, `unpublish_at`
- **delete_object**: Delete an object by ID. Parameters: `id`
- **batch_objects**: Create, update, or delete up to 25 objects in a single call. Each operation succeeds or fails independently. Parameters: `operations` (array of `{ method, type, id, title, metadata, status, ... }`)
- **generate_image**: Generate an AI image from a text description and upload it to the media library. Parameters: `prompt`, `size`, `aspect_ratio`
- **upload_media**: Upload a file from a public URL to the media library. Parameters: `url`, `name`, `folder`
**Example prompts:**
- "Create a new blog post about AI trends"
- "Generate a hero image for the homepage"
- "Upload the image from this URL to the media library"
- "Update the status of all draft posts to published"
#### Code Read
Read files and browse the directory structure of a connected GitHub repository. The agent can discover relevant files, understand your codebase structure, and search for specific content.
**Tools:**
- **list_repository_files**: List files and directories in the connected repo, filtered by an optional path prefix. Parameters: `path` (optional), `branch` (optional)
- **read_file**: Read the contents of a file from the repo. Parameters: `path` (required), `branch` (optional)
- **search_files**: Search for files by filename pattern (e.g. "*.tsx", "package.json"). Parameters: `pattern` (required), `path` (optional directory filter)
- **list_branches**: List all branches in the repo with their latest commit SHA and protection status
- **get_repository_info**: Get metadata about the connected repository including production URL, GitHub URL, framework, and Vercel project details
- **get_deployments**: List recent Vercel deployments with status, URLs, commit info, and timestamps. Parameters: `limit` (optional, default 5, max 20)
- **get_deployment_logs**: Get build and deployment logs for a specific Vercel deployment. Use `get_deployments` first to find the deployment ID, then use this tool to see the full build output including any errors. Parameters: `deployment_id` (required)
- **get_access_logs**: Get runtime access logs and function console output for a deployed Vercel project. Shows HTTP requests with status codes, paths, and methods, plus any `console.log`/`console.error` output from serverless functions. Useful for diagnosing production errors like 500s, 404s, or failed form submissions. Defaults to showing errors (status >= 400) from the last 24 hours. Parameters: `time_range` (optional: `1h`, `6h`, `24h`, `3d`), `status_filter` (optional: `errors`, `client_errors`, `server_errors`, `all`), `method` (optional), `path` (optional, supports regex), `limit` (optional, default 50, max 100)
**Example prompts:**
- "Show me the contents of src/index.ts"
- "List all files in the components directory"
- "Search for files that - "Fix the bug in the header component and open a PR"
- "Merge pull request #42 using squash"
- "Set the GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET env vars on the gmail-utils repo"
- "Build me a blog app with posts, categories, and an author page"
- "Check the status of my app build"
- "Deploy the app we just built"
#### Web Browse
Fetch and read content from web page URLs. The agent can research information, read linked articles, and gather context from the web.
**Tools:**
- **fetch_url**: Fetch and read web page content (HTML stripped to text). Parameters: `url`
**Example prompts:**
- "Read the content of https://example.com/blog/ai-trends"
- "Summarize the article at this URL"
#### API Requests
Make HTTP requests to any external REST API or service. Supports all standard HTTP methods (GET, POST, PUT, PATCH, DELETE) with custom headers for authentication. Use this to integrate with third-party services like Zapier, Shopify, Stripe, Gmail API, or any REST endpoint. All requests must use HTTPS.
**Secrets** allow you to store sensitive values like API keys and tokens securely. Values are encrypted at rest using AES-256-GCM and never exposed in conversations or logs. You can manage secrets from the agent form UI or let the agent manage them conversationally. Reference a secret in any endpoint URL or header value using the template syntax ``. The template is resolved server-side at runtime, so raw credentials are never sent to the model.
**API Endpoints** let you save reusable endpoint configurations (URL, method, headers, body template) so the agent can call them by name instead of rebuilding requests from scratch. Endpoints can reference secrets in their headers and URLs.
**Tools:**
- **api_request**: Make an HTTP request to an external API. Parameters: `url` (required, HTTPS only), `method` (required: GET/POST/PUT/PATCH/DELETE), `headers` (optional), `body` (optional JSON for POST/PUT/PATCH). Secret references (``) in URLs and headers are resolved automatically before the request is sent.
- **manage_api_endpoints**: Save, update, list, and remove reusable API endpoint configurations. Actions: `list`, `add`, `update`, `remove`. When adding or updating, the agent can include `` references in headers and URLs.
- **manage_secrets**: Securely store, list, and remove API keys and tokens. Actions: `list` (returns names and IDs only, never raw values), `add` (encrypts and stores a new secret), `remove` (deletes a secret, with a warning if referenced by any saved endpoints).
**Example prompts:**
- "Save my Stripe API key as a secret, then add an endpoint for listing customers"
- "POST the updated product data to the Shopify API"
- "GET the latest orders from the Stripe API and summarize them"
- "Send a trigger to my Zapier webhook with the new content data"
- "List my saved secrets and endpoints"
#### Send Notifications
Send messages to project members via email, Slack, Telegram, or WhatsApp. Email recipients are restricted to confirmed project members for security. Slack, Telegram, and WhatsApp require the respective integration to be connected in Project Settings > Integrations.
**Tools:**
- **send_email**: Send an email to project members. Use `to: "owner"` for the project owner, `to: "team"` for all members, or a specific project member email address. Parameters: `to`, `subject`, `body`
- **send_slack_message**: Post a message to a Slack channel. Uses the agent's configured Slack channel by default. Parameters: `message`, `channel_id` (optional), `blocks` (optional Block Kit JSON)
- **send_telegram_message**: Send a message to a Telegram chat. Uses the agent's configured Telegram chat by default. Parameters: `message`, `chat_id` (optional)
- **send_whatsapp_message**: Send a message to a WhatsApp user. Uses the agent's connected WhatsApp phone number by default. Parameters: `message`, `phone_number` (optional)
**Example prompts:**
- "Email the team that the content migration is complete"
- "Post a summary of today's published articles to the Slack channel"
- "Send a Telegram alert that the scheduled workflow finished"
- "Send a WhatsApp message to let them know the order shipped"
#### Agent Delegate
Hand off tasks to other agents in the same project. Useful for orchestrating specialized agents where one agent coordinates work across others.
**Tools:**
- **message_agent**: Send a message to another agent and receive its response. Parameters: `agent_id`, `message`
**Example prompts:**
- "Ask the content-writer agent to draft a blog post about this topic"
- "Delegate the image generation to the media agent"
#### Agent Manage
Create, list, update, and delete agents and workflows in the project. Allows agents to self-manage and orchestrate other agents programmatically.
**Tools:**
- **list_agents**: List all agents in the project with their IDs, names, types, and status
- **create_agent**: Create a new agent (content, repository, or computer_use type)
- **update_agent**: Update an agent's configuration (name, prompt, capabilities, schedule, status)
- **delete_agent**: Delete an agent and all its execution history
- **list_workflows**: List all workflows in the project
- **get_workflow**: Get a single workflow's full configuration, including all steps and their prompts
- **create_workflow**: Create a new multi-step workflow with ordered agent steps
- **update_workflow**: Update an existing workflow in place (name, steps, schedule, status) without changing its ID
- **delete_workflow**: Delete a workflow and its execution history
When building workflow steps, set `agent_type` to `content`, `repository`, `computer_use`, or `team`. A `team` step runs an existing team agent with its own capabilities and tools (including `api_request`); it requires `config.agent_id` set to that team agent's ID. Use this when a step needs the full team-agent toolset rather than the limited content/code/computer-use toolset.
**Example prompts:**
- "Create a new content agent called weekly-reporter"
- "List all agents in this project"
- "Pause the daily-digest agent"
- "Create a workflow that runs the content agent then the code agent"
- "Add a step to the orders workflow that runs my Hunter team agent to enrich the data"
#### Execute Workflows
Run workflows and check their execution status. Workflows are multi-step automated processes that chain agents together.
**Tools:**
- **execute_workflow**: Run a workflow by ID with optional trigger data. Parameters: `workflow_id`, `trigger_data`
- **get_workflow_status**: Check the status of a running workflow execution. Parameters: `execution_id`
**Example prompts:**
- "Run the content-pipeline workflow"
- "Check the status of the last workflow execution"
#### Always Available Tools
These tools are available to all Team Agents regardless of which capabilities are enabled:
- **send_message**: Send a formatted message to the current conversation channel
- **request_approval**: Pause execution and request human approval before proceeding with an action
### Conversation Memory
Memory controls how your agent retains conversation history.
- **Session**: Conversation history resets when the conversation ends. Best for stateless interactions.
- **Persistent**: Conversation history is maintained across sessions. The agent remembers previous interactions, which is useful for ongoing relationships with users or long-running tasks.
#### How conversations work under the hood
A conversation is a single thread of messages between a user and an agent on one channel (the dashboard, a Slack channel/thread, a Telegram chat, a WhatsApp number, an API session, etc.). Each turn carries the conversation forward, but the agent never sees the entire raw history at once. Instead, every turn is built from three layers:
1. **System context**: the agent's prompt, tool list, and AI Context content. This is the same on every turn and is cached so subsequent turns only pay for it once.
2. **Recent messages (verbatim)**: the most recent messages in the conversation are passed in word-for-word.
- **Solo agents**: last **30 messages** are kept in full.
- **Team agents** (those with connected_agents that can delegate via `message_agent`): last **15 messages** are kept in full. The smaller window leaves room for cross-agent context blocks without blowing the prompt budget.
3. **Compressed summary of older messages**: anything beyond the recent-message window is summarized into a single `[CONVERSATION SUMMARY - N earlier messages condensed]` block by Claude Haiku. The summary captures key decisions, tool calls and their outcomes, - "Every Monday, review all draft blog posts and suggest improvements"
- "Every hour, check for new support tickets and categorize them by priority"
## AI Context
AI Context gives your agent knowledge beyond its base prompt. When configured, the selected content is included in every conversation, allowing the agent to reference your actual data when responding.
You can include:
- **Object Types**: Specific content types and their schemas
- **Objects**: Individual content items and their field values
- **Media**: Media library items
- **Links**: URLs for web crawling and progressive discovery. The agent fetches and indexes linked pages to inform its responses.
- **Brand Guidelines**: Include your project's brand guidelines so the agent maintains a consistent voice and style across all generated content.
- **Reference Screenshots**: Screenshot URLs that give the agent visual reference for design-aware tasks.
- **MCP Servers**: Connect external [Model Context Protocol](https://modelcontextprotocol.io) servers to extend the agent's tool set with custom integrations.
This is configured through the AI Context modal when creating or editing an agent. Context helps agents give accurate, content-aware responses without users needing to describe the data in every message.
## Setting up Slack
1. Go to your **Bucket Settings > Integrations**
2. Click **Connect Slack** to start the OAuth flow
3. Authorize the Cosmic app in your Slack workspace
4. Once connected, create or edit a Team Agent
5. Toggle the **Slack** channel and select a channel from the dropdown
6. Optionally enable **"Only respond when @mentioned"** for busy channels
The agent will now respond to messages in the selected Slack channel. It sees up to 50 recent messages for context and has full thread awareness.
## Setting up Telegram
1. Create a Telegram bot via [BotFather](https://t.me/BotFather) and copy the bot token
2. Go to your **Bucket Settings > Integrations**
3. Paste the bot token and click **Connect**
4. Create a Team Agent and toggle the **Telegram** channel
5. Save the agent, then edit it to click **Generate Connect Code**
6. In your Telegram chat with the bot, send `/connect ` to link the agent
The agent will now respond to messages in that Telegram chat. Connect codes expire after 10 minutes.
## Setting up WhatsApp
Cosmic supports two WhatsApp modes:
**Option 1: Shared Number (Quick Start)**
Use Cosmic's hosted WhatsApp Business number. No Meta account required.
1. Create or edit a Team Agent
2. Toggle the **WhatsApp** channel
3. Save the agent, then edit it and click **Generate Connect Code**
4. Click **Open WhatsApp** to open a pre-filled message with the activation code
5. Send the message from your WhatsApp to pair your phone number with the agent
The agent will now respond to messages from that phone number. Connect codes expire after 10 minutes.
**Option 2: Bring Your Own Number (BYON)**
Connect your own WhatsApp Business number for full control and branding.
1. Create a WhatsApp Business App in the [Meta Developer Dashboard](https://developers.facebook.com/apps/)
2. Generate a System User access token with `whatsapp_business_messaging` permission
3. Go to your **Bucket Settings > Integrations**
4. Under WhatsApp, select **Bring Your Own Number** and enter your access token and phone number ID
5. Configure the webhook URL in your Meta App to point to the URL shown in Integrations
6. Create a Team Agent, toggle **WhatsApp**, and generate a connect code
With BYON, messages are sent from your own branded number and the integration is fully isolated to your project.
## Conversation commands
Team Agents support a small set of conversation commands in the Cosmic dashboard chat as well as on Slack, Telegram, and WhatsApp. Commands are nearly free: they are handled locally and never hit the agent's main model. `/reset` makes one short call to a small summarization model (Claude Haiku) to produce a handoff summary; the other commands don't call any model.
| Command | Aliases | What it does |
|---|---|---|
| `/reset` | `/new`, `/clear` | Ends the current conversation and starts a fresh one. A short handoff summary is generated from the closing conversation and carried into the next session as preloaded context, so the agent remembers what you were working on without paying for the full transcript. |
| `/reset --hard` | `/reset --wipe` | Same as `/reset`, but skips the handoff summary entirely. The next message starts with no memory of the previous session. Use this when you want a true clean slate. |
| `/tokens` | `/stats` | Shows the message count and token usage (input, output, total) for the current conversation. |
| `/help` | `/commands` | Lists the available commands. |
**Parser rules:**
- The entire message must be exactly the command (case-insensitive). `/reset` works; `/reset please` is treated as a normal message and passed to the agent.
- On Slack, commands work whether the bot is `@mentioned` or not; the mention is stripped before parsing.
- Commands are scoped to the current conversation. In the dashboard, that's the conversation you have open; on Slack, the channel or thread; on Telegram, the chat; on WhatsApp, the sender's phone number.
**When to use `/reset`:**
- The conversation has drifted and you want the agent to start fresh while keeping the high-level context.
- Token usage (visible via `/tokens`) is getting high and you want to reduce cost on the next turn without losing what you were working on.
- You are about to switch topics. Use `--hard` if you don't want any prior context bleeding in.
In the dashboard, after a soft `/reset` the chat pivots to the new conversation immediately: the message count and token counter reset to zero, and the `/reset` exchange (your command and the handoff summary) is persisted to the new session so it stays visible after a page refresh.
## Sharing conversations
Each conversation has its own shareable URL. When you switch between conversations in the rail (or start a new one), the dashboard reflects the active conversation in the address bar as `?conversation=`, for example:
```
https://app.cosmicjs.com/projects/PROJECT_ID/agents/AGENT_ID?conversation=CONVERSATION_ID
```
Copy that URL to share a direct link to the conversation with anyone who has access to the project. Refreshing the page or opening the link in a new tab loads the same conversation rather than the most recent one. Use `/reset` (or click "New chat") to switch to a fresh conversation and update the URL.
## Agent Messaging API Reference
### Send a message
```
POST /v3/ai/agents/:agentId/messages
```
**Authentication**: [Personal Access Token](/docs/dashboard/account#api-tokens) or session JWT via `Authorization: Bearer` header.
**Request body**:
| Field | Type | Required | Description |
|---|---|---|---|
| `message` | string | Yes | The message text |
| `conversation_id` | string | No | Continue an existing conversation |
| `channel_metadata` | object | No | Additional context passed to the agent |
| `model` | string | No | Override the agent's default AI model |
| `context` | object | No | Extra context for this message |
| `stream` | boolean | No | Set to `true` to receive a streaming SSE response instead of JSON |
**Example**:
```bash
curl -X POST https://dapi.cosmicjs.com/v3/ai/agents/AGENT_ID/messages \
-H "Authorization: Bearer cos_YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"message": "Summarize our latest blog posts"}'
```
### Streaming
Pass `stream: true` in the request body to receive a streaming response via [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) (`Content-Type: text/event-stream`). Each event is a `data:` line containing JSON.
**Example**:
```bash
curl -N -X POST https://dapi.cosmicjs.com/v3/ai/agents/AGENT_ID/messages \
-H "Authorization: Bearer cos_YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"message": "Summarize our latest blog posts", "stream": true}'
```
**Event types**:
| Event type | Description |
|---|---|
| `info` | Sent immediately with `conversation_id` and `model` |
| `text_delta` | Incremental text chunk with `text` and accumulated `fullText` |
| `tool_progress` | Status label while the agent executes a tool |
| `done` | Final event with `conversation_id`, complete `message`, `tokens_used`, and `model` |
| `awaiting_approval` | Agent is waiting for approval, includes `pending_approval` details |
| `error` | An error occurred, includes `message` |
**Example event stream**:
```
data: {"type":"info","conversation_id":"abc123","model":"claude-opus-4-8"}
data: {"type":"text_delta","text":"Here","fullText":"Here"}
data: {"type":"text_delta","text":" are","fullText":"Here are"}
data: {"type":"tool_progress","label":"Fetching content..."}
data: {"type":"text_delta","text":"The latest","fullText":"The latest"}
data: {"type":"done","conversation_id":"abc123","message":"The latest posts cover...","tokens_used":1234,"model":"claude-opus-4-8"}
```
### Inbound webhook
```
POST /v3/ai/agents/:agentId/webhook
```
**Authentication**: Webhook secret (no Bearer token required). See [Inbound Webhook](#channels) for authentication methods.
**Request body**:
| Field | Type | Required | Description |
|---|---|---|---|
| `message` | string | Yes | The message text |
| `conversation_id` | string | No | Continue an existing conversation |
| `metadata` | object | No | Additional context passed to the agent |
### List conversations
```
GET /v3/ai/agents/:agentId/conversations
```
**Authentication**: Personal Access Token or session JWT.
### Get conversation history
```
GET /v3/ai/agents/:agentId/conversations/:conversationId
```
**Authentication**: Personal Access Token or session JWT.
## Key Features
- **Parallel Execution**: Run multiple agents simultaneously (limits based on your plan)
- **Branch Isolation**: Code agents work on separate Git branches to prevent conflicts
- **Progress Tracking**: Monitor commits, files changed, and real-time status updates
- **Email Notifications**: Receive updates when agents complete their work
- **Pull Request Management**: Agents can create PRs for code review before merging
- **Progressive Discovery**: Content agents can crawl web content to inform their work
## Plan Limits
**Plan-Based Limits** (varies by plan):
- **Free Plan**: 2 agents at a time
- **Paid Plans**: More agents based on your plan (check your plan details)
## Agent Limits by Plan
Agent, automation, and workflow limits are tracked in three separate pools and apply at the project level (for standalone projects) or workspace level (for workspace projects). Only `active` entities count toward each cap, so drafts, paused, archived, or deleted items free a slot. Workflow steps do not consume team agent or automation slots.
| Plan | Team agents | Automations | Workflows |
|---|---|---|---|
| Free | 1 | 2 (manual only) | 1 |
| Builder | 3 | 5 (with scheduling) | 3 |
| Team | 10 | 25 (with scheduling) | 10 |
| Business | 25 | 100 (with scheduling) | 50 |
| Small Workspace | 25 | 100 (with scheduling) | 50 |
| Large Workspace | 75 | 300 (with scheduling) | 150 |
| Enterprise | Custom | Custom | Custom |
- **Team Agents**: Persistent AI agents connected to channels like Slack, WhatsApp, or Telegram.
- **Automations**: Standalone agents (content, code, or computer use) that run on demand, on a schedule, or on content events.
- **Workflows**: Multi-step orchestrations that chain agents and logic.
**Note**: Scheduled execution is available through [Workflows](/docs/dashboard/ai/workflows) on paid plans.
## Progressive Discovery
Content Agents can use Progressive Discovery to crawl and analyze web content before generating or updating CMS content. This feature allows agents to:
- Research current trends and topics from specified websites
- Gather real-world examples and data
- Reference actual sources with accurate URLs
- Create content informed by the latest information
To use Progressive Discovery, enable it when creating a content agent and specify the URLs or topics you want the agent to explore.
---
# Workflows
AI Workflows allow you to chain multiple [Agents](/docs/dashboard/ai/agents) together to complete complex operations that previously required entire teams. Define a workflow once, and run it on-demand or on a schedule.
### What Are Workflows?
Workflows orchestrate multiple AI agents (Content, Code, Computer Use, and Team Agents) to execute complex, multi-step operations autonomously. Each step in a workflow passes context to the next: content feeds into code, code deploys, Computer Use tests and records demos, and Team Agents run with their own tools (including API requests).
### How Workflows Work
1. **Define Your Workflow**: Choose a template or build custom. Chain Content, Code, Computer Use, and Team Agents in any sequence. Set triggers: manual, scheduled, or event-driven.
2. **Execute Automatically**: Agents work sequentially or in parallel. Each step passes context to the next, maintaining continuity throughout the workflow.
3. **Monitor in Real-Time**: Watch progress live with step-by-step updates. See token usage, costs, and duration. Pause for approval gates when human review is needed.
4. **Review & Iterate**: Get complete execution summaries. View all created content, code changes, and recordings. Clone successful workflows for future projects.
5. **Rerun Anytime**: Run workflows on-demand or schedule them to run automatically. Your automation runs 24/7 without intervention.
### Workflow Use Cases
#### Full-Stack Product Launch
**Time: 20 minutes vs 2-3 weeks**
Content Agent creates your product catalog, Code Agent builds the storefront, Computer Use Agent tests and records a demo video. Complete e-commerce site, deployed.
**Workflow steps:** Content Generation → Code Development → Deploy & Test
#### Automated Content Optimization
**Schedule: Runs every Monday at 2 AM**
Automatically analyze 500+ articles for outdated content, validate links, capture fresh screenshots, and update flagged articles. Always-fresh content, zero manual work.
**Workflow steps:** Analyze Content → Validate Links → Auto-Update
#### Multi-Market Launch
**Time: 90 minutes vs 16 weeks**
Launch in 12+ markets simultaneously. Localized content, market-specific websites, compliance validation, and demo videos—all running in parallel.
**Workflow steps:** Localize Content → Deploy Sites → Validate Compliance
#### Auto-Documentation
**Trigger: On every deploy**
Code deploys to production, agents analyze changes, test new features, capture demo videos, write documentation, and create sales materials. Docs ship with features.
**Workflow steps:** Analyze Code → Test Features → Generate Docs
### Creating a Workflow
1. Open your project and click **AI Studio** in the project sidebar, then choose **Workflows**
2. Click **"Create Workflow"**
3. Add steps by selecting agent types (Content, Code, Computer Use, or Team Agent)
4. Configure each step with specific instructions
5. Set execution order (sequential or parallel)
6. (Optional) Add approval gates for human review
7. (Optional) Set a schedule or trigger for automatic execution
### Team Agent Steps
A **Team Agent** step runs one of your existing team agents as a workflow step. Instead of configuring a one-off agent inline, you pick a team agent from a dropdown, and the step runs that agent with its own saved prompt, model, and capabilities.
This is the way to give a workflow step access to the full team-agent toolset, including **API requests** (`api_request`), notifications, and any pre-configured API endpoints. Regular Content, Code, and Computer Use steps run with a limited toolset, so when you need a step to call an external API or use a team agent's tools, use a Team Agent step.
**How it works:**
- Select an active team agent for the step. The step stores a live reference to that agent (its `agent_id`), so changes you make to the agent later apply to the workflow automatically.
- Add optional **Instructions for this step**. If provided, they are passed to the agent as the run prompt; otherwise the agent uses its own saved prompt.
- The previous step's output is passed along as context, and the agent's reply becomes this step's output for the next step.
- Each run uses a fresh conversation, so workflow runs do not pollute the agent's chat history. Open the step in the execution detail view to see the full conversation.
**Notes:**
- Team Agent steps do not support interactive approvals. If the agent requires approval to act, turn that off on the agent or add a separate Approval Gate step.
- A team agent referenced by a workflow step still counts once against your team-agent limit; the step itself does not consume an additional automation slot.
### Workflow Features
- **Sequential or Parallel Execution**: Run steps one after another or simultaneously
- **Context Passing**: Each step receives output from previous steps
- **Approval Gates**: Pause workflow for human review when needed
- **Scheduling**: Run workflows on a schedule (hourly, daily, weekly, monthly)
- **Event Triggers**: Automatically trigger workflows on specific events
- **Real-Time Monitoring**: Watch progress with live updates
- **Execution History**: Review past runs with complete logs and outputs
- **Templates**: Start with pre-built workflow templates for common use cases
### Event-Triggered Workflows
Workflows can be configured to run automatically when content events occur, enabling powerful automation scenarios.
**Available Events:**
- **Object Created**: Run workflow when new content is added
- **Object Edited**: Run workflow when content is modified
- **Object Deleted**: Run workflow when content is removed
- **Object Published**: Run workflow when content goes live
- **Object Unpublished**: Run workflow when content is taken offline
**Event Context Data:**
When an event triggers your workflow, the following data is automatically included in the prompt context for all workflow steps:
- **Event Type**: The action that triggered the workflow
- **Object Type**: The content type that was affected
- **Object ID**: The unique identifier of the object
- **Object Data**: Title, slug, status, locale, and all metadata fields
**Using Event Data for Conditional Logic:**
Each step in your workflow can reference the event data to make decisions:
```
Step 1 (Content Agent):
"If the triggered object's status is 'draft', generate SEO metadata.
If the object is 'published', create social media posts instead."
Step 2 (Code Agent):
"If the object type is 'products' and the price field changed,
update the pricing display component."
```
**Example Event-Triggered Workflows:**
**Auto-SEO on Publish:**
```
Trigger: Object Published (blog-posts)
Step 1: Generate meta description and keywords from content
Step 2: Create Open Graph image using AI image generation
Step 3: Update object with SEO metadata
```
**Content Localization Pipeline:**
```
Trigger: Object Created (articles)
Step 1: If locale is 'en-US', translate to Spanish, French, German
Step 2: Create localized versions as new objects
Step 3: Send notification with translation summary
```
**Product Update Automation:**
```
Trigger: Object Edited (products)
Step 1: If price changed, update all related promotional content
Step 2: Regenerate product comparison charts
Step 3: Notify sales team via email
```
### Workflow Examples
**Research-to-Publication Pipeline:**
```
Step 1 (Content Agent): Research topic from specified sources
Step 2 (Content Agent): Write article draft with citations
Step 3 (Code Agent): Create landing page for article
Step 4 (Computer Use Agent): Record demo video and screenshots
Step 5 (Content Agent): Publish with all media assets
```
**Code Review and Documentation:**
```
Step 1 (Code Agent): Implement feature from requirements
Step 2 (Code Agent): Write unit tests
Step 3 (Computer Use Agent): Test in browser and record demo
Step 4 (Content Agent): Generate documentation from code changes
Step 5 (Code Agent): Open PR with docs and demo video
```
### Best Practices
- **Start Simple**: Begin with 2-3 step workflows and add complexity as needed
- **Use Approval Gates**: Add human review steps for critical operations
- **Test First**: Run workflows manually before scheduling
- **Monitor Costs**: Watch token usage across workflow steps
- **Clone Successful Workflows**: Reuse working workflows as templates for new projects
## Execution Retention
Agent and workflow executions are automatically cleaned up after a retention period to manage storage and keep your dashboard performant.
### Retention Policy
- **Retention Period**: 90 days
- **Affected Executions**: Completed, failed, and cancelled executions
- **Protected Executions**: Running and active executions are never automatically deleted
### What Gets Deleted
When an execution exceeds the retention period, the following data is removed:
- Execution logs and message history
- Step-by-step results and outputs
- Token usage records for that execution
- Associated metadata (commits, file changes for code agents)
### What's Preserved
- **Agent and Workflow configurations** are never deleted by retention policies
- **Running executions** remain until they complete
- **Content created by agents** (CMS objects, media) persists independently
- **Code changes** committed to your repository remain in Git history
- **Pull requests** created by code agents remain in GitHub
### Best Practices
- Export important execution logs before the 90-day retention period if you need long-term records
- Use the execution detail view to review results while they're available
- Agent configurations store your prompts and settings permanently—only execution history expires
---
# Application Workflows
Application workflows in Cosmic provide a complete solution for managing your application lifecycle, from GitHub repository integration to production deployment and domain management.
## GitHub Repository Integration
Connect existing GitHub repositories or create new ones with full workflow support and deployment preview capabilities.
**Repository management:**
- Connect private and public GitHub repositories
- Access repositories from all GitHub organizations
- Branch detection and management
- Protected branch support with pull request workflows
## Deployment Pipeline
Applications deploy through an integrated pipeline with enterprise-level capabilities.
**Deployment capabilities:**
- Vercel integration with automatic deployments
- Preview URLs for every deployment
- Environment variable management across deployment targets
- Real-time deployment logs and monitoring
- Custom domain assignment and management
- Pull request preview deployments
## Environment Configuration
Manage application configuration securely across all deployment environments.
**Environment management:**
- Add, edit, and remove environment variables
- Target-specific configuration for production, preview, and development
- Encrypted storage for sensitive information
- Bulk operations for efficient management
## Domain Management
Complete deployment workflow includes integrated domain services.
**Domain capabilities:**
- Domain purchase directly from the platform
- Automatic DNS configuration
- SSL certificate provisioning
- Custom domain assignment to deployments
## Getting started
[Log in](https://app.cosmicjs.com/login) to your Cosmic account and start using application workflows today.
---
# Cosmic Chrome Extension
The [Cosmic Chrome Extension](https://chromewebstore.google.com/detail/cosmic-chrome-extension/ooihoppnbephpmmpiadjmpeicihmjong) is a tool that allows you to easily access your Cosmic content from your Cosmic powered website.
## How it works
This extension automatically highlights areas on the page that can be edited in the Cosmic CMS, and will provide a link directly to the Cosmic dashboard for easy editing access.
## How to install
1. Go to the [Cosmic Chrome Extension on the Chrome Web Store](https://chromewebstore.google.com/detail/cosmic-chrome-extension/ooihoppnbephpmmpiadjmpeicihmjong)
2. Click "Add to Chrome"
3. Click "Add extension"
4. After installing the Cosmic Chrome Extension, you will then need to configure your Bucket slug. Click on the Cosmic icon located in the top right of your Chrome browser. Set your Bucket slug (this can be found in Your Project > API access). Then set edit mode to On.
## Demo
After installing the extension, go to the [Cosmic Podcast Network](https://cosmic-podcast-network.vercel.app) and click the Cosmic icon in the top right of your browser to open the Cosmic Chrome Extension.
## How to use
1. **Codebase updates**
In your website codebase, around any element that can be edited in Cosmic, set an attribute for `data-cosmic-object="your-cosmic-object-id"`. You can find the Cosmic Object ID in the API response or in the Cosmic dashboard. See the [Objects section in the docs](/docs/api/objects) section for more info.
2. **Install and configure**
After installing the Cosmic Chrome Extension, you will then need to configure your Bucket slug. Click on the Cosmic icon located in the top right of your Chrome browser. Set your Bucket slug (this can be found in Your Project > API access). Then set edit mode to On.
3. **Testing**
Now you should see any element with a Cosmic Object ID lit up with a Cosmic blue border with a link that takes you directly to the area in the Cosmic dashboard to update the content.
---
# API reference
# API Reference
We offer a powerful REST API to interact with your Cosmic content. We recommend using one of the available SDKs which provide an enhanced development experience.
## API base URL
The base URL for all requests is noted below.
```bash {{ language: 'js' }}
http://api.cosmicjs.com
```
## API status
You can check the API status at the following endpoint. You can also subscribe to status updates on the [Cosmic status page](http://cosmicstatus.com).
```bash {{ language: 'js' }}
http://api.cosmicjs.com/v3/status
```
{/* */}
## Install the JavaScript SDK
The following examples include methods using the [Cosmic JavaScript SDK](https://www.npmjs.com/package/@cosmicjs/sdk). To run the examples, first install the NPM module using one of the following commands. Make sure you have [Node.js](https://nodejs.org/en) installed on your machine (recomended version: `v18.*`).
```bash {{ language: 'js' }}
yarn add @cosmicjs/sdk
# OR
pnpm add @cosmicjs/sdk
# OR
npm install @cosmicjs/sdk
# OR
bun add @cosmicjs/sdk
```
## Install the Swift SDK
In certain cases, there are also methods that use the [Cosmic Swift SDK](https://github.com/cosmicjs/cosmic-sdk-swift). To run the examples, first install the Swift package using Swift Package Manager.
```bash {{ language: 'swift' }}
.package(url: "https://github.com/cosmicjs/cosmic-sdk-swift.git", from: "1.0.0")
```
---
# Authentication
Learn how to authenticate your requests to the Cosmic API.
## Get your API keys
Cosmic uses API keys to authenticate requests. For the following examples, you will need your:
1. Bucket slug
2. Bucket read key
3. Bucket write key
You can get your API access keys by going to Bucket Settings > API Access in [the Cosmic dashboard](https://app.cosmicjs.com/login).
## Use your API keys
Use the methods below to use your Cosmic API keys.
Before you can make requests to the Cosmic API, you will need to grab your
Bucket slug and API keys from your dashboard. Find them in [Bucket Settings
» API Access](https://app.cosmicjs.com/login).
```js
// Import
import { createBucketClient } from '@cosmicjs/sdk';
// Authenticate
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY',
});
// Fetch content
await cosmic.objects
.find({
type: 'posts',
})
.limit(1);
// Write content
await cosmic.objects.insertOne({
title: 'Blog Post Title',
type: 'posts',
metadata: {
content: 'Here is the blog post content...',
seo_description: 'This is the blog post SEO description.',
featured_post: true,
},
});
```
```bash {{ title: 'cURL' }}
# Fetch content
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects \
-d read_key=${BUCKET_READ_KEY} \
--data-urlencode query='{"type": "posts"}' \
-d limit=1 \
-G
# Write content
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects \
-d '{"title":"Blog Post Title","type":"posts","metadata":{"seo_description":"This is the blog post SEO description.","featured_post": true}}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```swift {{ title: 'Swift' }}
// Import
import CosmicSDK
// Authenticate
let cosmic = CosmicSDKSwift(
.createBucketClient(
bucketSlug: BUCKET,
readKey: READ_KEY,
writeKey: WRITE_KEY
)
)
// Fetch content
@State var posts: [Object] = []
cosmic.find(type: posts) { results in
switch results {
case .success(let result):
self.posts = result.objects
case .failure(let error):
print(error)
}
}
// Write content
@State private var post: Object?
cosmic.insertOne(
type: posts,
title: post.title
) { results in
switch results {
case .success(_):
print("Updated \(post.id)")
case .failure(let error):
print(error)
}
}
```
Never expose your Bucket write key in any client-side code.
## Personal Access Tokens
For dashboard-level API access (managing agents, workflows, account settings, etc.), use a Personal Access Token (PAT) instead of a session JWT. PATs are ideal for scripts, CI/CD pipelines, CLI tools, and MCP servers.
Create a token at [Account Settings > API Tokens](https://app.cosmicjs.com/account/api-tokens). Tokens use the `cos_` prefix and carry your full account permissions. Learn more in the [API Tokens documentation](/docs/dashboard/account#api-tokens).
Include your token in the Authorization header:
```bash
curl https://dapi.cosmicjs.com/v3/users/get \
-H "Authorization: Bearer cos_YOUR_TOKEN"
```
PATs are the recommended authentication method for the [Agent Messaging API](/docs/dashboard/ai/agents#agent-messaging-api-reference). For example, to send a message to a Communication agent:
```bash
curl -X POST https://dapi.cosmicjs.com/v3/ai/agents/AGENT_ID/messages \
-H "Authorization: Bearer cos_YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"message": "Hello, agent!"}'
```
Never expose your Personal Access Token in client-side code. PATs carry your full account permissions.
## Agent key
An **agent key** (`agk_` prefix) is a short-lived bearer token issued by [`POST /v3/agents/sign-up`](/docs/api/agents#sign-up). It is the auth mechanism used when an AI agent provisions a Cosmic project on behalf of a human, before the human has a Cosmic account of their own.
Agent keys have a very narrow scope: they authenticate only the agent-flow endpoints.
| Endpoint | Auth |
|---|---|
| `POST /v3/agents/verify` | `Authorization: Bearer agk_...` |
| `GET /v3/agents/status` | `Authorization: Bearer agk_...` |
For everything else (objects, media, AI generation), use the **bucket read key and write key** that are returned in the same sign-up response. Those work with the standard [bucket API](/docs/api/objects), the [JavaScript SDK](https://www.npmjs.com/package/@cosmicjs/sdk), and every other Cosmic interface:
```bash
# Use the agent_key to call the agent-flow endpoints
curl https://dapi.cosmicjs.com/v3/agents/status \
-H "Authorization: Bearer agk_..."
# Use the bucket write_key (returned by /v3/agents/sign-up) for content
curl -X POST https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects \
-H "Authorization: Bearer ${BUCKET_WRITE_KEY}" \
-H "Content-Type: application/json" \
-d '{"title":"First post","type":"posts"}'
```
The bucket starts in restricted "unclaimed" mode until the human verifies the OTP from the claim email. AI generation is blocked while unclaimed; create/read/update of up to 50 objects and 5 MB of media still works. See the full [Agents API reference](/docs/api/agents) for the lifecycle, limits, and error codes.
Treat agent keys like any other secret. They identify the agent and grant access to the bucket keys, the human's email, and the verify flow. Persist them per-agent; do not embed in shared client code.
---
# Agents
The Agents API lets an AI agent provision a brand new Cosmic project and bucket on behalf of a human, without the human needing a Cosmic account up-front. The bucket starts in a restricted "unclaimed" state, an OTP is emailed to the human, and the agent can hand the code back to lift the limits.
This is the underlying API used by the [Agent Signup](/docs/agent-skills#agent-signup) flow exposed in the CLI and the MCP `/v1/agent` scope.
### Base URL
```
https://dapi.cosmicjs.com
```
Unlike the bucket-scoped endpoints in the rest of this reference, the Agents endpoints live on the dashboard API (`dapi.cosmicjs.com`).
---
## Sign up
Provision a new project + bucket and trigger a claim email to `human_email`.
This endpoint does **not** require authentication. The request must be sent as JSON with `Content-Type: application/json`. Re-calling with the same `human_email` + `agent_id` is idempotent: it refreshes the OTP and returns the existing project rather than creating a new one.
### Required body
The human's email address. The 6-digit OTP and a claim URL are sent here. Must be a valid email and not already a human-owned Cosmic account (see [errors](#errors)).
Display name for the new Cosmic project. The bucket slug is derived from this.
Stable identifier for the calling agent (e.g. `cursor`, `claude-code`, your-internal-agent slug). Used for rate limiting and analytics. Plain string, 1-128 chars.
### Optional body
Free-form label for the surface the agent runs in (e.g. `desktop`, `cli`, `mcp`). Echoed back in `/v3/agents/status`.
### Response
Bearer token (prefix `agk_`) used to call [`/v3/agents/verify`](#verify) and [`/v3/agents/status`](#status). Persist this securely; it is the durable agent-flow credential and survives token rotation.
User-scoped JWT for the shadow user that owns the new project + bucket. Pass it as `Authorization: Bearer ` to call any standard [Dashboard API](/docs/api) endpoint (object types, webhooks, team, etc.) on the agent's project. Valid for **14 days** while unclaimed (matches the auto-delete window). Auto-revoked when the human claims the bucket (the shadow user's `status` flips to 0). For long-lived agents, hit [`/v3/agents/status`](#status) periodically to obtain a fresh token.
Always `unclaimed` on a fresh sign-up.
`{ id, name }` for the provisioned project.
`{ slug, read_key, write_key }`. Use these immediately with the standard [bucket API](/docs/api/objects) and [SDK](https://www.npmjs.com/package/@cosmicjs/sdk). The keys returned here are raw (not JWT-wrapped) and ready to drop into `createBucketClient`. Bucket keys are durable and survive claim.
URL the agent can hand the human as an alternative to the OTP. Visiting it on `app.cosmicjs.com` lets the human verify and take ownership in one step.
Restricted-mode quotas, see [Auth states & limits](#auth-states-and-limits).
Number of days until the project is hard-deleted if it has not been claimed. Currently `14`.
```bash {{ title: 'cURL' }}
curl -X POST https://dapi.cosmicjs.com/v3/agents/sign-up \
-H "Content-Type: application/json" \
-d '{
"human_email": "tony@example.com",
"project_name": "Recipe Blog",
"agent_id": "my-agent-platform"
}'
```
```js {{ title: 'JavaScript' }}
const res = await fetch('https://dapi.cosmicjs.com/v3/agents/sign-up', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
human_email: 'tony@example.com',
project_name: 'Recipe Blog',
agent_id: 'my-agent-platform',
}),
});
const { agent_key, bucket } = await res.json();
```
```json {{ title: '200 OK' }}
{
"message": "Agent signup created. OTP sent to human_email.",
"auth_type": "unclaimed",
"agent_key": "agk_...",
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"project": { "id": "...", "name": "Recipe Blog" },
"bucket": {
"slug": "recipe-blog-...",
"read_key": "...",
"write_key": "..."
},
"claim_url": "https://app.cosmicjs.com/claim?token=agk_...",
"limits": {
"ai_credits_remaining": 0,
"media_mb_total": 5,
"objects_max": 50
},
"auto_delete_after_days": 14
}
```
---
## Verify
Submit the 6-digit code from the claim email to lift restricted-mode limits.
Requires `Authorization: Bearer agk_...` from the sign-up response. The agent never sees the code itself; the human reads it from their email and pastes it back.
### Required body
The 6-digit numeric OTP from the claim email. The code expires; if expired, call [`/v3/agents/sign-up`](#sign-up) again with the same `human_email` + `agent_id` to issue a fresh one (idempotent).
### Response
`verified` on success.
`verified`.
A freshly issued user JWT, with a longer expiry now that the project is verified (`90d`). Replace any previously stored token with this one.
`null` once verified; the bucket is on standard free-tier limits.
```bash {{ title: 'cURL' }}
curl -X POST https://dapi.cosmicjs.com/v3/agents/verify \
-H "Authorization: Bearer agk_..." \
-H "Content-Type: application/json" \
-d '{ "code": "123456" }'
```
```js {{ title: 'JavaScript' }}
await fetch('https://dapi.cosmicjs.com/v3/agents/verify', {
method: 'POST',
headers: {
Authorization: `Bearer ${agent_key}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ code: '123456' }),
});
```
```json {{ title: '200 OK' }}
{
"message": "Verified. Restricted-mode limits lifted.",
"auth_type": "verified",
"claim_status": "verified",
"limits": null
}
```
---
## Status
Check the current claim state and remaining limits for the agent's project + bucket. Safe to poll while waiting for the human to verify.
Requires `Authorization: Bearer agk_...`. Also useful as a recovery path: if the agent lost the sign-up response (e.g. CLI re-login on a new machine), `/status` returns the bucket slug, read key, and write key.
### Response
`unclaimed` or `verified`.
`unclaimed`, `verified`, or `human_owned` (the human signed up at `app.cosmicjs.com` with the same email and absorbed the project).
`agent_unclaimed` while restricted, otherwise the project's normal plan id.
A freshly issued user JWT for the shadow user. Treat `/status` as the canonical refresh endpoint: call it periodically with the `agent_key` to rotate the token before it expires.
Restricted-mode limits while unclaimed, `null` once verified or claimed.
Days until hard-delete if unclaimed; `null` once claimed.
`{ id, name }`.
`{ slug, read_key, write_key }`. Keys are raw (not JWT-wrapped).
The email the agent signed up against.
Echoed back from sign-up.
```bash {{ title: 'cURL' }}
curl https://dapi.cosmicjs.com/v3/agents/status \
-H "Authorization: Bearer agk_..."
```
```json {{ title: '200 OK (unclaimed)' }}
{
"auth_type": "unclaimed",
"claim_status": "unclaimed",
"plan_id": "agent_unclaimed",
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"limits": {
"ai_credits_remaining": 0,
"media_mb_total": 5,
"objects_max": 50
},
"auto_delete_after_days": 14,
"project": { "id": "...", "name": "Recipe Blog" },
"bucket": {
"slug": "recipe-blog-...",
"read_key": "...",
"write_key": "..."
},
"human_email": "tony@example.com",
"agent_id": "my-agent-platform",
"client": "cli"
}
```
---
## Auth states and limits
An agent-created project moves through three states:
| State | What it means | What's allowed |
|---|---|---|
| `unclaimed` | Bucket created by agent, human has not verified yet | Create/read/update up to **50 objects**, up to **5 MB** total media. **AI generation is disabled.** |
| `verified` | Human passed the OTP back to the agent (or visited the claim URL) | Standard free-tier limits, including AI generation |
| `human_owned` | Human took ownership by signing up at `app.cosmicjs.com` with the same email | Standard free-tier limits, full dashboard access |
Calls that exceed restricted-mode quotas return `402` with `code: "agent_unclaimed_limit"` and the offending `action` (`ai_generate`, `object_create`, or `media_upload`). Use this signal to prompt the human to claim:
```json {{ title: '402 Payment Required' }}
{
"message": "AI generation is disabled on unclaimed agent buckets. Ask the human to claim this bucket to enable AI features.",
"code": "agent_unclaimed_limit",
"action": "ai_generate",
"limits": {
"ai_credits_remaining": 0,
"media_mb_total": 5,
"objects_max": 50
}
}
```
Unclaimed projects are hard-deleted after **14 days** if not claimed. Plan accordingly: prompt the human early, and persist the `agent_key` so a returning user can resume the claim flow.
---
## Errors
| Status | `code` | When |
|---|---|---|
| `400` | (none) | Missing/invalid body or expired/incorrect OTP on `/verify`. |
| `401` | (none) | Missing or invalid `Authorization: Bearer agk_...` on `/verify` or `/status`. |
| `402` | `agent_unclaimed_limit` | Caller exceeded restricted-mode quotas (returned by the bucket data plane, not by this API). |
| `409` | `user_already_exists` | `human_email` already belongs to a Cosmic user. Response includes a `claim_existing_url` pointing the human to `/login?email=...`. Do not retry with a different email; ask the human to log in and provision a bucket from the dashboard. |
| `429` | (none) | Rate limit. The `/sign-up` endpoint is capped per IP, and `agent_id` has a daily ceiling. Back off and retry. |
### Related
- [Agent Signup overview](/docs/agent-skills#agent-signup) - end-to-end flow, including CLI and MCP.
- [Authentication](/docs/api/authentication#agent-key) - where `agent_key` fits among other auth methods.
- [CLI: `cosmic agent-signup`](/docs/cli) - the same flow without writing fetch calls.
- [MCP server: agent scope](/docs/mcp-server#agent-scope) - the same flow exposed as MCP tools.
---
# Request limits
Learn about request limits to the Cosmic API.
### API rate limits
All Cosmic Buckets have the following rate limits:
- **Rate limit:** `100` requests per second
- **Burst limit:** `200` requests
These limits apply to non-cached API requests. Non-cached requests include any initial `GET` request and all `POST`, `PUT`, `PATCH`, and `DELETE` requests to the API. This does not apply to any files or images served via the Cosmic CDN or imgix CDN.
If you exceed these limits, the API will return a `429 Too Many Requests` response. The burst limit allows for short spikes in traffic while the rate limit ensures sustained request rates remain within acceptable bounds.
### Response time limits
Endpoints have a timeout limit of `30` seconds. If you find yourself hitting this limit, you can reduce your payload size with `limit` and `props` options. See [Objects API Reference](/docs/api/objects) for more info.
### Size limits
Except for the upload media endpoint, which allows up to `900MB` files to be uploaded, all Cosmic requests and responses have a size limit of `6MB`.
### Optimizations
All requests allow `gzip` ecoding. If connecting to the API directly, adding `Accept-Encoding: gzip` can dramatically reduce response time and size. This is added by default on all Cosmic open source clients.
---
# Errors
Learn how to handle errors with the Cosmic API.
## Status codes
The Cosmic API uses the following status codes:
| Status code | Meaning |
| ------------------ | -------------------------------------------------------------------- |
| 200 | OK - Everything worked as expected. |
| 400 | Bad Request - Your request is invalid. |
| 401 | Unauthorized - Your access key is incorrect. |
| 402 | Payment Required - Your Bucket needs to be upgraded to continue use. |
| 403 | Forbidden - You are not allowed to access this content. |
| 404 | Not Found - The requested resource doesn't exist. |
| 429 | Too Many Requests - Too many requests hit the API too quickly. |
| 500, 502, 503, 504 | Internal Server Error - Something went wrong on our end. |
## Error response model
Here is the error response model that you can expect:
The status code from the table above.
A verbose error message that will try to hint at any possible issues with
the request.
## Error example
Error messages will attempt to be as specific as possible with what went wrong. For example, if there was an invalid property in a request the following format can be expected:
```json
{
"status": 400,
"message": "Metafield validation: invalid 'value' for metafield with key: 'number' and type: 'number'"
}
```
---
# Object types
Learn about Object types; used to organize and model Objects in your Cosmic Bucket.
## The Object type model
The Object type model contains all the information about the Object type including content modeling using Metafields, localization, preview links, and more.
### Properties
Unique identifier for Object type.
Object type title.
Singular title of the Object type.
Object type slugs are unique per Bucket.
Single or multiple Objects in this type.
Valid Unicode emoji displayed on the Object type table.
Array of Metafields. See [Metafields](/docs/api/metafields).
Contains boolean property `slug_field` which controls
the display options for the `slug` field for Objects in the
type.
Add localization to the Object type. Default: `false`
Array of available locales in the Object type. See [available locale
codes](#localization).
Default locale when creating new Objects in this type. Objects will be
grouped by this locale in the Object type table in the dashboard.
```json
{
"id": "63bde47897d49d0008a270b3",
"title": "Bikes",
"slug": "bikes",
"singular": "Bike",
"emoji": "🏍️",
"created_at": "2023-01-10T22:19:36.128Z",
"modified_at": "2023-03-16T21:09:09.914Z",
"singleton": false,
"options": {
"slug_field": true
},
"metafields": [
{
"id": "c7c50911-3b38-4b22-a307-392eb9f84739",
"title": "Image",
"key": "image",
"type": "file",
"helptext": "",
"required": false,
"media_validation_type": "image"
},
{
"id": "1157a40b-9a1a-4d06-96e0-2338f01d366d",
"title": "Headline",
"key": "headline",
"type": "text",
"helptext": "",
"required": false
}
]
}
```
---
## Get Object types
This endpoint enables you to retrieve a list of your Object types in the Bucket.
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY'
})
await cosmic.objectTypes.find()
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/object-types \
-d read_key=${BUCKET_READ_KEY} \
-G
```
```json {{ title: 'Response' }}
{
"object_types": [
{
"id": "63bde47897d49d0008a270b3",
"title": "Bikes",
"slug": "bikes",
"singular": "Bike",
"emoji": "🏍️",
"created_at": "2023-01-10T22:19:36.128Z",
"modified_at": "2023-03-16T21:09:09.914Z",
"singleton": false,
"options": {
"slug_field": true
},
"metafields": [
{
"id": "c7c50911-3b38-4b22-a307-392eb9f84739",
"title": "Image",
"key": "image",
"type": "file",
"helptext": "",
"required": false,
"media_validation_type": "image"
},
{
"id": "1157a40b-9a1a-4d06-96e0-2338f01d366d",
"title": "Headline",
"key": "headline",
"type": "text",
"helptext": "",
"required": false
}
...
]
},
{
"id": "63bde4c297d49d0008a270b4",
"title": "Cars",
"slug": "cars",
"singular": "Car",
"emoji": "🚗",
"created_at": "2023-01-10T22:19:36.128Z",
"modified_at": "2023-03-16T21:09:09.914Z",
"singleton": false,
"options": {
"slug_field": true
},
"metafields": [
{
"id": "c7c50911-3b38-4b22-a307-392eb9f84739",
"title": "Image",
"key": "image",
"type": "file",
"helptext": "",
"required": false,
"media_validation_type": "image"
},
{
"id": "1157a40b-9a1a-4d06-96e0-2338f01d366d",
"title": "Headline",
"key": "headline",
"type": "text",
"helptext": "",
"required": false
}
...
]
}
]
}
```
---
## Get a single Object type
Get a single Object type by `slug`.
### Required parameters
The Object type slug.
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY'
})
await cosmic.objectTypes.findOne('object-type-slug')
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/object-types/:slug \
-d read_key=${BUCKET_READ_KEY} \
-G
```
```json {{ title: 'Response' }}
{
"object_type": {
"id": "63bde47897d49d0008a270b3",
"title": "Bikes",
"slug": "bikes",
"singular": "Bike",
"emoji": "🏍️",
"created_at": "2023-01-10T22:19:36.128Z",
"modified_at": "2023-03-16T21:09:09.914Z",
"singleton": false,
"options": {
"slug_field": true
},
"metafields": [
{
"id": "c7c50911-3b38-4b22-a307-392eb9f84739",
"title": "Image",
"key": "image",
"type": "file",
"helptext": "",
"required": false,
"media_validation_type": "image"
},
{
"id": "1157a40b-9a1a-4d06-96e0-2338f01d366d",
"title": "Headline",
"key": "headline",
"type": "text",
"helptext": "",
"required": false
}
...
]
}
}
```
---
## Create an Object type
This endpoint enables you to create an Object type in your Bucket.
The data request payload will need to be sent in JSON format with the `Content-Type: application/json` header set.
### Required parameters
Object type title.
### Optional parameters
Singular title of the Object type.
Object type slugs are unique per Bucket.
Default: `title` converted to slug.
Single or multiple Objects in this type.
Valid Unicode emoji displayed on the Object type table.
Array of Metafields. See [Metafields](/docs/api/metafields).
Contains boolean property `slug_field` which controls
the display options for the `slug` field for Objects in the
type.
Add localization to the Object type. Default: `false`
Array of available locales in the Object type. See [available locale
codes](#localization).
Default locale when creating new Objects in this type. Objects will be
grouped by this locale in the Object type table in the dashboard.
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.objectTypes.insertOne({
title: "Bikes",
slug: "bikes",
emoji: "🏍️",
metafields: [
{
"title": "Image",
"key": "image",
"type": "file",
"required": true,
"media_validation_type": "image"
},
{
"title": "Headline",
"key": "headline",
"type": "text",
"required": false
}
]
})
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/object-types \
-d '{"title":"Motorcycles","slug":"motorcycles"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```json {{ title: 'Response' }}
{
"object_type": {
"id": "63bde47897d49d0008a270b3",
"title": "Bikes",
"slug": "bikes",
"singular": "Bike",
"emoji": "🏍️",
"created_at": "2023-01-10T22:19:36.128Z",
"modified_at": "2023-03-16T21:09:09.914Z",
"singleton": false,
"options": {
"slug_field": true
},
"metafields": [
{
"id": "c7c50911-3b38-4b22-a307-392eb9f84739",
"title": "Image",
"key": "image",
"type": "file",
"helptext": "",
"required": false,
"media_validation_type": "image"
},
{
"id": "1157a40b-9a1a-4d06-96e0-2338f01d366d",
"title": "Headline",
"key": "headline",
"type": "text",
"helptext": "",
"required": false
}
...
]
}
}
```
---
## Update an Object type
This endpoint enables you to update an Object type.
If using the NPM module, use the `$set` method to update the Object type properties specificed.
### Optional parameters
Singular title of the Object type.
Object type slugs are unique per Bucket.
Default: `title` converted to slug.
Single or multiple Objects in this type.
Valid Unicode emoji displayed on the Object type table.
Array of Metafields. See [Metafields](/docs/api/metafields).
Contains boolean property `slug_field` which controls
the display options for the `slug` field for Objects in the
type.
Add localization to the Object type. Default: `false`
Array of available locales in the Object type. See [available locale
codes](#localization).
Default locale when creating new Objects in this type. Objects will be
grouped by this locale in the Object type table in the dashboard.
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.objectTypes.updateOne('object-type-slug', {
title: 'Motorcycles',
slug: 'motorcycles',
singular: 'Motorcycle'
})
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/object-types/bikes \
-d '{"title":"Motorcycles","slug":"motorcycles","singular":"Motorcycle"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}" \
-X PATCH
```
```json {{ title: 'Response' }}
{
"object_type": {
"id": "63bde47897d49d0008a270b3",
"title": "Motorcycles",
"slug": "motorcycles",
"singular": "Motorcycle",
"emoji": "🏍️",
"created_at": "2023-01-10T22:19:36.128Z",
"modified_at": "2023-03-16T21:09:09.914Z",
"singleton": false,
"options": {
"slug_field": true
},
"metafields": [
{
"id": "c7c50911-3b38-4b22-a307-392eb9f84739",
"title": "Image",
"key": "image",
"type": "file",
"helptext": "",
"required": false,
},
{
"id": "1157a40b-9a1a-4d06-96e0-2338f01d366d",
"title": "Headline",
"key": "headline",
"type": "text",
"helptext": "",
"required": false
}
...
]
}
}
```
---
## Delete an Object type
This endpoint enables you to delete an Object type and all Objects in this type from your Bucket.
### Required parameters
Object type slug.
### Optional parameters
Triggers corresponding Object action webhook (See Webhooks).
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.objectTypes.deleteOne("object-type-slug")
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/object-types/:slug \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}" \
-X DELETE
```
```json {{ title: 'Response' }}
{
"message": "Object type with slug ':slug' deleted successfully from bucket."
}
```
## Metafields
Learn about adding Metafields to Object types in the [Metafields page](/docs/api/metafields).
---
# Objects
Learn about Objects; the basic building blocks of content in your Cosmic Bucket.
Use the following methods to create, read, update, and delete Objects.
## The Object model
The Object model contains all the information about Objects.
### Properties
Unique identifier for Object.
Object type slug.
Object title.
Object slugs are unique per each Object type. Localized versions of Objects
are linked with the same slug. See [localization](/docs/api/localization).
Object status.
Options `published | draft`
HTML Content. (deprecatated in API v3, use Metafield instead)
Values of the Metafields created in the Object type.
The id of the user who created the Object.
Date the Object was created.
The id of the user who last modified the Object.
Date Object was last modified.
The id of the user assigned to the Object.
The id of the user who assigned the Object.
Date the Object was assigned.
Date Object was last published.
UNIX millisecond timestamp. Publish automatically at a later time.
UNIX millisecond timestamp. Unpublish automatically at a later time.
See [localization](/docs/api/localization) for locale options.
Media `name`. Media must be available in Bucket. See [media](/docs/api/media).
```json
{
"id": "63dc57ca24090e0008683d42",
"slug": "add-a-headless-cms-to-astro-in-3-easy-steps",
"title": "Add a headless CMS to Astro in 3 easy steps",
"bucket": "63dc24a4d71e244b63c88fca",
"created_at": "2023-02-03T00:39:38.35Z",
"modified_at": "2023-03-23T12:08:13.547Z",
"status": "published",
"thumbnail": "https://imgix.cosmicjs.com/1c8531f0-97fb-11ed-81d8-8f0123e10511-A-photo-of-Michelangelos-sculpture-of-David-wearing-headphones-djing.webp",
"published_at": "2023-03-23T12:08:13.547Z",
"modified_by": "629e6cdda6f4f100091ae2e0",
"publish_at": null,
"type": "blog-posts",
"metadata": {
"content": "Astro is a lightweight web framework capable of shipping highly performant websites with minimal (or non-existent) JavaScript bundles. In this guide...",
"image": {
"url": "https://cdn.cosmicjs.com/02670ac0-38ef-11ed-adfd-ddb1795c6ac6-add-a-headless-cms-to-astro-in-3-easy-steps.png",
"imgix_url": "https://imgix.cosmicjs.com/02670ac0-38ef-11ed-adfd-ddb1795c6ac6-add-a-headless-cms-to-astro-in-3-easy-steps.png"
},
"published_date": "2022-09-20",
"author": {
"title": "Bill Brasky"
}
}
}
```
---
## Get Objects
This endpoint enables you to retrieve a list of your Objects.
### Optional parameters
A JSON object to perform Object search and filtering. See [queries section](/docs/api/queries) for more detail. Must be URL encoded for REST requests.
### Optional methods
Declare which properties to return in comma-separated string (or array if using the NPM module). Remove to see all Object properties. Can include nested metadata. Example: `id,title,metadata.author.metadata.image.url`.
If you are using the Cosmic JavaScript SDK, you can format the `props` string in a graph syntax such as:
```graphql
{
id
slug
title
metadata {
content
description
parent {
title
}
}
}
```
Set to `any` for latest version of draft or published Object.
Options `published | draft | any`
Default `published`
Order of Objects returned.
Options `created_at, -created_at, modified_at, -modified_at, random, order, metadata.$key, -metadata.$key`
Use `-` for descending order.
Default `-order` (order in dashboard, top down)
Sort by Metadata
Sort by metadata using `metadata.$key` and `-metadata.$key`. For example, setting `sort` to `metadata.price` will return Objects from low to high price. To enable sortable Metafields, go to Object type > Settings in the dashboard. Metafields that can be sortable include Text, Number, and Date Metafields. You are currently limited to 2 sortable Metafields per Object type.
Limit the number of Objects returned.
Default `1000`
Used for pagination. The number of Objects to skip.
Default `0`
The depth of Object references using Object Relationship Metafields. Circular reference is prohibited.
Default `0`
Used for pagination. Get Objects after specified Object `id` (can only use one of `skip` or `after`).
Set to `false` for real-time updates. Increases latency of endpoint.
Default `true`
Set to `true` for reader-friendly formated JSON response.
Default `false`
Used to get more media data. Contains a `media` object with a `props` property. This is handy for getting media size, dimensions, alt text, metadata, etc. See the [Media model](/docs/api/media) for more available properties. Available only on the Cosmic JavaScript SDK. For example:
```js
await cosmic.objects.find({
type: 'object-type-slug'
}).props(props)
.options({
media: {
props: 'alt_text,width,height'
}
})
```
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY'
})
const props = `{
id
slug
title
metadata {
content
description
parent {
title
}
}
}`
await cosmic.objects.find({
type: 'object-type-slug'
}).props(props).limit(1)
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects \
-d read_key=${BUCKET_READ_KEY} \
--data-urlencode query='{"type":"object-type-slug"}' \
-d props=id,slug,title,metadata.content,metadata.description,metadata.parent.title \
-d limit=1 \
-G
```
```swift {{ title: 'Swift' }}
let cosmic = CosmicSDKSwift(
.createBucketClient(
bucketSlug: "BUCKET_SLUG",
readKey: "READ_KEY",
writeKey: "WRITE_KEY"
)
)
@State var objects: [Object] = []
cosmic.find(
type: "object-type-slug",
props: "id,
slug,
title,
metadata.content,
metadata.description,
metadata.parent.title",
limit: "1",
sort: .random,
status: .any
) { results in
switch results {
case .success(let result):
self.objects = result.objects
case .failure(let error):
print(error)
}
}
```
```json {{ title: 'Response' }}
{
"objects": [
{
"id": "5f7357967286d7773adc551e",
"slug": "learning",
"title": "Learning",
"metadata": {
"content": "Learning is fun!!
",
"description": "This is the example description",
"parent": {
"title": "Example Post"
}
}
}
],
"total": 6,
"limit": 1
}
```
---
## Get a single Object by slug
This endpoint enables you to get a single Object by `slug`. To get a single Object by `slug` indicate the `type` and `slug` in the `query` parameter.
With the Cosmic NPM module, you can use the `findOne` method to return an `object`. If using the REST API, it will return an `array`.
### Optional parameters
A JSON object to perform Object search and filtering. See [queries section](/docs/api/queries) for more detail. Must be URL encoded for REST requests.
### Optional methods
Declare which properties to return in comma-separated string (or array if using the NPM module). Remove to see all Object properties. Can include nested metadata. Example: `slug,title,metadata.content,metadata.image.imgix_url`.
If you are using the Cosmic JavaScript SDK, you can format the `props` string in a graph syntax such as:
```graphql
{
slug
title
metadata {
content
image {
imgix_url
}
}
}
```
Set to `any` for latest version of draft or published Object.
Options `published | draft | any`
Default `published`
The depth of Object references using Object Relationship Metafields. Circular reference is prohibited.
Default `0`
Set to `false` for real-time updates. Increases latency of endpoint.
Default `true`
Set to `true` for reader-friendly formated JSON response.
Default `false`
Used to get more media data. Contains a `media` object with a `props` property. This is handy for getting media size, dimensions, alt text, metadata, etc. See the Available only on the Cosmic JavaScript SDK. For example:
```js
await cosmic.objects.findOne({
type: 'object-type-slug',
slug: 'object-slug'
}).props(props)
.options({
media: {
props: 'alt_text,width,height'
}
})
```
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY'
})
const props = `{
slug
title
metadata {
content
image {
imgix_url
}
}
}`
await cosmic.objects.findOne({
type: 'object-type-slug',
slug: 'object-slug'
}).props(props)
.options({
media: {
props: 'alt_text,width,height'
}
})
```
`
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects \
-d read_key=${BUCKET_READ_KEY} \
--data-urlencode query='{"type":"object-type-slug","slug":"object-slug"}' \
-d props=slug,title,metadata.content,metadata.image.imgix_url \
-d limit=1 \
-G
```
```json {{ title: 'Response' }}
{
"object": {
"slug": "my-blog-post-slug",
"title": "My Blog Post",
"metadata": {
"content": "Learning is fun!!
",
"image": {
"imgix_url": "https://imgix.cosmicjs.com/123asdf...",
"alt_text": "This is an example image alt text",
"width": 1200,
"height": 600
}
}
}
}
```
---
## Get a single Object by id
This endpoint enables you to get a single Object by `id`. To get a single Object by `id`, indicate the `id` in the `query` parameter.
To get an Object by slug, see the [above example](/docs/api/objects#get-a-single-object-by-slug).
### Optional parameters
A JSON object to perform Object search and filtering. See [queries section](/docs/api/queries) for more detail. Must be URL encoded for REST requests.
### Optional methods
Declare which properties to return in comma-separated string (or array if using the NPM module). Remove to see all Object properties. Can include nested metadata. Example: `slug,title,metadata.content,metadata.image.imgix_url`.
If you are using the Cosmic JavaScript SDK, you can format the `props` string in a graph syntax such as:
```graphql
{
slug
title
metadata {
content
image {
imgix_url
}
}
}
```
Set to `any` for latest version of draft or published Object.
Options `published | draft | any`
Default `published`
The depth of Object references using Object Relationship Metafields. Circular reference is prohibited.
Default `0`
Set to `false` for real-time updates. Increases latency of endpoint.
Default `true`
Set to `true` for reader-friendly formated JSON response.
Default `false`
Used to get more media data. Contains a `media` object with a `props` property. This is handy for getting media size, dimensions, alt text, metadata, etc. See the Available only on the Cosmic JavaScript SDK. For example:
```js
await cosmic.objects.findOne({
id: 'object-id'
}).props(props)
.options({
media: {
props: 'alt_text,width,height'
}
})
```
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY'
})
const props = `{
slug
title
metadata {
content
image {
imgix_url
}
}
}`
await cosmic.objects.findOne({
id: 'object-id'
}).props(props)
.options({
media: {
props: 'alt_text,width,height'
}
})
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects/:id \
-d read_key=${BUCKET_READ_KEY} \
-d props=slug,title,content,metadata.image.imgix_url \
-G
```
```swift {{ title: 'Swift' }}
let cosmic = CosmicSDKSwift(
.createBucketClient(
bucketSlug: "BUCKET_SLUG",
readKey: "READ_KEY",
writeKey: "WRITE_KEY"
)
)
@State private var object: Object?
cosmic.findOne(type: "object-type", id: "object.id") { results in
switch results {
case .success(let result):
self.object = result.object
case .failure(let error):
print(error)
}
}
```
```json {{ title: 'Response' }}
{
"object": {
"slug": "learning",
"title": "Learning",
"metadata": {
"content": "Learning is fun!!
",
"image": {
"imgix_url": "https://imgix.cosmicjs.com/123asdf...",
"alt_text": "This is an example image alt text",
"width": 1200,
"height": 600
}
}
}
}
```
---
## Create an Object
This endpoint enables you to create an Object in your Bucket.
The data request payload will need to be sent in JSON format with the `Content-Type: application/json` header set.
### Required parameters
Object title.
Object type `slug`.
### Optional parameters
If `slug` is not included, the `title` will be converted into the `slug`.
If validation requirements are set on Metafields on the Object type, they will need to pass the validation requirements.
Triggers corresponding Object action webhook (See Webhooks).
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.objects.insertOne({
title: 'Blog Post Example Title',
type: 'blog-posts',
metadata: {
content: 'Here is an example blog post content...',
seo_description: 'This is an example blog post SEO description.',
featured_post: true
}
})
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects \
-d '{"title":"Blog Post Example Title","type":"blog-posts","metadata":{"content": "Here is an example blog post content...","seo_description":"This is an example blog post SEO description.","featured_post": true}}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```swift {{ title: 'Swift' }}
let cosmic = CosmicSDKSwift(
.createBucketClient(
bucketSlug: "BUCKET_SLUG",
readKey: "READ_KEY",
writeKey: "WRITE_KEY"
)
)
@State private var object: Object?
cosmic.insertOne(
type: "object-type",
title: "object.title"
) { results in
switch results {
case .success(_):
print("Updated \(object.id)")
case .failure(let error):
print(error)
}
}
```
```json {{ title: 'Response' }}
{
"object": {
"id": "5ff75368c2dfa81a91695cec",
"title": "Blog Post Example Title",
"slug": "blog-post-example-title",
"type":"blog-posts-type-slug",
"metadata":{
"content": "Here is an example blog post content...",
"seo_description": "This is an example blog post SEO description.",
"featured_post": true
}
}
}
```
---
## Update an Object
This endpoint enables you to update an Object.
The data request payload will need to be sent in JSON format with the `Content-Type: application/json` header set.
### Required parameters
Object id.
### Optional parameters
Object title.
Object slug.
Status of the Object.
Options `published | draft`
If validation requirements are set on Metafields on the Object type, they will need to pass the validation requirements.
UNIX millisecond timestamp. Publish automatically at a later time.
UNIX millisecond timestamp. Unpublish automatically at a later time.
See [localization](/docs/api/localization) for locale options.
Media `name`. Media must be available in Bucket. See Media(link to media).
Triggers corresponding Object action webhook (See Webhooks).
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.objects.updateOne("object-id", {
title: 'New Title Edit',
metadata: {
featured_post: false
}
})
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects/:id \
-d '{"title":"New Title Edit"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}" \
-X PATCH
```
```swift {{ title: 'Swift' }}
let cosmic = CosmicSDKSwift(
.createBucketClient(
bucketSlug: "BUCKET_SLUG",
readKey: "READ_KEY",
writeKey: "WRITE_KEY"
)
)
@State private var object: Object?
cosmic.updateOne(
type: "object-type",
id: "object.id",
title: "New Title Edit",
metadata: ["featured_post": false]
) { results in
switch results {
case .success(_):
print("Updated \(object.id)")
case .failure(let error):
print(error)
}
}
```
```json {{ title: 'Response' }}
{
"object": {
"id": "5ff75368c2dfa81a91695cec",
"title": "New Title Edit",
"slug": "blog-post-title",
"type":"blog-posts",
"metadata":{
"content": "Here is the blog post content...",
"seo_description": "This is the blog post SEO description.",
"featured_post": false
}
}
}
```
---
## Update Object metadata
Learn how to update Object metadata.
Use the `metadata` property when doing create or update requests to the Objects API endpoint.
### Update basic Metafields
To update basic Metafields on Objects such as text and numbers, make sure to send the corresponding type.
### Required parameter
Using the `metadata` property, update metadata values using the Object type Metafield `key:value` format.
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.objects.updateOne('object-id', {
metadata: {
headline: 'This guitar amp is LOUD!',
max_volume: 11,
on_sale: true
}
})
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects/:id \
-d '{"metadata":{"headline":"This guitar amp is LOUD!","max_volume":11,"on_sale":true}}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}" \
-X PATCH
```
```swift {{ title: 'Swift' }}
let cosmic = CosmicSDKSwift(
.createBucketClient(
bucketSlug: "BUCKET_SLUG",
readKey: "READ_KEY",
writeKey: "WRITE_KEY"
)
)
@State private var object: Object?
cosmic.updateOne(
type: "object-type",
id: "object.id",
metadata: [
"headline": "This guitar amp is LOUD!",
"max_volume": 11,
"on_sale": true
]
) { results in
switch results {
case .success(_):
print("Updated \(object.id)")
case .failure(let error):
print(error)
}
}
```
```json {{ title: 'Response' }}
{
"object": {
"id": "5ff75368c2dfa81a91695cec",
"title": "Fender Spinal Tap Edition Amp",
"slug": "fender-spinal-tap-edition-amp",
"metadata": {
"headline": "This guitar amp is LOUD!",
"max_volume": 11,
"on_sale": true
}
}
}
```
`
### Object relationship Metafield
**Single Object**
To add or update a single Object relationship Metafield, set the Object `id` as a `string` in the `metadata.$key` value.
**Multiple Object**
To add or update a multiple Object relationship Metafield, use an `array` of Object ids.
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.objects.updateOne('object-id', {
metadata: {
author: 'author-object-id', // Object id
categories: ['cat1-object-id','cat2-object-id','cat3-object-id'] // Object ids
}
})
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects/:id \
-d '{"metadata":{"author":"author-object-id","categories":["cat1-object-id","cat2-object-id","cat3-object-id"]}}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}" \
-X PATCH
```
```swift {{ title: 'Swift' }}
let cosmic = CosmicSDKSwift(
.createBucketClient(
bucketSlug: BUCKET,
readKey: READ_KEY,
writeKey: WRITE_KEY
)
)
@State private var object: Object?
cosmic.updateOne(
type: "object-type",
id: "object.id",
metadata: [
"author": "author-object-id",
"categories": [
"cat1-object-id",
"cat2-object-id",
"cat3-object-id"
]
]
) { results in
switch results {
case .success(_):
print("Updated \(object.id)")
case .failure(let error):
print(error)
}
}
```
```json {{ title: 'Response' }}
{
"object": {
"id": "5ff75368c2dfa81a91695cec",
"title": "New Title Edit",
"slug": "blog-post-title",
"metadata": {
"author": "author-object-id",
"categories": ["cat1-object-id", "cat2-object-id", "cat3-object-id"]
}
}
}
```
### Media Metafields
To add a value to a media Metafield, use the `name` of an existing media resource in the Bucket.
**Single Media**
To add a single media Metafield, use the media `name` value such as:
```json
{
"metadata": {
"image": "image-name-in-bucket.jpg"
}
}
```
**Multi Media**
For the Multi Media Metafield, use an `array` of media `name` values such as:
```json
{
"metadata": {
"images": ["image-name-1.jpg", "image-name-2.jpg", "image-name-3.jpg"]
}
}
```
See [media model](/docs/api/media).
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.objects.updateOne('object-id', {
metadata: {
image: "image-name-in-bucket.jpg"
}
})
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects/:id \
-d '{"metadata":{"image":"image-name-in-bucket.jpg"}}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}" \
-X PATCH
```
```swift {{ title: 'Swift' }}
let cosmic = CosmicSDKSwift(
.createBucketClient(
bucketSlug: BUCKET,
readKey: READ_KEY,
writeKey: WRITE_KEY
)
)
@State private var object: Object?
cosmic.updateOne(
type: "object-type",
id: "object.id",
metadata: [
"image": "image-name-in-bucket.jpg"
]
) { results in
switch results {
case .success(_):
print("Updated \(object.id)")
case .failure(let error):
print(error)
}
}
```
```json {{ title: 'Response' }}
{
"object": {
"id": "5ff75368c2dfa81a91695cec",
"title": "New Title Edit",
"slug": "blog-post-title",
"metadata": {
"image": {
"url": "https://cdn.cosmicjs.com/image-name-in-bucket.jpg",
"imgix_url": "https://imgix.cosmicjs.com/image-name-in-bucket.jpg"
}
}
}
}
```
---
## Add Object Revision
This endpoint enables you to add a revision to an Object.
The data request payload will need to be sent in JSON format with the `Content-Type: application/json` header set.
### Required parameters
Object id.
### Default parameters
The status will always be `draft`. Use the [update methods](/docs/api/objects#update-an-object) to update the status of an Object to `published`.
### Optional parameters
Object title.
Object slug.
HTML Content. (deprecatated in API v3, use Metafield instead)
If validation requirements are set on Metafields on the Object type, they will need to pass the validation requirements.
UNIX millisecond timestamp. Publish automatically at a later time.
UNIX millisecond timestamp. Unpublish automatically at a later time.
Media `name`. Media must be available in Bucket. See Media(link to media).
See [localization](/docs/api/localization) for locale options.
Triggers corresponding Object action webhook (See Webhooks).
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.objectRevisions.insertOne("object-id", {
title: 'New Title Edit',
metadata: {
featured_post: false
}
})
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects/:id/revisions \
-d '{"title":"New Title Edit"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}" \
-X POST
```
```json {{ title: 'Response' }}
{
"revision": {
"id": "5ff75368c2dfa81a91695cec",
"title": "New Title Edit",
"slug": "blog-post-title",
"type":"blog-posts",
"metadata":{
"content": "Here is the blog post content...",
"seo_description": "This is the blog post SEO description.",
"featured_post": false
}
}
}
```
---
## Batch Operations
Perform multiple Object operations (create, update, delete) in a single request. Each operation succeeds or fails independently.
The data request payload will need to be sent in JSON format with the `Content-Type: application/json` header set.
### Required parameters
Array of operations to perform. Maximum 25 operations per request.
### Operation object
The operation type.
Options `add | edit | delete`
Object id. Required for `edit` and `delete` methods.
Object data. Required for `add` and `edit` methods. Supports the same properties as the individual create/update endpoints (title, type, slug, metadata, status, etc).
Triggers corresponding Object action webhook for this operation.
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY',
})
const result = await cosmic.objects.batch([
{ method: 'add', object: { title: 'New Post', type: 'posts', metadata: { content: 'Hello' } } },
{ method: 'edit', object_id: 'OBJECT_ID', object: { title: 'Updated Title' } },
{ method: 'delete', object_id: 'OBJECT_ID_2' },
])
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects/batch \
-d '{"operations":[{"method":"add","object":{"title":"New Post","type":"posts","metadata":{"content":"Hello"}}},{"method":"edit","object_id":"OBJECT_ID","object":{"title":"Updated Title"}},{"method":"delete","object_id":"OBJECT_ID_2"}]}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```bash {{ title: 'CLI' }}
cosmic objects batch --data '[{"method":"add","object":{"title":"New Post","type":"posts","metadata":{"content":"Hello"}}},{"method":"edit","object_id":"OBJECT_ID","object":{"title":"Updated Title"}},{"method":"delete","object_id":"OBJECT_ID_2"}]'
# Or from a file
cosmic objects batch --file operations.json
```
```json {{ title: 'Response' }}
{
"operations": [
{
"method": "add",
"status": "success",
"object": {
"id": "5ff75368c2dfa81a91695cec",
"title": "New Post",
"slug": "new-post",
"type": "posts"
}
},
{
"method": "edit",
"status": "success",
"object": {
"id": "OBJECT_ID",
"title": "Updated Title"
}
},
{
"method": "delete",
"status": "success",
"message": "Object 'OBJECT_ID_2' deleted."
}
]
}
```
---
## Delete an Object
This endpoint enables you to delete Objects from your Bucket.
### Required parameters
Object id.
### Optional parameters
Triggers corresponding Object action webhook (See Webhooks).
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.objects.deleteOne('object-id')
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects/:id \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}" \
-X DELETE
```
```swift {{ title: 'Swift' }}
let cosmic = CosmicSDKSwift(
.createBucketClient(
bucketSlug: BUCKET,
readKey: READ_KEY,
writeKey: WRITE_KEY
)
)
@State private var object: Object?
cosmic.deleteOne(type: "object-type", id: "object.id")
{ results in
switch results {
case .success(_):
print("Deleted \(object.id)")
case .failure(let error):
print(error)
}
}
```
```json {{ title: 'Response' }}
{
"message": "Object with id ':id' deleted successfully from bucket."
}
```
---
---
# Revisions
Learn about Revisions; the version history of content in your Cosmic Bucket.
Use the following methods to view and manage Revisions. Note: Revisions cannot be edited or deleted.
## The Revision model
The Revision model contains all the information about content revisions.
### Properties
Unique identifier for Revision.
ID of the Object this revision belongs to.
Object title at time of revision.
Object slug at time of revision.
HTML Content at time of revision. (deprecatated in API v3, use Metafield instead)
Values of the Metafields at time of revision.
The id of the user who created the revision.
Date the revision was created.
Status of the revision.
Options `published | draft`
Date revision was published (if applicable).
Date revision was last modified.
See [localization](/docs/api/localization) for locale options.
```json
{
"id": "64fe8a1b24090e0008683e53",
"object_id": "63dc57ca24090e0008683d42",
"title": "Add a headless CMS to Astro in 3 easy steps",
"slug": "add-a-headless-cms-to-astro-in-3-easy-steps",
"bucket": "63dc24a4d71e244b63c88fca",
"created_at": "2023-03-23T12:08:13.547Z",
"modified_at": "2023-03-23T12:08:13.547Z",
"status": "published",
"thumbnail": "https://imgix.cosmicjs.com/1c8531f0-97fb-11ed-81d8-8f0123e10511-A-photo-of-Michelangelos-sculpture-of-David-wearing-headphones-djing.webp",
"published_at": "2023-03-23T12:08:13.547Z",
"created_by": "629e6cdda6f4f100091ae2e0",
"type": "blog-posts",
"metadata": {
"content": "Astro is a lightweight web framework capable of shipping highly performant websites with minimal (or non-existent) JavaScript bundles. In this guide...",
"image": {
"url": "https://cdn.cosmicjs.com/02670ac0-38ef-11ed-adfd-ddb1795c6ac6-add-a-headless-cms-to-astro-in-3-easy-steps.png",
"imgix_url": "https://imgix.cosmicjs.com/02670ac0-38ef-11ed-adfd-ddb1795c6ac6-add-a-headless-cms-to-astro-in-3-easy-steps.png"
},
"published_date": "2022-09-20",
"author": {
"title": "Bill Brasky"
}
}
}
```
---
## Get Revisions
This endpoint enables you to retrieve a list of revisions for a specific Object.
### Required parameters
ID of the Object to retrieve revisions for.
### Optional methods
Declare which properties to return in comma-separated string (or array if using the NPM module). Remove to see all Revision properties.
Limit the number of Revisions returned.
Default `1000`
Used for pagination. The number of Revisions to skip.
Default `0`
Order of Revisions returned.
Options `created_at, -created_at`
Use `-` for descending order.
Default `-created_at` (newest first)
Set to `false` for real-time updates. Increases latency of endpoint.
Default `true`
Set to `true` for reader-friendly formated JSON response.
Default `false`
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY'
})
await cosmic.objectRevisions.find('object-id').props([
'id',
'title',
'created_at',
'status'
]).limit(10)
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects/${OBJECT_ID}/revisions \
-d read_key=${BUCKET_READ_KEY} \
-d props=id,title,created_at,status \
-d limit=10 \
-G
```
```json {{ title: 'Response' }}
{
"revisions": [
{
"id": "64fe8a1b24090e0008683e53",
"title": "Add a headless CMS to Astro in 3 easy steps",
"created_at": "2023-03-23T12:08:13.547Z",
"status": "published"
},
{
"id": "64fe8a0924090e0008683e52",
"title": "Add a headless CMS to Astro in 3 easy steps (Draft)",
"created_at": "2023-03-23T12:07:45.123Z",
"status": "draft"
}
],
"total": 2,
"limit": 10
}
```
---
## Get a single Revision
This endpoint enables you to get a single Revision by its ID.
### Required parameters
ID of the Object the revision belongs to.
ID of the specific revision to retrieve.
### Optional methods
Declare which properties to return in comma-separated string (or array if using the NPM module). Remove to see all Revision properties.
Set to `false` for real-time updates. Increases latency of endpoint.
Default `true`
Set to `true` for reader-friendly formated JSON response.
Default `false`
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY'
})
await cosmic.objectRevisions.findOne({
objectId: 'object-id',
revisionId: 'revision-id'
}).props([
'id',
'title',
'metadata',
'created_at'
])
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects/${OBJECT_ID}/revisions/${REVISION_ID} \
-d read_key=${BUCKET_READ_KEY} \
-d props=id,title,metadata,created_at \
-G
```
```json {{ title: 'Response' }}
{
"revision": {
"id": "64fe8a1b24090e0008683e53",
"title": "Add a headless CMS to Astro in 3 easy steps",
"created_at": "2023-03-23T12:08:13.547Z",
"metadata": {
"content": "Astro is a lightweight web framework capable of shipping highly performant websites with minimal (or non-existent) JavaScript bundles. In this guide...",
"image": {
"url": "https://cdn.cosmicjs.com/02670ac0-38ef-11ed-adfd-ddb1795c6ac6-add-a-headless-cms-to-astro-in-3-easy-steps.png",
"imgix_url": "https://imgix.cosmicjs.com/02670ac0-38ef-11ed-adfd-ddb1795c6ac6-add-a-headless-cms-to-astro-in-3-easy-steps.png"
},
"published_date": "2022-09-20",
"author": {
"title": "Bill Brasky"
}
}
}
}
```
---
## Add a Revision
This endpoint enables you to add a new revision to an existing Object.
Adding a revision creates a new version of the Object without publishing it.
### Required parameters
ID of the Object to add a revision to.
### Optional parameters
Updated title for the revision.
Updated slug for the revision.
Updated metadata values for the revision.
Status of the revision.
Options `published | draft`
Default `draft`
Triggers corresponding Object action webhook (See Webhooks).
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.objectRevisions.insertOne('object-id', {
title: 'Updated Blog Post Title',
metadata: {
content: 'This is the updated content for the blog post...',
featured_post: true
},
status: 'draft'
})
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects/${OBJECT_ID}/revisions \
-d '{"title":"Updated Blog Post Title","metadata":{"content":"This is the updated content for the blog post...","featured_post":true},"status":"draft"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer ${BUCKET_WRITE_KEY}" \
-X POST
```
```json {{ title: 'Response' }}
{
"revision": {
"id": "65fe8a1b24090e0008683e54",
"object_id": "63dc57ca24090e0008683d42",
"title": "Updated Blog Post Title",
"slug": "add-a-headless-cms-to-astro-in-3-easy-steps",
"status": "draft",
"created_at": "2023-04-15T09:22:45.123Z",
"created_by": "629e6cdda6f4f100091ae2e0",
"metadata": {
"content": "This is the updated content for the blog post...",
"featured_post": true,
"image": {
"url": "https://cdn.cosmicjs.com/02670ac0-38ef-11ed-adfd-ddb1795c6ac6-add-a-headless-cms-to-astro-in-3-easy-steps.png",
"imgix_url": "https://imgix.cosmicjs.com/02670ac0-38ef-11ed-adfd-ddb1795c6ac6-add-a-headless-cms-to-astro-in-3-easy-steps.png"
}
}
}
}
```
---
---
# Metafields
Learn about Metafields; the way you compose, extend, and connect the Object content model in Cosmic.
**What are Metafields?** Metafields are the way to add custom fields to your Objects. They are stored in the Object type and are not stored in the Object. They contain the data model, validation, etc.
**What is Metadata?** Metadata is the data you add to your Objects using the Metafields model. They contain the data values.
## Data model
| Parameter | Required | Type | Description |
| :---------------------- | :------------------------------------------------------: | :--------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type` | required | Enum | text, textarea, html-textarea, select, multi-select, select-dropdown, object, objects, file, files, date, radio-buttons, check-boxes, repeater, parent, markdown, json, switch, number, color, emoji |
| `title` | required | String | Your Metafield title |
| `key` | required | String | Unique identifier for your Metafield |
| `value` | varies | Varies by `type` | Metafield value. Property required to be present (empty string ok) except for `repeater` and `parent` (should not be present). See example model below for various value types and requirements. |
| `required` | | Bool | A value is required |
| `unique` | | Bool | Value must be unique across all Objects of the same type. Applies to top-level text, textarea, number, date, select Metafields (not supported inside Parent or Repeater groups). Localized versions of the same Object are excluded from this check. |
| `regex` | | String | Restrict the value to match a regular expresssion |
| `regex_message` | | String | The message displayed when the value fails the regex |
| `minlength` | | Number | Add minlength to text or textarea Metafields |
| `maxlength` | | Number | Add maxlength to text or textarea Metafields |
| `options` | Required for `select`, `multi-select`, `radio`, `checkbox` and `switch` | Varies by `type` | Array of `{ "value": "..." }` options for `select`, `multi-select`, `select-dropdown`, radio, and checkbox Metafields. String for switch Metafield with possible values `true,false` and `yes,no` |
| `children` | | Array | Array of nested Metafields |
| `object_type` | | String | Valid Object type slug. Applies only to `object` and `objects` Metafield |
| `repeater_fields` | | Array | Array of nested Metafields. Applies only to `repeater` Metafield |
| `media_validation_type` | | String | image, video, audio, application. Applies only to `file` and `files` Metafield |
| `show_when` | | Object | Conditional visibility. Show this field only when a sibling field matches a condition. Format: `{ "key": "field_key", "op": "eq" or "neq" or "exists" or "not_exists", "value": "match_value" }`. Hidden fields skip required validation. The API always stores all fields. Top-level only. |
## Adding and editing Metafields
When adding / editing Metafields to Object types using the API, use the following model for each Metafields type. Any value added to the `value` property is treated as a default value on each newly created Object.
```json
{
"metafields": [
{
"type": "text",
"title": "Headline",
"key": "headline",
"value": "3030 Palo Alto Blvd.",
"required": true
},
{
"type": "textarea",
"title": "Basic Text",
"key": "basic_text",
"value": "This home is a must see!",
"required": true
},
{
"type": "html-textarea",
"title": "Extended Text",
"key": "extended_text",
"value": "Some HTML content for dramatic effect!
"
},
{
"type": "markdown",
"title": "Markdown Text",
"key": "markdown_text",
"value": "# Hello World!"
},
{
"type": "select-dropdown",
"title": "State",
"key": "state",
"value": "California",
"options": [
{
"key": "CA",
"value": "California"
},
{
"key": "TX",
"value": "Texas"
}
]
},
{
"type": "select",
"title": "Category",
"key": "category",
"value": "Technology",
"options": [
{ "value": "Technology" },
{ "value": "Business" },
{ "value": "Design" }
]
},
{
"type": "multi-select",
"title": "Tags",
"key": "tags",
"value": ["Technology", "Business"],
"options": [
{ "value": "Technology" },
{ "value": "Business" },
{ "value": "Design" }
]
},
{
"type": "object",
"title": "Author",
"key": "author",
"object_type": "authors",
"value": "5a4806974fa85fc8a7000002" // Object ID
},
{
"type": "objects",
"title": "Categories",
"key": "categories",
"object_type": "categories",
"value": ["5a4806974fa85fc8a7000007,5a4806974fa85fc8a7000008"] // Object IDs
},
{
"type": "file",
"title": "Hero",
"key": "hero",
"value": "media-name-property-in-bucket.jpg", // This is the name of your media.
"media_validation_type": "image"
},
{
"type": "files",
"title": "Gallery",
"key": "gallery",
"value": [
"gallery-image-1.jpg",
"gallery-image-2.jpg",
"gallery-image-3.jpg"
] // These are the names of your media.
},
{
"type": "date",
"title": "Listing Start Date",
"key": "listing_start_date",
"value": "2020-10-15"
},
{
"type": "json",
"title": "JSON Data",
"key": "json_data",
"value": {
"strings": "cheese",
"arrays": ["Bradbury", "Charles", "Ramono", "the last Jedi", "Liotta"],
"objects": {
"bools": true,
"nestable": true
}
}
},
{
"type": "radio-buttons",
"title": "Deposit Required",
"key": "deposit_required",
"value": "The Other",
"options": [
{
"value": "This"
},
{
"value": "That"
},
{
"value": "The Other"
}
]
},
{
"type": "check-boxes",
"title": "Amenities",
"key": "amenities",
"value": ["Pool", "Gym"],
"options": [
{
"value": "Pool"
},
{
"value": "Gym"
},
{
"value": "Landscaping"
}
]
},
{
"type": "switch",
"title": "This is great",
"key": "this_is_great",
"value": true,
"options": "true,false"
},
{
"type": "color",
"title": "Color",
"key": "color",
"value": "#29abe2"
},
{
"type": "parent", // ! Value is not allowed for parent Metafield !
"title": "Call Out Section",
"key": "call_out_section",
"children": [
{
"type": "text",
"title": "Headline",
"key": "headline",
"value": "You're Going to Love it Here!"
},
{
"type": "html-textarea",
"title": "Section Content",
"key": "section_content",
"value": "You are going to love it in Cosmic Village. The best place to raise a team!
"
},
{
"type": "file",
"title": "Hero",
"key": "hero",
"value": "big-beautiful-image.jpg",
"media_validation_type": "image"
}
]
},
{
"type": "repeater", // ! Value is not allowed for repeater Metafield !
"title": "Testimonials",
"key": "testimonials",
// Available repeaters
"repeater_fields": [
{
"title": "Name",
"key": "name",
"value": "",
"type": "text",
"required": false
},
{
"title": "Quote",
"key": "quote",
"value": "",
"type": "text",
"required": false
}
]
}
]
}
```
### `select` and `multi-select`
```json
{
"type": "select",
"title": "Category",
"key": "category",
"value": "Technology",
"options": [
{ "value": "Technology" },
{ "value": "Business" },
{ "value": "Design" }
]
}
```
```json
{
"type": "multi-select",
"title": "Tags",
"key": "tags",
"value": ["Technology", "Business"],
"options": [
{ "value": "Technology" },
{ "value": "Business" },
{ "value": "Design" }
]
}
```
### Metafield Validation
You can use optional validation parameters to make sure editors using the web dashboard enter the correct values.
Reference the [Metafield model](/docs/api/metafields#data-model) to learn more.
| Parameter | Required | Type | Description |
| --------------- | -------- | ------ | ------------------------------------------------------------------------------------ |
| `required` | | Bool | A value is required |
| `unique` | | Bool | Value must be unique per Object type. Applies to top-level text, textarea, number, date, select (not inside Parent or Repeater). Localized versions of the same Object are excluded. |
| `regex` | | String | Restrict the value to match a regular expresssion |
| `regex_message` | | String | The message displayed when the value fails the regex |
| `minlength` | | Number | Add minlength to text or textarea Metafields |
| `maxlength` | | Number | Add maxlength to text or textarea Metafields |
| `show_when` | | Object | Conditional visibility. Show field only when sibling matches condition. See [show_when](#conditional-visibility). |
### Conditional Visibility
Use the `show_when` property to show or hide a Metafield based on another field's value. This is a UI-only feature: the API always stores and returns all Metafield values regardless of visibility state.
```json
{
"key": "company_name",
"title": "Company Name",
"type": "text",
"required": true,
"show_when": {
"key": "contact_type",
"op": "eq",
"value": "Business"
}
}
```
**Operators:**
- `eq` - Field value equals the specified value
- `neq` - Field value does not equal the specified value
- `exists` - Field has any non-empty value
- `not_exists` - Field is empty or not set
When a field is hidden by its `show_when` condition, `required` validation is automatically skipped.
### Example Metafields with validation
```json
{
"title": "Users",
"singular": "User",
"slug": "users",
"metafields": [
{
"key": "first_name",
"title": "First Name",
"type": "text",
"required": true,
"minlength": 2
},
{
"key": "last_name",
"title": "Last Name",
"type": "text",
"required": true,
"minlength": 2
},
{
"key": "email",
"title": "Email",
"type": "text",
"unique": true,
"regex": "/^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/",
"regex_message": "You must enter a valid email."
},
{
"key": "avatar",
"title": "Avatar",
"type": "file",
"media_validation_type": "image"
},
{
"key": "tagline",
"title": "Tagline",
"type": "text",
"maxlength": 50
}
]
}
```
## Fetching Metadata
When fetching Objects from the API, Metafields get converted into `key: value` pairs on the Object `metadata` property. See the [Objects model](/docs/api/objects) for more information.
`select` Metafields resolve to a **plain string** (the selected option value). `multi-select` Metafields resolve to a **string array** of selected values. For example, `category` and `tags` in the sample `metadata` below illustrate those shapes.
> Note: `select-dropdown` is deprecated. Use `select` for single-select or `multi-select` for multi-select in new content models. Existing `select-dropdown` fields continue to work and return `{ key, value }` objects in metadata.
```json
{
"metadata": {
"headline": "3030 Palo Alto Blvd.",
"basic_text": "This home is a must see!",
"extended_text": "Some HTML content for dramatic effect!
",
"markdown_text": "# Hello World!",
"state": "California",
"category": "Technology",
"tags": ["Technology", "Business"],
"author": {
"title": "Author Name",
"metadata": {
"image": {
"url": "https://cdn.cosmicjs.com/author-headshot.jpg",
"imgix_url": "https://imgix.cosmicjs.com/author-headshot.jpg"
}
}
// May include more nested data
},
"categories": [
{
"title": "Category 1"
// May include more nested data
},
{
"title": "Category 2"
// May include more nested data
},
],
"hero": "https://cdn.cosmicjs.com/media-name-property-in-bucket.jpg",
"gallery": [
{
"url": "https://cdn.cosmicjs.com/gallery-image-1.jpg",
"imgix_url": "https://imgix.cosmicjs.com/gallery-image-1.jpg"
},
{
"url": "https://cdn.cosmicjs.com/gallery-image-2.jpg",
"imgix_url": "https://imgix.cosmicjs.com/gallery-image-2.jpg"
},
{
"url": "https://cdn.cosmicjs.com/gallery-image-3.jpg",
"imgix_url": "https://imgix.cosmicjs.com/gallery-image-3.jpg"
},
],
"listing_start_date": "2020-10-15",
"json_data": {
"strings": "cheese",
"arrays": ["Bradbury", "Charles", "Ramono", "the last Jedi", "Liotta"],
"objects": {
"bools": true,
"nestable": true
}
},
"deposit_required": "The Other",
"amenities": ["Pool", "Gym"],
"this_is_great": true,
"call_out_section": {
"headline": "You're Going to Love it Here!",
"section_content": "You are going to love it in Cosmic Village. The best place to raise a team!
",
"hero": {
"url": "https://cdn.cosmicjs.com/big-beautiful-image.jpg",
"imgix_url": "https://imgix.cosmicjs.com/big-beautiful-image.jpg"
}
},
"testimonials": [
{
"name": "Fiona Apple",
"quote": "This is the best place in the LA area!"
},
{
"name": "Jon Brion",
"quote": "I came for the great music, I stayed for the good vibes."
}
]
}
```
---
# Media
Learn about media; the images, files, and documents stored in your Cosmic Bucket.
## The media model
The media model contains all the information about your media.
### Properties
Unique identifier for the media.
Unique name of the uploaded file, used in media Metafield value. (See
[updating Object metadata](/docs/api/objects#update-object-metadata))
Media CDN URL.
imgix URL (used for image processing and optimizations). See
[using imgix](#using-imgix).
Media folder.
Alt text. Available for images only.
Image width in pixels. Available for images only.
Image height in pixels. Available for images only.
User-added JSON metadata.
Original file name.
File size in bytes.
File type.
Bucket id.
Date created.
```json
{
"id": "641c6b898bb999b71f8a0dde",
"name": "7f9403a32f29-toucan.jpg",
"original_name": "toucan.jpg",
"size": 32466,
"type": "image/png",
"bucket": "63dc24a4d71e244b63c88fca",
"created_at": "2024-03-23T15:08:57.913Z",
"folder": "wildlife",
"alt_text": "A picture of a Toucan.",
"width": 1200,
"height": 600,
"url": "https://cdn.cosmicjs.com/7f9403a32f29-toucan.jpg",
"imgix_url": "https://imgix.cosmicjs.com/7f9403a32f29-toucan.jpg"
}
```
---
## Get media list
This endpoint enables you to retrieve a list of your media. By default, a maximum of 1000 media items are shown per page.
### Optional parameters
A JSON object to perform media search and filtering. See [queries section](/docs/api/queries) for more detail. Must be URL encoded for REST requests.
### Optional methods
Declare which properties to return in comma-separated string (or array if using the NPM module). Remove to see all media properties. Can include nested metadata. Example: `id,title,metadata.author.metadata.image.url`.
Order of media returned.
Options `created_at, -created_at, modified_at, -modified_at, random`
Use `-` for descending order.
Limit the number of media returned.
Default `1000`
Used for pagination. The number of media to skip.
Default `0`
Set to `false` for real-time updates. Increases latency of endpoint.
Default `true`
Set to `true` for reader-friendly formated JSON response.
Default `false`
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY'
})
await cosmic.media.find({
folder: "product-images", // Get media in folder
})
.props('url')
.limit(2)
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/media \
-d read_key=${BUCKET_READ_KEY} \
--data-urlencode query='{"folder":"product-images"}' \
-d props=url \
-d limit=2 \
-G
```
```json {{ title: 'Response' }}
{
"media": [
{
"url": "https://cdn.cosmicjs.com/9c4d6b70-49e5-11eb...",
},
{
"url": "https://cdn.cosmicjs.com/9c4d6b70-49e5-11eb...",
}
],
"total": 10,
"limit": 2
}
```
---
---
## Get a single media
This endpoint enables you to get a single media.
With the Cosmic NPM module, you can use the `findOne` method to return an `object` type instead of `array`. If using the REST API, it will return an `array`.
### Optional parameters
Use any of the properties on the media model. A common one would be the file name.
A JSON object to perform Object search and filtering. See [queries section](/docs/api/queries) for more detail. Must be URL encoded for REST requests.
### Optional methods
Declare which properties to return in comma-separated string (or array if using the NPM module). Remove to see all media properties. Can include nested metadata. Example: `id,title,metadata.author.metadata.image.url`.
Order of media returned.
Options `created_at, -created_at, modified_at, -modified_at, random`
Use `-` for descending order.
Used for pagination. The number of media to skip.
Default `0`
Set to `false` for real-time updates. Increases latency of endpoint.
Default `true`
Set to `true` for reader-friendly formated JSON response.
Default `false`
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY'
})
await cosmic.media.findOne({
name: 'asdf-1234-toucan.png'
}).props([
'name',
'imgix_url',
'alt_text',
'metadata'
])
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/media \
-d read_key=${BUCKET_READ_KEY} \
--data-urlencode query='{"name":"7f9403a32f29-toucan.jpg"}' \
-d props=name,imgix_url,alt_text,metadata \
-G
```
```json {{ title: 'Response' }}
{
"media": {
"name": "7f9403a32f29-toucan.jpg",
"imgix_url": "https://imgix.cosmicjs.com/7f9403a32f29-toucan.jpg",
"alt_text": "Picture of a Toucan.",
"metadata": {
"caption": "Toucan in the wild.",
"credit": "Bird Watchers of America"
}
}
}
```
---
## Create media
This endpoint enables you to upload media to your Bucket.
### Base URL
Use the following endpoint to create media in your Cosmic Bucket.
```
https://workers.cosmicjs.com
```
### Upload limits
The size limit for uploads to the upload URL is `900MB`.
### Required parameters
Media object.
### Media object
The Media Object must be an object with certain properties indicated below.
If using [Multer NPM module](https://www.npmjs.com/package/multer), the popular Node.js package for handling `multipart/form-data`, the file object will have these by default. Otherwise, you should create an object with these properties:
The name of your file (For example: something.jpg)
The File Buffer.
### Optional parameters
Media folder.
Alt text (available for images only).
User-added JSON metadata.
Triggers corresponding media action webhook (See Webhooks).
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
// Using Multer:
const media = req.files[0]
// or not using Multer:
// const media = { originalname: filename, buffer: filedata }
const data = await cosmic.media.insertOne({
media: media,
folder: "album-covers",
metadata: {
caption: "None more black",
credit: "Nigel Tufnel",
}
})
```
```bash {{ title: 'cURL' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/media \
--form 'media=@none-more-black.png' \
--form 'folder=album-covers' \
--form 'metadata={"caption":"None more black","credit":"Nigel Tufnel"}' \
-H 'Authorization: Bearer {BUCKET_WRITE_KEY}'
```
```json {{ title: 'Response' }}
{
"media": {
"id": "602fd622853cca45f4c9fd96",
"name": "c20391e0-b8a4-11e6-8836-fbdfd6956b31-test.png",
"original_name": "none-more-black.png",
"size": 457307,
"folder": "album-covers",
"type": "image/png",
"bucket": "5839c67f0d3201c114000004",
"created_at": "2016-12-02T15:34:05.054Z",
"url": "https://cdn.cosmicjs.com/asdf-1234-none-more-black.png",
"imgix_url": "https://imgix.cosmicjs.com/asdf-1234-none-more-black.png",
"metadata": {
"caption": "None more black",
"credit": "Nigel Tufnel"
}
}
}
```
## Upload example
### React Dropzone and React Server Actions
Go to the [Cosmic Next File Upload](https://github.com/cosmicjs/cosmic-next-file-upload) example code to see how to use [React Dropzone](https://react-dropzone.js.org/) and React Server Actions to upload your media without exposing your Cosmic API keys to the client.
---
## Update media
This endpoint enables you to update media data.
### Required parameters
Media id.
### Optional parameters
Media folder.
Alt text (available for images only).
User-added JSON metadata.
Triggers corresponding media action webhook (See Webhooks).
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.media.updateOne('media-id', {
folder: "national-parks",
alt_text: "Picture of Grand Teton National Park".
})
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/media/:id \
-d '{"folder":"national-parks","alt_text":"Picture of Grand Teton National Park"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}" \
-X PATCH
```
```json {{ title: 'Response' }}
{
"media": {
"id": "602fd622853cca45f4c9fd96",
"name": "c20391e0-grand-tetons.png",
"original_name": "grand-tetons.png",
"size": 457307,
"folder": "national-parks",
"type": "image/png",
"bucket": "5839c67f0d3201c114000004",
"created_at": "2016-12-02T15:34:05.054Z",
"url": "https://cdn.cosmicjs.com/c20391e0-grand-tetons.png",
"imgix_url": "https://imgix.cosmicjs.com/c20391e0-grand-tetons.png",
"alt_text": "Picture of Grand Teton National Park"
}
}
```
---
## Delete media
This endpoint enables you to delete media from your Bucket. The underlying file is removed from storage and the CDN caches are purged, so the media URL stops working after deletion.
If the same file is also used by other Buckets (imported, cloned, or installed from an app), deleting it from this Bucket only removes the reference in this Bucket. The file remains available to the other Buckets that use it.
Deleting media does not automatically update Objects or Metafields that reference it. After deleting, you'll need to remove those references manually.
### Required parameters
Media id.
### Optional parameters
Triggers corresponding media action webhook (See Webhooks).
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
await cosmic.media.deleteOne('media-id')
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/media/:id \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}" \
-X DELETE
```
```json {{ title: 'Response' }}
{
"message": "Media with id ':id' deleted successfully from bucket."
}
```
---
## Using imgix
[imgix](https://imgix.com/) is included with every Cosmic account. You can use the imgix suite of image processing tools on the URL provided by the `imgix_url` property found on Cosmic media and Object API responses.
### Before imgix
The image is full size and not optimized:

https://imgix.cosmicjs.com/8d508870-9988-11ec-9edf-8d8ed23fd38e-starry.jpg
### After imgix
Using imgix, we can create an optimized thumbnail by adding `?w=100&auto=format,compress` to the end of the URL:

https://imgix.cosmicjs.com/8d508870-9988-11ec-9edf-8d8ed23fd38e-starry.jpg?w=100&auto=format,compress
There are lots of image processing capabilities with this library as well as a [React imgix component](https://www.npmjs.com/package/react-imgix) to automate optimizations. Check out the [imgix documentation](https://docs.imgix.com/) for more info.
---
# AI
Learn about AI capabilities in the API; generate text, images, and videos using Cosmic AI.
Cosmic provides AI-powered text, image, and video generation capabilities through the API and SDK.
### Base URL
Use the following endpoint to create AI-generated text and images.
```
https://workers.cosmicjs.com
```
---
## Generate Text
This endpoint enables you to generate text content using AI models.
The data request payload will need to be sent in JSON format with the `Content-Type: application/json` header set. A bucket write key is required for all AI operations.
### Required parameters
You must provide either a `prompt` or `messages` parameter.
A text prompt for the AI to generate content from. Use this for simple, single-prompt text generation.
An array of message objects for chat-based models. Each message object should have a `role` (either "user" or "assistant") and `content` (the message text).
### Optional parameters
The AI model to use for text generation. Options include Claude models (e.g., `claude-opus-4-8`), Gemini models (e.g., `gemini-3.1-pro-preview`), and OpenAI models (e.g., `gpt-5.2-codex`). Defaults to `claude-opus-4-8`. See Available Models section for full list.
The maximum number of tokens to generate in the response. Higher values allow for longer responses but may increase processing time.
URL of a file to analyze. Can be any file type available in your Bucket including images, PDFs, Excel spreadsheets, Word documents, and more. The AI model will be able to analyze the content when generating text. Can be used with either `prompt` or `messages`.
When set to true, enables streaming for real-time responses as they're generated, rather than waiting for the complete response. Default is false.
```js {{ title: 'Simple prompt' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
// Using a simple prompt
const textResponse = await cosmic.ai.generateText({
prompt: 'Write a product description for a coffee mug',
max_tokens: 500
})
console.log(textResponse.text)
console.log(textResponse.usage)
```
```js {{ title: 'Chat messages' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
const chatResponse = await cosmic.ai.generateText({
messages: [
{ role: 'user', content: 'Tell me about coffee mugs' },
{
role: 'assistant',
content: 'Coffee mugs are vessels designed to hold hot beverages...'
},
{ role: 'user', content: 'What materials are they typically made from?' }
],
max_tokens: 500
})
console.log(chatResponse.text)
console.log(chatResponse.usage)
```
```js {{ title: 'Image analysis' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
const imageAnalysis = await cosmic.ai.generateText({
prompt: 'Describe this image in detail and suggest a caption for social media',
media_url: 'https://cdn.cosmicjs.com/mountain-landscape.jpg',
max_tokens: 500
})
console.log(imageAnalysis.text)
console.log(imageAnalysis.usage)
```
```js {{ title: 'Document analysis' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
const pdfAnalysis = await cosmic.ai.generateText({
prompt: 'Summarize the key points from this document',
media_url: 'https://cdn.cosmicjs.com/quarterly-report.pdf',
max_tokens: 500
})
console.log(pdfAnalysis.text)
console.log(pdfAnalysis.usage)
```
```js {{ title: 'Chat with file' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
const spreadsheetAnalysis = await cosmic.ai.generateText({
messages: [
{ role: 'user', content: 'What trends do you see in this sales data?' },
{
role: 'assistant',
content: 'Looking at the spreadsheet, I can see several patterns...'
},
{ role: 'user', content: 'What was the highest performing month?' }
],
media_url: 'https://cdn.cosmicjs.com/sales-data.xlsx',
max_tokens: 500
})
console.log(spreadsheetAnalysis.text)
console.log(spreadsheetAnalysis.usage)
```
```bash {{ title: 'Simple prompt' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/text \
-d '{"prompt":"Write a product description for a coffee mug","max_tokens":500}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```bash {{ title: 'With media_url' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/text \
-d '{"prompt":"Summarize this document","media_url":"https://cdn.cosmicjs.com/document.pdf","max_tokens":500}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```json {{ title: 'Simple prompt response' }}
{
"text": "Introducing our Artisan Ceramic Coffee Mug – the perfect companion for your daily brew. Crafted with care from high-quality ceramic, this elegant mug retains heat longer, ensuring your coffee stays at the ideal temperature. The ergonomic handle provides a comfortable grip, while the smooth, glazed interior prevents staining and makes cleaning effortless. Available in a range of sophisticated colors to match any kitchen aesthetic, this 12oz mug strikes the perfect balance between style and functionality.",
"usage": {
"input_tokens": 10,
"output_tokens": 89
}
}
```
```json {{ title: 'Document analysis response' }}
{
"text": "The quarterly report highlights three key achievements:\n\n1. Q4 revenue exceeded projections by 15%, driven primarily by strong performance in the APAC region.\n\n2. New product launches in the sustainable product category showed 2.5x growth compared to previous year.\n\n3. Customer retention rates improved to 85%, attributed to the implementation of the new loyalty program.\n\nKey recommendations include expanding the sustainable product line and rolling out the loyalty program to additional markets in the coming quarter.",
"usage": {
"input_tokens": 25,
"output_tokens": 95
}
}
```
### Streaming Capabilities
Text generation supports real-time streaming responses, allowing you to receive and display content as it's being generated.
#### Using with the SDK
```jsx
import { TextStreamingResponse } from '@cosmicjs/sdk';
// Enable streaming with the stream: true parameter
const result = await cosmic.ai.generateText({
prompt: 'Tell me about coffee mugs',
// or use messages array format
max_tokens: 500,
stream: true // Enable streaming
});
// Cast the result to TextStreamingResponse
const stream = result as TextStreamingResponse;
// Option 1: Event-based approach
let fullResponse = '';
stream.on('text', (text) => {
fullResponse += text;
process.stdout.write(text); // Display text as it arrives
});
stream.on('usage', (usage) => console.log('Usage:', usage));
stream.on('end', (data) => console.log('Complete:', fullResponse));
stream.on('error', (error) => console.error('Error:', error));
// Option 2: For-await loop approach
async function processStream() {
let fullResponse = '';
try {
for await (const chunk of stream) {
if (chunk.text) {
fullResponse += chunk.text;
process.stdout.write(chunk.text);
}
}
console.log('\nComplete text:', fullResponse);
} catch (error) {
console.error('Error:', error);
}
}
```
#### Using the simplified stream method
```jsx
// Simplified streaming method
const stream = await cosmic.ai.stream({
prompt: 'Tell me about coffee mugs',
max_tokens: 500,
});
// Process stream using events or for-await loop as shown above
```
#### Using cURL for streaming
```bash
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/text \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer ${BUCKET_WRITE_KEY}" \
-d '{"prompt":"Tell me about coffee mugs","stream":true}' \
--no-buffer
```
The `TextStreamingResponse` supports two usage patterns:
1. **Event-based**: Extends EventEmitter with these events:
- `text`: New text fragments
- `usage`: Token usage information
- `end`: Final data when stream completes
- `error`: Stream errors
2. **AsyncIterator**: For for-await loops, with chunk objects containing:
- `text`: Text fragments
- `usage`: Token usage information
- `end`: Set to true for the final chunk
- `error`: Error information
---
## Generate Image
This endpoint enables you to create AI-generated images based on text prompts.
The data request payload will need to be sent in JSON format with the `Content-Type: application/json` header set.
### Required parameters
A text description of the image you want to generate. More detailed prompts typically yield better results.
### Optional parameters
The image generation model to use. Options: `gemini-3.1-flash-image-preview` (default, recommended), `gemini-3-pro-image-preview`, or `dall-e-3`. Defaults to `gemini-3.1-flash-image-preview`.
The size of the generated image. For Gemini 3.1 Flash Image: `512x512`, `1024x1024`, `2048x2048`, or `4096x4096`. For Gemini 3 Pro Image: `1024x1024`, `2048x2048`, or `4096x4096`. For DALL-E 3: `1024x1024`, `1792x1024`, or `1024x1792`. Defaults to `1024x1024`.
The quality of the generated image. Options: `standard` or `hd`. Defaults to `standard`. HD quality provides more detailed images but costs more. (DALL-E 3 only)
Array of reference image URLs to provide context for image generation. The AI will analyze these images and use them to inform the generated image. Supported with Gemini models. Flash Image supports up to 14 reference images, Pro Image supports up to 5.
Media folder to store the generated image in. (Folder must exist)
Alt text for the generated image.
User-added JSON metadata for the generated image.
```js {{ title: 'Generate image' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
const imageResponse = await cosmic.ai.generateImage({
prompt: 'A serene mountain landscape at sunset',
folder: 'ai-generated',
alt_text: 'AI-generated mountain landscape at sunset',
metadata: {
caption: 'Beautiful mountain vista',
generated_by: 'Cosmic AI'
}
})
console.log(imageResponse.media.url)
console.log(imageResponse.media.imgix_url)
```
```js {{ title: 'Generate image with options' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
const imageResponse = await cosmic.ai.generateImage({
prompt: 'A futuristic cityscape at night with neon lights',
model: 'dall-e-3',
size: '1792x1024',
quality: 'hd',
folder: 'ai-generated',
alt_text: 'Futuristic cityscape with neon lights'
})
console.log(imageResponse.media.url)
console.log(imageResponse.revised_prompt)
```
```js {{ title: 'With reference images (Gemini)' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
// Use reference images to guide the generation
const imageResponse = await cosmic.ai.generateImage({
prompt: 'Create a similar style image but with mountains instead of buildings',
model: 'gemini-3-pro-image-preview',
size: '2048x2048',
reference_images: [
'https://cdn.cosmicjs.com/style-reference.jpg',
'https://cdn.cosmicjs.com/composition-reference.jpg'
],
folder: 'ai-generated',
alt_text: 'Mountain landscape in referenced style'
})
console.log(imageResponse.media.url)
```
```bash {{ title: 'cURL' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/image \
-d '{"prompt":"A serene mountain landscape at sunset","folder":"ai-generated","alt_text":"AI-generated mountain landscape at sunset"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```bash {{ title: 'cURL with options' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/image \
-d '{"prompt":"A futuristic cityscape at night with neon lights","model":"dall-e-3","size":"1792x1024","quality":"hd"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```bash {{ title: 'cURL with reference images' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/image \
-d '{
"prompt":"Create a similar style image but with mountains",
"model":"gemini-3-pro-image-preview",
"size":"2048x2048",
"reference_images":[
"https://cdn.cosmicjs.com/style-reference.jpg",
"https://cdn.cosmicjs.com/composition-reference.jpg"
]
}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```json {{ title: 'Response' }}
{
"media": {
"id": "65f3a2c8853cca45f4c9fd96",
"name": "c20391e0-b8a4-11e6-8836-fbdfd6956b31-mountain-sunset.png",
"original_name": "mountain-sunset.png",
"size": 457307,
"folder": "ai-generated",
"type": "image/png",
"bucket": "5839c67f0d3201c114000004",
"created_at": "2024-03-14T15:34:05.054Z",
"url": "https://cdn.cosmicjs.com/c20391e0-b8a4-11e6-8836-fbdfd6956b31-mountain-sunset.png",
"imgix_url": "https://imgix.cosmicjs.com/c20391e0-b8a4-11e6-8836-fbdfd6956b31-mountain-sunset.png",
"alt_text": "AI-generated mountain landscape at sunset",
"metadata": {
"caption": "Beautiful mountain vista",
"generated_by": "Cosmic AI"
}
},
"revised_prompt": "A serene mountain landscape at sunset with golden light illuminating the peaks, reflecting in a calm lake below, and wispy clouds catching the last rays of sunlight."
}
```
---
## Generate Video
This endpoint enables you to create AI-generated videos using Google's Veo 3.1 models with native audio generation.
The data request payload will need to be sent in JSON format with the `Content-Type: application/json` header set. Video generation is an asynchronous operation that typically takes 30-90 seconds.
**Content Policy:** Video generation will fail if the prompt contains references to real people (celebrities, public figures), copyrighted characters, or other policy-violating content. If you receive a "No videos generated" error, try rephrasing your prompt to avoid these elements.
### Required parameters
A detailed text description of the video you want to generate. More descriptive prompts yield better results.
### Optional parameters
The video generation model to use. Options: `veo-3.1-fast-generate-preview` (recommended, faster) or `veo-3.1-generate-preview` (premium quality). Defaults to `veo-3.1-fast-generate-preview`.
Video duration in seconds. Options: `4`, `6`, or `8`. Defaults to `8`.
Video resolution. Options: `720p` or `1080p`. Defaults to `720p`.
Array with 1 reference image URL to use as the first frame for video generation. Veo uses image-to-video mode to animate from this starting frame, ensuring precise control over the initial appearance, composition, and style. Ideal for product showcases, character consistency, and brand-accurate animations. Maximum 1 image.
Media folder to store the generated video in. (Folder must exist)
User-added JSON metadata for the generated video.
```js {{ title: 'Generate video' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
const videoResponse = await cosmic.ai.generateVideo({
prompt: 'A calico kitten playing with a ball of yarn in golden sunlight',
duration: 8,
resolution: '720p',
folder: 'ai-videos'
})
console.log(videoResponse.media.url)
console.log(videoResponse.usage)
```
```js {{ title: 'Premium quality video' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
const premiumVideo = await cosmic.ai.generateVideo({
prompt: 'Cinematic close-up of rain on window at night, city lights blurred',
model: 'veo-3.1-generate-preview', // Premium quality
duration: 8,
resolution: '1080p',
folder: 'premium-videos',
metadata: {
campaign: 'product-launch',
version: '1.0'
}
})
console.log(premiumVideo.media.url)
console.log(premiumVideo.generation_time_seconds)
```
```js {{ title: 'With reference images' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
const styledVideo = await cosmic.ai.generateVideo({
prompt: 'Elegant rotation revealing all product angles with soft lighting',
duration: 6,
reference_images: [
'https://cdn.cosmicjs.com/product-hero.jpg'
],
folder: 'product-videos',
metadata: {
product_id: 'prod_123',
campaign: 'launch-2024'
}
})
console.log(styledVideo.media.url)
console.log(`Generated in ${styledVideo.generation_time_seconds}s`)
```
```bash {{ title: 'cURL' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/video \
-d '{"prompt":"A serene mountain landscape with gentle wind","duration":8,"resolution":"720p"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```bash {{ title: 'cURL with options' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/video \
-d '{
"prompt":"Time-lapse of flower blooming with butterflies",
"model":"veo-3.1-fast-generate-preview",
"duration":8,
"resolution":"1080p",
"folder":"nature-videos"
}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```json {{ title: 'Response' }}
{
"media": {
"id": "65f8a3b2c4d5e6f7g8h9i0j1",
"name": "veo-a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.mp4",
"original_name": "veo-a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.mp4",
"size": 8450000,
"type": "video/mp4",
"bucket": "65a1b2c3d4e5f6g7h8i9j0k1",
"created_at": "2025-12-20T10:30:00.000Z",
"folder": "ai-videos",
"url": "https://cdn.cosmicjs.com/veo-xxx.mp4",
"imgix_url": "https://imgix.cosmicjs.com/veo-xxx.mp4",
"alt_text": "A calico kitten playing with a ball of yarn in golden sunlight",
"metadata": {
"duration": 8,
"resolution": "720p",
"generation_time_seconds": 45
}
},
"usage": {
"input_tokens": 288000,
"output_tokens": 0,
"total_tokens": 288000
},
"generation_time_seconds": 45
}
```
---
## Available Models
Cosmic supports a variety of AI models from Anthropic, Google Gemini, and OpenAI for text, image, video, and audio generation.
### Text Generation Models
#### Anthropic Claude Models
| Model | API Model ID | Description |
| ----------------- | ------------------------------- | ------------------------------------------------- |
| Claude Opus 4.8 | `claude-opus-4-8` | Most capable model, with improved judgment, honesty, and agentic reliability (recommended) |
| Claude Opus 4.7 | `claude-opus-4-7` | Previous flagship Opus model with 1M context, high-resolution vision, and task budgets |
| Claude Opus 4.6 | `claude-opus-4-6` | Previous flagship Opus model for agents and coding |
| Claude Opus 4.5 | `claude-opus-4-5-20251101` | Earlier flagship model with improved performance |
| Claude Opus 4.1 | `claude-opus-4-1-20250805` | Most powerful and capable model |
| Claude Opus 4 | `claude-opus-4-20250514` | Previous flagship model |
| Claude Sonnet 4.5 | `claude-sonnet-4-5-20250929` | High-performance model |
| Claude Sonnet 4 | `claude-sonnet-4-20250514` | High-performance model with exceptional reasoning |
| Claude Haiku 4.5 | `claude-haiku-4-5-20251001` | Fastest model with near-frontier intelligence |
#### Google Gemini Models
| Model | API Model ID | Description |
| --------------------------- | --------------------------------- | ------------------------------------------------------------ |
| Gemini 3.1 Pro | `gemini-3.1-pro-preview` | Google's most advanced model with improved reasoning, token efficiency, and agentic performance (recommended) |
| Gemini 3 Pro 🍌 | `gemini-3-pro-preview` | Google's previous flagship model with state-of-the-art reasoning |
| Gemini 3.1 Flash Image 🍌 | `gemini-3.1-flash-image-preview` | Fast, efficient image generation with 512px to 4K support, 14 aspect ratios, and up to 14 reference images (recommended) |
| Gemini 3 Pro Image 🍌 | `gemini-3-pro-image-preview` | Premium image generation for professional assets with up to 4K images |
| Veo 3.1 Fast 📹 | `veo-3.1-fast-generate-preview` | Fast video generation with native audio (recommended for most use cases) |
| Veo 3.1 Standard 📹 | `veo-3.1-generate-preview` | Premium video generation with exceptional quality and cinematic realism |
#### OpenAI GPT Models
| Model | API Model ID | Description |
| -------------- | -------------- | ------------------------------------------------------------ |
| GPT-5.2 Codex | `gpt-5.2-codex`| Most intelligent coding model for long-horizon, agentic coding tasks (recommended) |
| GPT-5.2 | `gpt-5.2` | Latest GPT-5 model with improved performance |
| GPT-5 | `gpt-5` | OpenAI's most advanced multimodal model |
| GPT-5 Mini | `gpt-5-mini` | Cost-effective GPT-5 variant |
| GPT-5 Nano | `gpt-5-nano` | Ultra-fast and cost-effective for simple tasks |
| GPT-4.1 | `gpt-4.1` | Enhanced coding and reasoning capabilities |
| GPT-4o | `gpt-4o` | Flagship multimodal model |
| o1 | `o1` | Advanced reasoning model for complex problems |
| o3 | `o3` | Latest reasoning model with improved performance |
#### Text Generation Model Selection
By default, Cosmic uses Claude Opus 4.8 for text generation. You can specify a different model by including the `model` parameter in your request:
```js
// Using Claude
const response = await cosmic.ai.generateText({
prompt: 'Write a product description',
model: 'claude-opus-4-8', // Optional: specify model
max_tokens: 500
})
// Using Gemini 3.1 Pro for agentic workflows
const geminiResponse = await cosmic.ai.generateText({
prompt: 'Analyze this content and suggest improvements',
model: 'gemini-3.1-pro-preview', // Use Gemini 3.1 Pro
max_tokens: 500
})
// Using GPT-5.2 Codex for coding tasks
const codexResponse = await cosmic.ai.generateText({
prompt: 'Write a React component that displays a blog post',
model: 'gpt-5.2-codex', // Use GPT-5.2 Codex
max_tokens: 2000
})
```
Or using cURL:
```bash
# Using Claude
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/text \
-d '{"prompt":"Write a product description","model":"claude-opus-4-8","max_tokens":500}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
# Using Gemini 3.1 Pro
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/text \
-d '{"prompt":"Analyze this content and suggest improvements","model":"gemini-3.1-pro-preview","max_tokens":500}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
# Using GPT-5.2 Codex
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/text \
-d '{"prompt":"Write a React component that displays a blog post","model":"gpt-5.2-codex","max_tokens":2000}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
### Image Generation Models
#### Google Gemini Image Models
| Model | API Model ID | Description | Supported Sizes | Aspect Ratios |
| --------------------------- | --------------------------------- | ------------------------------------------------------------ | --------------- | ------------- |
| Gemini 3.1 Flash Image 🍌 | `gemini-3.1-flash-image-preview` | Fast, efficient image generation (default, recommended) | 512x512, 1024x1024, 2048x2048, 4096x4096 | 14 ratios |
| Gemini 3 Pro Image 🍌 | `gemini-3-pro-image-preview` | Premium image generation for professional assets | 1024x1024, 2048x2048, 4096x4096 | 10 ratios |
**Flash Image supported aspect ratios:** 1:1, 1:4, 1:8, 2:3, 3:2, 3:4, 4:1, 4:3, 4:5, 5:4, 8:1, 9:16, 16:9, 21:9
**Pro Image supported aspect ratios:** 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9
#### OpenAI DALL-E Models
| Model | API Model ID | Description |
| --------- | ------------ | ---------------------------------------------- |
| DALL-E 3 | `dall-e-3` | OpenAI's latest image generation model |
#### Image Generation Model Selection
By default, Cosmic uses Gemini 3.1 Flash Image for image generation. You can explicitly specify the model by including the `model` parameter in your request.
**Gemini image models** support reference images for contextual generation. You can provide URLs to existing images, and Gemini will analyze their style, composition, and content to inform the generated image. This is perfect for:
- Maintaining consistent visual styles across generated images
- Creating variations based on existing artwork
- Applying the aesthetic of one image to a new scene
- Combining elements from multiple reference images
Flash Image supports up to 14 reference images (10 object + 4 character references), while Pro Image supports up to 5.
```js
// Using Gemini 3.1 Flash Image (default, recommended)
const flashResponse = await cosmic.ai.generateImage({
prompt: 'A futuristic cityscape at night with neon lights',
model: 'gemini-3.1-flash-image-preview',
size: '1024x1024',
aspect_ratio: '16:9'
})
// Using Flash Image with 512px for quick thumbnails
const thumbResponse = await cosmic.ai.generateImage({
prompt: 'Product icon for a note-taking app',
model: 'gemini-3.1-flash-image-preview',
size: '512x512'
})
// Using Gemini 3 Pro Image for premium 4K generation
const proResponse = await cosmic.ai.generateImage({
prompt: 'A futuristic cityscape at night with neon lights',
model: 'gemini-3-pro-image-preview',
size: '4096x4096'
})
// Using Gemini with reference images for style consistency
const styledResponse = await cosmic.ai.generateImage({
prompt: 'A mountain landscape in the same artistic style',
model: 'gemini-3.1-flash-image-preview',
reference_images: [
'https://cdn.cosmicjs.com/your-style-reference.jpg'
],
size: '2048x2048'
})
// Using DALL-E 3
const dalleResponse = await cosmic.ai.generateImage({
prompt: 'A futuristic cityscape at night',
model: 'dall-e-3',
size: '1792x1024',
quality: 'hd'
})
```
Or using cURL:
```bash
# Using Gemini 3.1 Flash Image (default)
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/image \
-d '{"prompt":"A futuristic cityscape at night","model":"gemini-3.1-flash-image-preview","size":"1024x1024","aspect_ratio":"16:9"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
# Using Gemini 3 Pro Image for 4K
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/image \
-d '{"prompt":"A futuristic cityscape at night","model":"gemini-3-pro-image-preview","size":"4096x4096"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
# Using DALL-E 3
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/image \
-d '{"prompt":"A futuristic cityscape at night","model":"dall-e-3","size":"1792x1024","quality":"hd"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
---
### Video Generation Models
#### Google Veo Models
| Model | API Model ID | Description |
| -------------- | ------------------------------- | ------------------------------------------------ |
| Veo 3.1 Fast | `veo-3.1-fast-generate-preview` | Faster generation, excellent quality (30-90s) |
| Veo 3.1 Standard | `veo-3.1-generate-preview` | Premium quality, cinematic realism (60-180s) |
#### Video Generation Model Selection
By default, Cosmic uses Veo 3.1 Fast for video generation. Both models support:
- **Native Audio**: Automatically generated audio that matches the scene
- **Flexible Durations**: 4, 6, or 8 seconds
- **High Resolution**: 720p or 1080p
- **Image-to-Video Mode**: Use 1 reference image as the starting frame
**Veo 3.1 Fast** is recommended for most use cases, offering excellent quality with faster generation times. Use **Veo 3.1 Standard** for premium marketing content and cinematic quality.
```js
// Using Veo Fast (recommended)
const fastVideo = await cosmic.ai.generateVideo({
prompt: 'A peaceful zen garden with koi fish swimming',
model: 'veo-3.1-fast-generate-preview',
duration: 8,
resolution: '720p'
})
// Using Veo Standard for premium quality
const premiumVideo = await cosmic.ai.generateVideo({
prompt: 'Cinematic shot of city skyline at golden hour',
model: 'veo-3.1-generate-preview',
duration: 8,
resolution: '1080p'
})
// Using reference image as starting frame (image-to-video)
const styledVideo = await cosmic.ai.generateVideo({
prompt: 'Product rotates smoothly revealing all angles',
model: 'veo-3.1-fast-generate-preview',
duration: 6,
reference_images: [
'https://cdn.cosmicjs.com/product-hero.jpg'
]
})
```
Or using cURL:
```bash
# Using Veo Fast
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/video \
-d '{"prompt":"A peaceful zen garden with koi fish","model":"veo-3.1-fast-generate-preview","duration":8}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
# Using Veo Standard for premium quality
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/video \
-d '{"prompt":"Cinematic city skyline at golden hour","model":"veo-3.1-generate-preview","duration":8,"resolution":"1080p"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
### Audio Generation Models
#### OpenAI TTS Models
| Model | API Model ID | Description | Voices |
| -------- | ------------ | ------------------------------------------------ | ------ |
| TTS Standard | `tts-1` | Fast, low-latency text-to-speech (recommended) | 9 |
| TTS HD | `tts-1-hd` | Higher quality audio (2x cost) | 9 |
#### Available Voices
**Feminine voices**
| Voice | Description | Best for |
| ---------- | ------------------------------------------------ | --------------------------------- |
| **nova** | Warm and bright, great for friendly narration (default) | Podcasts, explainers |
| shimmer | Soft and intimate, gentle delivery | Meditation, ASMR, bedtime stories |
| coral | Clear and polished, professional tone | Product demos, business content |
| sage | Calm and steady, thoughtful pacing | Education, tutorials |
| alloy | Neutral and balanced, versatile default | General purpose, articles |
**Masculine voices**
| Voice | Description | Best for |
| ------ | ------------------------------------------------ | ------------------------------------- |
| echo | Deep and authoritative, confident delivery | Announcements, trailers, news |
| onyx | Bold and commanding, strong presence | Intros, branding, dramatic reads |
| fable | Animated and expressive, natural storyteller | Storytelling, audiobooks |
| ash | Warm and approachable, conversational | Conversational, interviews |
#### Audio Generation Model Selection
By default, Cosmic uses `tts-1` with the `nova` voice. Texts longer than 4,096 characters are automatically split at paragraph boundaries and concatenated into a single audio file.
```js
// Using default voice (nova)
const audio = await cosmic.ai.generateAudio({
prompt: 'Welcome to our product walkthrough.',
})
// Using a specific voice and HD quality
const hdAudio = await cosmic.ai.generateAudio({
prompt: articleContent,
voice: 'sage',
model: 'tts-1-hd',
folder: 'podcasts'
})
```
Or using cURL:
```bash
# Using default settings
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/audio \
-d '{"prompt":"Welcome to our product walkthrough."}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
# Using HD model with specific voice
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/audio \
-d '{"prompt":"Your article text here...","voice":"sage","model":"tts-1-hd"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
---
### Using Reference Images with Video Generation (Image-to-Video Mode)
Veo 3.1 supports **image-to-video mode**, where you provide 1 reference image that becomes the first frame of your video. This ensures precise control over the starting appearance, composition, and style.
**What Image-to-Video Does:**
- **Precise Starting Frame**: Your reference image becomes the exact first frame of the video
- **Product Accuracy**: Start with your exact product photo and animate from there
- **Character Consistency**: Begin with a specific character pose or appearance
- **Brand Control**: Ensure videos start with approved brand imagery
**Best Practices:**
```js
// Product showcase starting from hero image
const productVideo = await cosmic.ai.generateVideo({
prompt: 'Product rotates smoothly, revealing all angles with studio lighting',
reference_images: [
'https://cdn.cosmicjs.com/product-hero-front.jpg'
],
duration: 8
})
// Character animation from specific pose
const characterVideo = await cosmic.ai.generateVideo({
prompt: 'Character waves and smiles at camera with friendly expression',
reference_images: [
'https://cdn.cosmicjs.com/character-neutral-pose.jpg'
],
duration: 6
})
// Brand scene animation
const brandVideo = await cosmic.ai.generateVideo({
prompt: 'Camera slowly zooms in while maintaining brand aesthetic',
reference_images: [
'https://cdn.cosmicjs.com/brand-scene-wide.jpg'
],
duration: 8
})
```
**Guidelines:**
- Use high-resolution images (1024x1024+ recommended)
- Only 1 reference image supported (becomes the first frame)
- Ensure URL is publicly accessible
- Your prompt should describe the motion/animation starting from that image
- Think of it as "how should this image come to life?"
### Advanced Veo 3.1 Capabilities
According to [Google's Veo 3.1 documentation](https://ai.google.dev/gemini-api/docs/video?example=dialogue), Veo 3.1 supports several advanced features:
#### ✅ Image-to-Video Mode
Use 1 reference image as the first frame of your video. Veo animates from this starting point with precise control over initial appearance. See examples above.
#### ✅ Video Extension
Extend previously generated videos to create longer content. See the **Extend Video** section below for full documentation.
---
## Extend Video
This endpoint enables you to extend a previously generated Veo video by creating a new 8-second clip that continues from the final second of the original video.
Video extension creates a new video that maintains visual continuity with the original. Only videos generated with Veo can be extended (they must have a `veo_file_uri` in their metadata). Extension is always 8 seconds at 720p resolution.
### Required parameters
A text description of how to continue the video. Should describe the motion/action that follows the original video.
The ID of the original Veo-generated video to extend. The video must have been generated using the Generate Video endpoint.
### Optional parameters
The video generation model to use. Options: `veo-3.1-fast-generate-preview` (recommended) or `veo-3.1-generate-preview`. Defaults to `veo-3.1-fast-generate-preview`.
Media folder to store the extended video in. (Folder must exist)
User-added JSON metadata for the extended video.
### Limitations
- **Duration**: Extensions are always 8 seconds
- **Resolution**: Extensions are always 720p (even if the original was 1080p)
- **Source**: Only Veo-generated videos can be extended (must have `veo_file_uri` in metadata)
- **Chaining**: Extended videos can also be extended, enabling creation of longer narratives
```js {{ title: 'Extend video' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
// First, generate an initial video
const initialVideo = await cosmic.ai.generateVideo({
prompt: 'A calico kitten sitting peacefully in golden sunlight',
duration: 8,
resolution: '720p'
})
console.log('Initial video ID:', initialVideo.media.id)
// Then extend it with a continuation
const extendedVideo = await cosmic.ai.extendVideo({
media_id: initialVideo.media.id,
prompt: 'The kitten stands up and walks away into the garden'
})
console.log('Extended video URL:', extendedVideo.media.url)
console.log('Source video ID:', extendedVideo.source_media_id)
```
```js {{ title: 'Chain multiple extensions' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
// Create a longer narrative by chaining extensions
const scene1 = await cosmic.ai.generateVideo({
prompt: 'Cinematic: A door slowly opens revealing a mysterious room',
duration: 8
})
const scene2 = await cosmic.ai.extendVideo({
media_id: scene1.media.id,
prompt: 'Camera slowly enters the room, revealing dusty furniture'
})
const scene3 = await cosmic.ai.extendVideo({
media_id: scene2.media.id,
prompt: 'A shaft of light illuminates an old photograph on the desk'
})
// Now you have 24 seconds of connected footage
console.log('Scene 1:', scene1.media.url)
console.log('Scene 2:', scene2.media.url)
console.log('Scene 3:', scene3.media.url)
```
```bash {{ title: 'cURL' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/video/extend \
-d '{"media_id":"65f8a3b2c4d5e6f7g8h9i0j1","prompt":"The scene continues with the character walking away"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```bash {{ title: 'cURL with options' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/video/extend \
-d '{
"media_id":"65f8a3b2c4d5e6f7g8h9i0j1",
"prompt":"Camera slowly pans to reveal the sunset",
"model":"veo-3.1-generate-preview",
"folder":"extended-videos",
"metadata":{
"project":"brand-story",
"scene":"3"
}
}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```json {{ title: 'Response' }}
{
"media": {
"id": "65f8b4c3d5e6f7g8h9i0j1k2",
"name": "veo-ext-a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.mp4",
"original_name": "veo-ext-a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.mp4",
"size": 8650000,
"type": "video/mp4",
"bucket": "65a1b2c3d4e5f6g7h8i9j0k1",
"created_at": "2025-12-20T10:35:00.000Z",
"folder": null,
"url": "https://cdn.cosmicjs.com/veo-ext-xxx.mp4",
"imgix_url": "https://imgix.cosmicjs.com/veo-ext-xxx.mp4",
"alt_text": "The scene continues with the character walking away",
"metadata": {
"duration": 8,
"resolution": "720p",
"generation_time_seconds": 52,
"is_extension": true,
"source_media_id": "65f8a3b2c4d5e6f7g8h9i0j1",
"veo_file_uri": "https://generativelanguage.googleapis.com/v1beta/files/..."
}
},
"usage": {
"input_tokens": 288000,
"output_tokens": 0,
"total_tokens": 288000
},
"generation_time_seconds": 52,
"source_media_id": "65f8a3b2c4d5e6f7g8h9i0j1",
"is_extension": true
}
```
### Video Extension Use Cases
**Creating Longer Narratives**
Chain multiple 8-second extensions to create minute-long videos or longer stories:
```js
// Build a 32-second video (4 segments)
let currentVideo = await cosmic.ai.generateVideo({
prompt: 'Opening scene: sunrise over mountains',
duration: 8
})
const segments = [currentVideo]
for (const continuation of [
'Birds take flight from the trees below',
'A hiker appears on the trail in the distance',
'Close-up of the hiker reaching the summit'
]) {
currentVideo = await cosmic.ai.extendVideo({
media_id: currentVideo.media.id,
prompt: continuation
})
segments.push(currentVideo)
}
console.log(`Created ${segments.length} connected segments (${segments.length * 8}s total)`)
```
**Extending Product Showcases**
Continue product demonstrations with smooth transitions:
```js
const productIntro = await cosmic.ai.generateVideo({
prompt: 'Product slowly rotates on white background',
reference_images: ['https://cdn.cosmicjs.com/product.jpg'],
duration: 8
})
const productDetails = await cosmic.ai.extendVideo({
media_id: productIntro.media.id,
prompt: 'Camera zooms in to show product texture and details'
})
```
**Building Background Loops**
Create longer ambient footage for websites or presentations:
```js
const ambientBase = await cosmic.ai.generateVideo({
prompt: 'Gentle rain falling on window with city lights blurred behind',
duration: 8
})
const ambientExtended = await cosmic.ai.extendVideo({
media_id: ambientBase.media.id,
prompt: 'Rain continues with occasional lightning flash in the distance'
})
```
---
## Generate Audio
This endpoint converts text to natural-sounding speech using OpenAI's text-to-speech models. The generated audio is automatically uploaded to your Cosmic media library as an MP3 file.
The data request payload will need to be sent in JSON format with the `Content-Type: application/json` header set. Texts longer than 4,096 characters are automatically chunked at paragraph boundaries and concatenated into a single audio file.
### Required parameters
The text to convert to speech. Can be any length; texts over 4,096 characters are automatically split and processed in chunks.
### Optional parameters
Voice to use for speech generation. Feminine: `nova` (default), `shimmer`, `coral`, `sage`, `alloy`. Masculine: `echo`, `onyx`, `fable`, `ash`.
TTS model to use: `tts-1` (default, optimized for speed) or `tts-1-hd` (higher quality, 2x cost).
Media folder to store the generated audio in. (Folder must exist)
User-added JSON metadata for the audio file.
```js {{ title: 'SDK' }}
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY',
writeKey: 'BUCKET_WRITE_KEY'
})
const audio = await cosmic.ai.generateAudio({
prompt: 'Welcome to our podcast. Today we explore the future of AI-powered content management.',
voice: 'nova'
})
```
```js {{ title: 'SDK with options' }}
const audio = await cosmic.ai.generateAudio({
prompt: articleContent,
voice: 'sage',
model: 'tts-1-hd',
folder: 'podcasts',
metadata: {
episode: 42,
topic: 'AI content management'
}
})
```
```bash {{ title: 'cURL' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/audio \
-d '{"prompt":"Welcome to our podcast.","voice":"nova"}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```bash {{ title: 'cURL with options' }}
curl https://workers.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/ai/audio \
-d '{
"prompt":"Your full article text here...",
"voice":"sage",
"model":"tts-1-hd",
"folder":"podcasts"
}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer {BUCKET_WRITE_KEY}"
```
```json {{ title: 'Response' }}
{
"media": {
"id": "65f8c5d4e6f7g8h9i0j1k2l3",
"name": "tts-a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.mp3",
"original_name": "tts-a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.mp3",
"size": 245000,
"type": "audio/mpeg",
"bucket": "65a1b2c3d4e5f6g7h8i9j0k1",
"created_at": "2026-02-21T15:30:00.000Z",
"folder": null,
"url": "https://cdn.cosmicjs.com/tts-xxx.mp3",
"imgix_url": "https://imgix.cosmicjs.com/tts-xxx.mp3",
"alt_text": "Welcome to our podcast...",
"metadata": {
"prompt": "Welcome to our podcast...",
"model": "tts-1",
"voice": "nova",
"duration_estimate": "1 min",
"char_count": 82,
"chunk_count": 1
}
},
"usage": {
"input_tokens": 21,
"output_tokens": 3600,
"total_tokens": 3621
}
}
```
---
## Usage and Limitations
AI capabilities in Cosmic are subject to the following considerations:
- **Rate Limits**: AI generation requests may be subject to rate limiting based on your plan.
- **Token Usage**: Text, image, video, and audio generation consume tokens. Media generation (images, videos, and audio) has higher token costs due to computational requirements.
- **Media Storage**: Generated images and videos are stored in your Cosmic Bucket's media library and count toward your storage quota.
- **Video Generation Time**: Video generation is asynchronous and typically takes 30-90 seconds (Fast) or 60-180 seconds (Standard).
- **Content Policy**: Generated content must comply with Cosmic's terms of service and content policies. Video generation will fail without a specific error message if the prompt violates content policies (e.g., celebrity likeness, copyrighted material, or safety concerns). If you receive a "No videos generated" error, try rephrasing your prompt to avoid references to real people, brands, or copyrighted characters.
- **Regional Restrictions**: In EU, UK, CH, MENA regions, person generation has limitations (see [Google's documentation](https://ai.google.dev/gemini-api/docs/video?example=dialogue) for details).
- **Watermarking**: Videos created by Veo are watermarked using SynthID for AI-generated content identification.
### Pricing Overview
All AI features consume tokens from your monthly allocation or token packs. Token costs vary by model complexity and media type.
#### Text Generation Pricing
Text generation uses tiered pricing based on model capability. More powerful models cost more tokens to use, reflecting their higher computational requirements and superior performance.
**How Token Multipliers Work:** Your actual token deduction is multiplied by the tier multiplier:
| Tier | Multiplier | Models | Token Deduction |
|------|------------|--------|-----------------|
| **Budget** | 1.0x | GPT-5 Nano, GPT-4.1 Nano, GPT-4o Mini, GPT-5 Mini, GPT-4.1 Mini, Claude Haiku 3, Claude Haiku 4.5 | 1,000 actual tokens = 1,000 deducted |
| **Standard** | 2.0x | GPT-5, GPT-5.2, GPT-4.1, GPT-4o, o1-mini, o3, o3-mini, o4-mini, Claude Sonnet 4, Claude Sonnet 4.5, Claude Opus 4.5, Claude Opus 4.6, Claude Opus 4.7, Claude Opus 4.8, Gemini 3 Pro | 1,000 actual tokens = 2,000 deducted |
| **Premium** | 4.0x | Claude Opus 4, Claude Opus 4.1, o1, o3-pro | 1,000 actual tokens = 4,000 deducted |
**Example:** Using Claude Opus 4.8 (Standard tier) with a 1,000 token response will deduct 2,000 tokens from your balance (1,000 × 2.0x).
#### Media Generation Pricing
Images and videos use fixed token costs. **All media generation costs are billed as output tokens**.
| Feature | Token Cost (Output) |
|---------|------------|
| **DALL-E 3 Image** | 4,800 tokens |
| **Gemini 1K/2K Image** | 32,160 tokens |
| **Gemini 4K Image** | 57,600 tokens |
| **Veo Fast Video (4s)** | 144,000 tokens |
| **Veo Fast Video (6s)** | 216,000 tokens |
| **Veo Fast Video (8s)** | 288,000 tokens |
| **Veo Fast Extension** | 288,000 tokens |
| **Veo Standard Video (4s)** | 384,000 tokens |
| **Veo Standard Video (6s)** | 576,000 tokens |
| **Veo Standard Video (8s)** | 768,000 tokens |
| **Veo Standard Extension** | 768,000 tokens |
| **TTS Audio (per 1K chars)** | 3,600 tokens |
| **TTS HD Audio (per 1K chars)** | 7,200 tokens |
**Note:** Input tokens (your prompt) for media generation are minimal compared to the output cost. Audio generation tokens scale proportionally with text length. The token costs listed above represent the generation cost and are deducted from your output token allocation.
For more information about AI capabilities and pricing, please refer to the [Cosmic pricing page](https://www.cosmicjs.com/pricing) or [contact Cosmic support](https://www.cosmicjs.com/contact).
---
# Queries
Learn about queries; the way to fetch content from your Cosmic Bucket.
### Prerequisite
The following references assume you have already reviewed the methods for fetching [Objects](/docs/api/objects) and [media](/docs/api/media) from your Bucket.
### Queries in the browser URL
If accessing the endpoint via browser address bar, open and closed curly
braces will need to be encoded: `%7B` and `%7D` respectively. [This encoder
tool may help](https://meyerweb.com/eric/tools/dencoder/).
## Object properties
You can compose queries to search by the following Object properties.
| Parameter | Description |
| :-------------- | :------------------------- |
| `id` | Object id |
| `title` | Object title |
| `slug` | Object slug |
| `type` | Object type Slug |
| `locale` | Object locale |
| `created_at` | Object created at date |
| `published_at` | Object published at date |
| `modified_at` | Object modified at date |
| `created_by` | Object created by user id |
| `modified_by` | Object modified by user id |
| `assigned_to` | Object assigned to user id |
| `metadata.$key` | Metadata value(s) |
## Media properties
Construct queries to search by the following media properties.
| Parameter | Description |
| :-------------- | :-------------------- |
| `id` | Media id |
| `name` | Media name |
| `original_name` | Media original name |
| `size` | Media size |
| `type` | Media type |
| `created` | Media created date |
| `folder` | Media folder |
| `metadata` | Media metadata (JSON) |
## Selectors
Use the following selectors to build your queries.
| Parameter | Description |
| --------- | ---------------------------------------------------------------------------- |
| `$eq` | Matches values that are equal to a specified value. Default key/value query. |
| `$gt` | Matches values that are greater than a specified value. |
| `$gte` | Matches values that are greater than or equal to a specified value. |
| `$lt` | Matches values that are less than a specified value. |
| `$lte` | Matches values that are less than or equal to a specified value. |
| `$in` | Matches **any** of the values specified in an array. |
| `$all` | Matches **all** of the values specified in an array. |
| `$ne` | Matches all values that are not equal to a specified value. |
| `$nin` | Matches none of the values specified in an array. |
## Evaluation
| Parameter | Description |
| -------------------- | -------------------------------------------------------------------- |
| `$regex`, `$options` | Search for string, use `$options: "i"` for case insensitive matches. |
## Logic Operators
| Parameter | Description |
| --------- | ------------------------------------------------------------------- |
| `$and` | Returns results that match all of the query conditions. |
| `$not` | Returns results that do not match the query expression. |
| `$or` | Returns results that match any of the specified conditions. |
| `$nor` | Returns results that fail to match any of the specified conditions. |
## Basic examples
The following examples use the NPM module and assume you have an understaning of [authentication](/docs/api/authentication).
A basic query may be when you want to fetch Objects in a certain type. For example, blog posts:
```js
const query = {
type: 'posts',
};
await cosmic.objects.find(query);
```
You can also use queries to fetch media.
```js
const query = {
type: 'video/mp4', // fetch all video files
};
await cosmic.media.find(query);
```
## Advanced examples
Let's say you want to fetch only blog posts with a certain text metafield by a key and value:
```js
const query = {
type: 'posts',
'metadata.some_unique_key': 'some-unique-value',
};
await cosmic.objects.find(query);
```
Let's say you want to fetch only blog posts from a certain category set by a single Object relationship metafield:
```js
const query = {
type: 'posts',
'metadata.category': 'category-object-id', // The category Object id
};
await cosmic.objects.find(query);
```
When querying using an Object Metafield, make sure you query by the Object
`id` not the `slug`.
Let's say you want to fetch products that have a `price` (Number Metafield) less than `100`:
```js
const query = {
type: 'products',
'metadata.price': {
$lt: 100,
},
};
await cosmic.objects.find(query);
```
Let's say you want to fetch products that have any of a certain set of `tags` (select dropdown Metafield):
```js
const query = {
type: 'products',
'metadata.tags': {
$in: ['Clothing', 'Menswear'],
},
};
await cosmic.objects.find(query);
```
Let's say you want to fetch blog posts assigned to one of a set of users (by user `id`) using the `assigned_to` property:
```js
const query = {
type: 'posts',
assigned_to: {
$in: ['user-id-1', 'user-id-2'],
},
};
await cosmic.objects.find(query);
```
Let's say you want to fetch products that match a combination of values using the `$and` logic operator.
```js
const query = {
type: 'products',
$and: [
{
'metadata.category': 'Tshirt',
},
{
'metadata.price': {
$lte: 29,
},
},
],
};
await cosmic.objects.find(query);
```
Using the `$regex` method we can create a search feature that searches Objects by `title`.
```js
const query = {
type: 'products',
title: {
$regex: 'Hoodie',
$options: 'i', // case insensitive
},
};
await cosmic.objects.find(query);
```
### More query info
**Want more information?** Cosmic queries follow MongoDB methods of comparison
and logical operators. See further documentation and more examples in the
[MongoDB
docs](https://docs.mongodb.com/manual/reference/operator/query/index.html).
---
# Webhooks
Learn about webhooks; used to create automation workflows when you create, update, and delete content using the Cosmic dashboard and API.
## Creating webhooks
Go to Bucket Settings > Webhooks to create a new webhook. Give your webhook a URL, title, properties to return, custom headers, and select the events you want to listen for on a given resource. See the [dashboard reference for webhooks](/docs/dashboard/buckets#webhooks) for more information on creating webhooks in the dashboard.
When webhooks are activated, whenever an event happens in the dashboard or API, a webhook is sent by Cosmic to the indicated URL as a `POST` request. See section below for possible event types and payload example.
---
## The webhook model
The webhook response model contains all the information about the webhook response.
### Properties
The resource that received the action.
Options `objects | media`
The event that occured.
Options `created | edited | deleted`
The time the event was triggered (in UTC milliseconds).
The payload that you define in the dashboard using `props`. Optional.
---
## Consuming webhooks
When your app receives a webhook request from Cosmic, check the `resource` and `event` property to see what event occured.
### Using props
You can specify which `props` you would like to include in the `data` property (if
any). For example, this is the payload you would receive when a new object is created
and published with the `props` of `slug,title,type,status,metadata` included.
```json {{ 'title': 'Example payload' }}
{
"resource": "objects",
"event": "created",
"triggered_at": 1576861549889,
"data": {
"object": {
"slug": "cosmic-webhooks-rock",
"title": "Cosmic webhooks rock",
"type": "blog-posts",
"status": "published",
"metadata": {
"content": "Cosmic webhooks enable me to communicate with third-party APIs automatically when I update content in my Cosmic Bucket, sweet!
",
"headline": "Cosmic webhooks are AMAZING!",
"emoji": "🚀"
}
}
}
}
```
---
## Custom headers
You can also include custom headers to send any custom information, or for an added layer of security. For example, when verifying the request using a secret key.
```js
const secret = req.headers['super-secret-key'];
if (secret === process.env.SUPER_SECRET_KEY) {
// Request is verified
} else {
// Request could not be verified
}
```
If the `super-secret-key` value in the custom header you created matches the one in your environment variable you can be sure that the request was truly coming from Cosmic.
## Testing webhooks
You can use a service like [Beeceptor](https://beeceptor.com/) to test your webhooks and view response data.
---
# Localization
Learn how to add localization to your Cosmic content.
For a reference on how to add localization to your Object types in your Bucket dashboard, see the [dashboard documentation on localization](/docs/dashboard/buckets#localization).
---
## Get localized Objects
This endpoint enables you to retrieve a list of your Objects by `locale` by indicating the Objects `type` and `locale` in the `query` parameter.
### Required parameters
A localization key. See the [available locales](#available-locales).
See the [Objects API reference](/docs/api/objects) for more querying references.
```js
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: 'BUCKET_SLUG',
readKey: 'BUCKET_READ_KEY'
})
await cosmic.objects.find({
type: 'posts',
locale: 'es' // Get all posts in Spanish
}).props([
'slug',
'title',
'metadata.content',
])
```
```bash {{ title: 'cURL' }}
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects \
-d read_key=${BUCKET_READ_KEY} \
--data-urlencode query='{"type":"posts","locale":"es"}' \
-d props=slug,title,metadata.content \
-G
```
```json {{ title: 'Response' }}
{
"objects": [
{
"slug": "aprendiendo",
"title": "Aprendiendo",
"metadata": {
"content": "¡Es divertido aprender!
"
}
}
],
"total": 6,
"limit": 1
}
```
---
## Available locales
The following are the available locales that can be used to localize your Objects.
| Code | Title |
| :---------- | :--------------------------------------------: |
| af-NA | Afrikaans (Namibia) |
| af-ZA | Afrikaans (South Africa) |
| af | Afrikaans |
| ak-GH | Akan (Ghana) |
| ak | Akan |
| sq-AL | Albanian (Albania) |
| sq | Albanian |
| am-ET | Amharic (Ethiopia) |
| am | Amharic |
| ar-DZ | Arabic (Algeria) |
| ar-BH | Arabic (Bahrain) |
| ar-EG | Arabic (Egypt) |
| ar-IQ | Arabic (Iraq) |
| ar-JO | Arabic (Jordan) |
| ar-KW | Arabic (Kuwait) |
| ar-LB | Arabic (Lebanon) |
| ar-LY | Arabic (Libya) |
| ar-MA | Arabic (Morocco) |
| ar-OM | Arabic (Oman) |
| ar-QA | Arabic (Qatar) |
| ar-SA | Arabic (Saudi Arabia) |
| ar-SD | Arabic (Sudan) |
| ar-SY | Arabic (Syria) |
| ar-TN | Arabic (Tunisia) |
| ar-AE | Arabic (United Arab Emirates) |
| ar-YE | Arabic (Yemen) |
| ar | Arabic |
| hy-AM | Armenian (Armenia) |
| hy | Armenian |
| as-IN | Assamese (India) |
| as | Assamese |
| asa-TZ | Asu (Tanzania) |
| asa | Asu |
| az-Cyrl | Azerbaijani (Cyrillic) |
| az-Cyrl-AZ | Azerbaijani (Cyrillic, Azerbaijan) |
| az-Latn | Azerbaijani (Latin) |
| az-Latn-AZ | Azerbaijani (Latin, Azerbaijan) |
| az | Azerbaijani |
| bm-ML | Bambara (Mali) |
| bm | Bambara |
| eu-ES | Basque (Spain) |
| eu | Basque |
| be-BY | Belarusian (Belarus) |
| be | Belarusian |
| bem-ZM | Bemba (Zambia) |
| bem | Bemba |
| bez-TZ | Bena (Tanzania) |
| bez | Bena |
| bn-BD | Bengali (Bangladesh) |
| bn-IN | Bengali (India) |
| bn | Bengali |
| bs-BA | Bosnian (Bosnia and Herzegovina) |
| bs | Bosnian |
| bg-BG | Bulgarian (Bulgaria) |
| bg | Bulgarian |
| my-MM | Burmese (Myanmar [Burma]) |
| my | Burmese |
| ca-ES | Catalan (Spain) |
| ca | Catalan |
| tzm-Latn | Central Morocco Tamazight (Latin) |
| tzm-Latn-MA | Central Morocco Tamazight (Latin, Morocco) |
| tzm | Central Morocco Tamazight |
| chr-US | Cherokee (United States) |
| chr | Cherokee |
| cgg-UG | Chiga (Uganda) |
| cgg | Chiga |
| zh-Hans | Chinese (Simplified Han) |
| zh-Hans-CN | Chinese (Simplified Han, China) |
| zh-Hans-HK | Chinese (Simplified Han, Hong Kong SAR China) |
| zh-Hans-MO | Chinese (Simplified Han, Macau SAR China) |
| zh-Hans-SG | Chinese (Simplified Han, Singapore) |
| zh-Hant | Chinese (Traditional Han) |
| zh-Hant-HK | Chinese (Traditional Han, Hong Kong SAR China) |
| zh-Hant-MO | Chinese (Traditional Han, Macau SAR China) |
| zh-Hant-TW | Chinese (Traditional Han, Taiwan) |
| zh | Chinese |
| kw-GB | Cornish (United Kingdom) |
| kw | Cornish |
| hr-HR | Croatian (Croatia) |
| hr | Croatian |
| cs-CZ | Czech (Czech Republic) |
| cs | Czech |
| da-DK | Danish (Denmark) |
| da | Danish |
| nl-BE | Dutch (Belgium) |
| nl-NL | Dutch (Netherlands) |
| nl | Dutch |
| ebu-KE | Embu (Kenya) |
| ebu | Embu |
| en-AS | English (American Samoa) |
| en-AU | English (Australia) |
| en-BE | English (Belgium) |
| en-BZ | English (Belize) |
| en-BW | English (Botswana) |
| en-CA | English (Canada) |
| en-GU | English (Guam) |
| en-HK | English (Hong Kong SAR China) |
| en-IN | English (India) |
| en-IE | English (Ireland) |
| en-JM | English (Jamaica) |
| en-MT | English (Malta) |
| en-MH | English (Marshall Islands) |
| en-MU | English (Mauritius) |
| en-NA | English (Namibia) |
| en-NZ | English (New Zealand) |
| en-MP | English (Northern Mariana Islands) |
| en-PK | English (Pakistan) |
| en-PH | English (Philippines) |
| en-SG | English (Singapore) |
| en-ZA | English (South Africa) |
| en-TT | English (Trinidad and Tobago) |
| en-UM | English (U.S. Minor Outlying Islands) |
| en-VI | English (U.S. Virgin Islands) |
| en-GB | English (United Kingdom) |
| en-US | English (United States) |
| en-ZW | English (Zimbabwe) |
| en | English |
| eo | Esperanto |
| et-EE | Estonian (Estonia) |
| et | Estonian |
| ee-GH | Ewe (Ghana) |
| ee-TG | Ewe (Togo) |
| ee | Ewe |
| fo-FO | Faroese (Faroe Islands) |
| fo | Faroese |
| fil-PH | Filipino (Philippines) |
| fil | Filipino |
| fi-FI | Finnish (Finland) |
| fi | Finnish |
| fr-BE | French (Belgium) |
| fr-BJ | French (Benin) |
| fr-BF | French (Burkina Faso) |
| fr-BI | French (Burundi) |
| fr-CM | French (Cameroon) |
| fr-CA | French (Canada) |
| fr-CF | French (Central African Republic) |
| fr-TD | French (Chad) |
| fr-KM | French (Comoros) |
| fr-CG | French (Congo - Brazzaville) |
| fr-CD | French (Congo - Kinshasa) |
| fr-CI | French (Côte d’Ivoire) |
| fr-DJ | French (Djibouti) |
| fr-GQ | French (Equatorial Guinea) |
| fr-FR | French (France) |
| fr-GA | French (Gabon) |
| fr-GP | French (Guadeloupe) |
| fr-GN | French (Guinea) |
| fr-LU | French (Luxembourg) |
| fr-MG | French (Madagascar) |
| fr-ML | French (Mali) |
| fr-MQ | French (Martinique) |
| fr-MC | French (Monaco) |
| fr-NE | French (Niger) |
| fr-RW | French (Rwanda) |
| fr-RE | French (Réunion) |
| fr-BL | French (Saint Barthélemy) |
| fr-MF | French (Saint Martin) |
| fr-SN | French (Senegal) |
| fr-CH | French (Switzerland) |
| fr-TG | French (Togo) |
| fr | French |
| ff-SN | Fulah (Senegal) |
| ff | Fulah |
| gl-ES | Galician (Spain) |
| gl | Galician |
| lg-UG | Ganda (Uganda) |
| lg | Ganda |
| ka-GE | Georgian (Georgia) |
| ka | Georgian |
| de-AT | German (Austria) |
| de-BE | German (Belgium) |
| de-DE | German (Germany) |
| de-LI | German (Liechtenstein) |
| de-LU | German (Luxembourg) |
| de-CH | German (Switzerland) |
| de | German |
| el-CY | Greek (Cyprus) |
| el-GR | Greek (Greece) |
| el | Greek |
| gu-IN | Gujarati (India) |
| gu | Gujarati |
| guz-KE | Gusii (Kenya) |
| guz | Gusii |
| ha-Latn | Hausa (Latin) |
| ha-Latn-GH | Hausa (Latin, Ghana) |
| ha-Latn-NE | Hausa (Latin, Niger) |
| ha-Latn-NG | Hausa (Latin, Nigeria) |
| ha | Hausa |
| haw-US | Hawaiian (United States) |
| haw | Hawaiian |
| he-IL | Hebrew (Israel) |
| he | Hebrew |
| hi-IN | Hindi (India) |
| hi | Hindi |
| hu-HU | Hungarian (Hungary) |
| hu | Hungarian |
| is-IS | Icelandic (Iceland) |
| is | Icelandic |
| ig-NG | Igbo (Nigeria) |
| ig | Igbo |
| id-ID | Indonesian (Indonesia) |
| id | Indonesian |
| ga-IE | Irish (Ireland) |
| ga | Irish |
| it-IT | Italian (Italy) |
| it-CH | Italian (Switzerland) |
| it | Italian |
| ja-JP | Japanese (Japan) |
| ja | Japanese |
| kea-CV | Kabuverdianu (Cape Verde) |
| kea | Kabuverdianu |
| kab-DZ | Kabyle (Algeria) |
| kab | Kabyle |
| kl-GL | Kalaallisut (Greenland) |
| kl | Kalaallisut |
| kln-KE | Kalenjin (Kenya) |
| kln | Kalenjin |
| kam-KE | Kamba (Kenya) |
| kam | Kamba |
| kn-IN | Kannada (India) |
| kn | Kannada |
| kk-Cyrl | Kazakh (Cyrillic) |
| kk-Cyrl-KZ | Kazakh (Cyrillic, Kazakhstan) |
| kk | Kazakh |
| km-KH | Khmer (Cambodia) |
| km | Khmer |
| ki-KE | Kikuyu (Kenya) |
| ki | Kikuyu |
| rw-RW | Kinyarwanda (Rwanda) |
| rw | Kinyarwanda |
| kok-IN | Konkani (India) |
| kok | Konkani |
| ko-KR | Korean (South Korea) |
| ko | Korean |
| khq-ML | Koyra Chiini (Mali) |
| khq | Koyra Chiini |
| ses-ML | Koyraboro Senni (Mali) |
| ses | Koyraboro Senni |
| lag-TZ | Langi (Tanzania) |
| lag | Langi |
| lv-LV | Latvian (Latvia) |
| lv | Latvian |
| lt-LT | Lithuanian (Lithuania) |
| lt | Lithuanian |
| luo-KE | Luo (Kenya) |
| luo | Luo |
| luy-KE | Luyia (Kenya) |
| luy | Luyia |
| mk-MK | Macedonian (Macedonia) |
| mk | Macedonian |
| jmc-TZ | Machame (Tanzania) |
| jmc | Machame |
| kde-TZ | Makonde (Tanzania) |
| kde | Makonde |
| mg-MG | Malagasy (Madagascar) |
| mg | Malagasy |
| ms-BN | Malay (Brunei) |
| ms-MY | Malay (Malaysia) |
| ms | Malay |
| ml-IN | Malayalam (India) |
| ml | Malayalam |
| mt-MT | Maltese (Malta) |
| mt | Maltese |
| gv-GB | Manx (United Kingdom) |
| gv | Manx |
| mr-IN | Marathi (India) |
| mr | Marathi |
| mas-KE | Masai (Kenya) |
| mas-TZ | Masai (Tanzania) |
| mas | Masai |
| mer-KE | Meru (Kenya) |
| mer | Meru |
| mn | Mongolian |
| mfe-MU | Morisyen (Mauritius) |
| mfe | Morisyen |
| naq-NA | Nama (Namibia) |
| naq | Nama |
| ne-IN | Nepali (India) |
| ne-NP | Nepali (Nepal) |
| ne | Nepali |
| nd-ZW | North Ndebele (Zimbabwe) |
| nd | North Ndebele |
| nb-NO | Norwegian Bokmål (Norway) |
| nb | Norwegian Bokmål |
| nn-NO | Norwegian Nynorsk (Norway) |
| nn | Norwegian Nynorsk |
| nyn-UG | Nyankole (Uganda) |
| nyn | Nyankole |
| or-IN | Oriya (India) |
| or | Oriya |
| om-ET | Oromo (Ethiopia) |
| om-KE | Oromo (Kenya) |
| om | Oromo |
| ps-AF | Pashto (Afghanistan) |
| ps | Pashto |
| fa-AF | Persian (Afghanistan) |
| fa-IR | Persian (Iran) |
| fa | Persian |
| pl-PL | Polish (Poland) |
| pl | Polish |
| pt-BR | Portuguese (Brazil) |
| pt-GW | Portuguese (Guinea-Bissau) |
| pt-MZ | Portuguese (Mozambique) |
| pt-PT | Portuguese (Portugal) |
| pt | Portuguese |
| pa-Arab | Punjabi (Arabic) |
| pa-Arab-PK | Punjabi (Arabic, Pakistan) |
| pa-Guru | Punjabi (Gurmukhi) |
| pa-Guru-IN | Punjabi (Gurmukhi, India) |
| pa | Punjabi |
| ro-MD | Romanian (Moldova) |
| ro-RO | Romanian (Romania) |
| ro | Romanian |
| rm-CH | Romansh (Switzerland) |
| rm | Romansh |
| rof-TZ | Rombo (Tanzania) |
| rof | Rombo |
| ru-MD | Russian (Moldova) |
| ru-RU | Russian (Russia) |
| ru-UA | Russian (Ukraine) |
| ru | Russian |
| rwk-TZ | Rwa (Tanzania) |
| rwk | Rwa |
| saq-KE | Samburu (Kenya) |
| saq | Samburu |
| sg-CF | Sango (Central African Republic) |
| sg | Sango |
| seh-MZ | Sena (Mozambique) |
| seh | Sena |
| sr-Cyrl | Serbian (Cyrillic) |
| sr-Cyrl-BA | Serbian (Cyrillic, Bosnia and Herzegovina) |
| sr-Cyrl-ME | Serbian (Cyrillic, Montenegro) |
| sr-Cyrl-RS | Serbian (Cyrillic, Serbia) |
| sr-Latn | Serbian (Latin) |
| sr-Latn-BA | Serbian (Latin, Bosnia and Herzegovina) |
| sr-Latn-ME | Serbian (Latin, Montenegro) |
| sr-Latn-RS | Serbian (Latin, Serbia) |
| sr | Serbian |
| sn-ZW | Shona (Zimbabwe) |
| sn | Shona |
| ii-CN | Sichuan Yi (China) |
| ii | Sichuan Yi |
| si-LK | Sinhala (Sri Lanka) |
| si | Sinhala |
| sk-SK | Slovak (Slovakia) |
| sk | Slovak |
| sl-SI | Slovenian (Slovenia) |
| sl | Slovenian |
| xog-UG | Soga (Uganda) |
| xog | Soga |
| so-DJ | Somali (Djibouti) |
| so-ET | Somali (Ethiopia) |
| so-KE | Somali (Kenya) |
| so-SO | Somali (Somalia) |
| so | Somali |
| es-AR | Spanish (Argentina) |
| es-BO | Spanish (Bolivia) |
| es-CL | Spanish (Chile) |
| es-CO | Spanish (Colombia) |
| es-CR | Spanish (Costa Rica) |
| es-DO | Spanish (Dominican Republic) |
| es-EC | Spanish (Ecuador) |
| es-SV | Spanish (El Salvador) |
| es-GQ | Spanish (Equatorial Guinea) |
| es-GT | Spanish (Guatemala) |
| es-HN | Spanish (Honduras) |
| es-419 | Spanish (Latin America) |
| es-MX | Spanish (Mexico) |
| es-NI | Spanish (Nicaragua) |
| es-PA | Spanish (Panama) |
| es-PY | Spanish (Paraguay) |
| es-PE | Spanish (Peru) |
| es-PR | Spanish (Puerto Rico) |
| es-ES | Spanish (Spain) |
| es-US | Spanish (United States) |
| es-UY | Spanish (Uruguay) |
| es-VE | Spanish (Venezuela) |
| es | Spanish |
| sw-KE | Swahili (Kenya) |
| sw-TZ | Swahili (Tanzania) |
| sw | Swahili |
| sv-FI | Swedish (Finland) |
| sv-SE | Swedish (Sweden) |
| sv | Swedish |
| gsw-CH | Swiss German (Switzerland) |
| gsw | Swiss German |
| shi-Latn | Tachelhit (Latin) |
| shi-Latn-MA | Tachelhit (Latin, Morocco) |
| shi-Tfng | Tachelhit (Tifinagh) |
| shi-Tfng-MA | Tachelhit (Tifinagh, Morocco) |
| shi | Tachelhit |
| dav-KE | Taita (Kenya) |
| dav | Taita |
| ta-IN | Tamil (India) |
| ta-LK | Tamil (Sri Lanka) |
| ta | Tamil |
| te-IN | Telugu (India) |
| te | Telugu |
| teo-KE | Teso (Kenya) |
| teo-UG | Teso (Uganda) |
| teo | Teso |
| th-TH | Thai (Thailand) |
| th | Thai |
| bo-CN | Tibetan (China) |
| bo-IN | Tibetan (India) |
| bo | Tibetan |
| ti-ER | Tigrinya (Eritrea) |
| ti-ET | Tigrinya (Ethiopia) |
| ti | Tigrinya |
| to-TO | Tonga (Tonga) |
| to | Tonga |
| tr-TR | Turkish (Turkey) |
| tr | Turkish |
| uk-UA | Ukrainian (Ukraine) |
| uk | Ukrainian |
| ur-IN | Urdu (India) |
| ur-PK | Urdu (Pakistan) |
| ur | Urdu |
| uz-Arab | Uzbek (Arabic) |
| uz-Arab-AF | Uzbek (Arabic, Afghanistan) |
| uz-Cyrl | Uzbek (Cyrillic) |
| uz-Cyrl-UZ | Uzbek (Cyrillic, Uzbekistan) |
| uz-Latn | Uzbek (Latin) |
| uz-Latn-UZ | Uzbek (Latin, Uzbekistan) |
| uz | Uzbek |
| vi-VN | Vietnamese (Vietnam) |
| vi | Vietnamese |
| vun-TZ | Vunjo (Tanzania) |
| vun | Vunjo |
| cy-GB | Welsh (United Kingdom) |
| cy | Welsh |
| yo-NG | Yoruba (Nigeria) |
| yo | Yoruba |
| zu-ZA | Zulu (South Africa) |
| zu | Zulu |
---