These are the old docs. Go the new Cosmic documentation.
NAV undefined

REST API

bash javascript

Introduction

Starting Point

# API Endpoint
https://api.cosmicjs.com
// Install the NPM package
npm install cosmicjs

The Cosmic JS REST API helps you easily manage data and files for websites and applications. We support cross-origin resource sharing, allowing you to interact securely with our API from a client-side web application (though you should never expose your private keys or credentials in any public website's client-side code). JSON is returned by all API responses, including errors.

Some code samples are runnable using Runkit.

Getting Started

Go to https://cosmicjs.com/signup to create an account and get familiar with the Cosmic JS Dashboard.

Terms

These docs assume you understand the core concepts of Cosmic JS including Buckets, Object Types and Objects. For a brief overview of these terms, see the Getting Started guide.

Errors

The Cosmic JS API uses the following error codes:

Error 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.

Authentication

Definition

POST https://api.cosmicjs.com/v1/authenticate
Cosmic.authenticate()

Example Request

# With shell, you can just pass your email and password
curl -X POST "https://api.cosmicjs.com/v1/authenticate" \
-d "email=you@youremail.com" \
-d "password=yourpassword"
const Cosmic = require('cosmicjs')() // double parentheses to init function without token
Cosmic.authenticate({
  email: 'you@youremail.com',
  password: 'yourpassword'
}).then(data => {
    console.log(data)
}).catch(err => {
    console.log(err)
})

Example Response

{
  "success": true,
  "message": "Token created successfully.",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXV.eyJlbWFpbCI6InNwaXJvbnl..."
}

Send your email and password to receive your access token. Your access token will be used to add Buckets to your account as well as other account-related access. You do not need to use the token to access your Bucket. Your Bucket has its own read and write keys for restricted access.

Parameter Required Type Description
email required String Your Cosmic JS login email
password required String Your Cosmic JS login password

Buckets

Add Bucket

Definition

POST https://api.cosmicjs.com/v1/buckets
Cosmic.addBucket()

Example Request

curl -X POST "https://api.cosmicjs.com/v1/buckets" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: application/json" \
-d '{"title": "My New Bucket"}'
const Cosmic = require('cosmicjs')({
  token: 'your-token-from-auth-request' // required
})
Cosmic.addBucket({
  title: 'My New Bucket',
  slug: 'my-new-bucket' // must be unique across all Buckets in system
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "bucket": {
    "_id": "55b3d557df0fb1df7600004b",
    "slug": "my-new-bucket",
    "title": "My New Bucket"
  }
}

title is the only required property. If no slug is present, the title will be converted to a slug. See the table below for the other optional properties. The Bucket request matches the bucket.json file located in Your Bucket Dashboard > Import / Export.

Parameter Required Type Description
title required String Your Bucket title
slug String URL-friendly unique identifier
read_key String Restrict read access
write_key String Restrict write access
cluster String Add this Bucket to a Cluster. ID of existing Cluster
object_types Array Populate your Bucket with Object Types. See Object Types for model.
objects Array Populate your Bucket with Objects. See Objects for model.
media Array Populate your Bucket with Media. See Media for model.
media_folders Array Populate your Bucket with Media Folders. See Media for model.
webhooks Array Populate your Bucket with Webhooks. See Webhooks for model.
extensions Array Populate your Bucket with Extensions. See Extensions for model.

Get Buckets

Definition

GET https://api.cosmicjs.com/v1/buckets
Cosmic.getBuckets()

Example Request

curl "https://api.cosmicjs.com/v1/buckets" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: application/json"
const Cosmic = require('cosmicjs')({
  token: 'your-token-from-auth-request' // optional
})
Cosmic.getBuckets().then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Gets all Buckets connected to your account. Your authorization token in the header request is the only required property.

Example Response

{
  "buckets": [
    {
      "_id": "5a051c23ae05992b360005e7",
      "slug": "my-first-bucket",
      "title": "My First Bucket",
      "created_at": "2017-11-10T03:25:23.807Z",
      "modified_at": "2017-11-11T17:20:04.322Z"
    },
    {
      "_id": "5a329f6769a130011900000c",
      "slug": "my-second-bucket",
      "title": "My Second Bucket",
      "created_at": "2017-12-14T15:57:27.274Z",
      "modified_at": "2018-01-14T04:06:29.630Z"
    },
    {
      "_id": "5a329f6769a130011900000c",
      "slug": "my-third-bucket",
      "title": "My Third Bucket",
      "created_at": "2017-12-14T15:57:27.274Z",
      "modified_at": "2018-01-14T04:06:29.630Z"
    }
  ]
}

Connect to Bucket

Example Request

curl "https://api.cosmicjs.com/v1/wedding-site"
// Use the Cosmic.bucket method to connect to different Buckets in your account.
const Cosmic = require('cosmicjs')({
  token: 'your-token-from-auth-request' // optional
})
const bucket = Cosmic.bucket({
  slug: 'my-first-bucket',
  read_key: '',
  write_key: ''
})
const bucket2 = Cosmic.bucket({
  slug: 'my-other-bucket',
  read_key: '',
  write_key: ''
})

For the NPM module:

Parameter Required Type Description
slug required String The Bucket slug
read_key String Restrict read access
write_key String Restrict write access

Get Bucket

Definition

GET https://api.cosmicjs.com/v1/:bucket_slug
bucket.getBucket()

Example Request

curl "https://api.cosmicjs.com/v1/wedding-site"

const Cosmic = require('cosmicjs')
const api = Cosmic()
const bucket = api.bucket({
  slug: 'wedding-site'
})
const data = (await bucket.getBucket()).bucket

Returns the entire Bucket including Object Types, Objects, Media and more. If you would like to restrict read access to your Bucket, you can do so in Your Bucket > Basic Settings.

Parameter Required Type Description
hide_metafields Enum true, Hides metafields
read_key String Restrict read access to your Bucket

Delete Bucket

Definition

DELETE https://api.cosmicjs.com/v1/buckets/:bucket_id
Cosmic.deleteBucket()

Example Request

curl -X DELETE "https://api.cosmicjs.com/v1/buckets/:bucket_id" \
-H "Authorization: Bearer <ACCESS_TOKEN>"
const Cosmic = require('cosmicjs')){
  token: 'your-token-from-auth-request' // required
})
Cosmic.deleteBucket({
  id: 'bucket_id'
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "status": "200",
  "message": "Bucket deleted"
}

DANGER! Deletes the whole Bucket. This cannot be undone.

Parameter Required Type Description
id required String The Bucket id found as "_id"
token required String You can only delete Buckets that you have created / own.

Import Bucket

Definition

POST https://api.cosmicjs.com/v1/buckets/:bucket_id/import
Cosmic.importBucket()

Example Request

curl -X POST "https://api.cosmicjs.com/v1/buckets/5ace13795a39fb49db87ac95/import" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: application/json" \
-d '{ "bucket": { "title": "My New Bucket" } }'
const Cosmic = require('cosmicjs')({
  token: 'your-token-from-auth-request' // required
})
const params = {
  "id": "5ace13795a39fb49db87ac95", // Bucket id found in Bucket Settings > Basic Settings
  "bucket": { // import data
    "object_types": [...],
    "objects": [...],
    "media": [...]
  }
}
Cosmic.importBucket(params).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "bucket": {
    "_id": "5ace13795a39fb49db87ac95",
    "slug": "same-bucket-slug",
    "title": "Same Bucket Title",
    "object_types": [...], // all new Object Types
    "objects": [...], // all new Objects
    "media": [...] // all new Media
  }
}

DANGER! The Bucket import method removes all current data: Object Types, Objects and Media and replaces it with new data. This cannot be undone.

The Bucket data schema matches the bucket.json file located in Your Bucket Dashboard > Import / Export.

Parameter Required Type Description
object_types Array Populate your Bucket with Object Types. See Object Types for model.
objects Array Populate your Bucket with Objects. See Objects for model.
media Array Populate your Bucket with Media. See Media for model.
media_folders Array Populate your Bucket with Media Folders. See Media for model.
webhooks Array Populate your Bucket with Webhooks. See Webhooks for model.
extensions Array Populate your Bucket with Extensions. See Extensions for model.

Deploy App

Definition

POST https://api.cosmicjs.com/v1/buckets/:bucket_id/deploy
Cosmic.deployApp()

Example Request

curl -X POST "https://api.cosmicjs.com/v1/buckets/5ace13795a39fb49db87ac95/deploy" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: application/json" \
-d '{ "repo_url": "https://github.com/cosmicjs/portfolio-website", "repo_branch": "master" }'
const Cosmic = require('cosmicjs')({
  token: 'your-token-from-auth-request' // required
})
const params = {
  "id": "5ace13795a39fb49db87ac95", // Bucket id found in Bucket Settings > Basic Settings
  "repo_url": "https://github.com/cosmicjs/portfolio-website",
  "repo_branch": "master"
}
Cosmic.deployApp(params).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "code": 200,
  "status": "success",
  "message": "App deploying.  You will receive an email when the deployment is completed successfully."
}

The Bucket deploy App action replaces the currently deployed App connected to this Bucket (if one exists).

Parameter Required Type Description
repo_url String Link to public (or private, if GitHub account connected) repository
repo_branch String Repo branch to deploy. Defaults to master if none specified.

Users

Add User to Bucket

Definition

POST https://api.cosmicjs.com/v1/:bucket_slug/users
bucket.addUser()

Example Request

{
  "email": "newuser@example.com",
  "role": "editor"
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
const params = {
  "email": "newuser@example.com",
  "role": "editor",
  "first_name": "Quasar",
  "last_name": "Jones"
}
bucket.addUser(params).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "status": 200,
  "message": "User added."
}

Add a user to your Bucket. Authentication token is required and must have admin level access.

Parameter Required Type Description
email required String The new user's email
role required Enum admin, developer, editor or contributor
first_name String The new user's first name
last_name String The new user's last name
write_key String Include if a write access key has been added to your Bucket

Get Users

Definition

GET https://api.cosmicjs.com/v1/:bucket_slug/users
bucket.getUsers()

Example Request

const bucket = Cosmic.bucket({
  slug: 'bucket-slug'
})
bucket.getUsers().then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})
curl "https://api.cosmicjs.com/v1/creative-agency/users" \
-H "Authorization: Bearer <ACCESS_TOKEN>"

Example Response

{
  "users": [
    {
      "_id": "5357ef811693be2118000001",
      "first_name": "Starman",
      "last_name": "Jones",
      "email": "starman@milkyway.com",
      "username": "starman",
      "bio": "Enjoy traveling at the speed of light, black holes and supernovas are my jam.",
      "avatar_url": "https://cosmicjs.imgix.net/1c3690c0-9dbc-11e7-b30d-b3b3f0076a4f-me.jpg",
      "website": "https://starman.com",
      "twitter": "https://twitter.com/starman",
      "linkedin": "http://linkedin.com/in/starman",
      "github": "http://github.com/starman",
      "company": "Starman Inc.",
      "location": "Neptune"
    },
    {
      "_id": "56d66b2f903a79b904000001",
      "first_name": "Quasar",
      "last_name": "Jones",
      "email": "quasar@milkyway.com",
      "username": "quasar",
      "bio": "I contain massive black holes and may evolve into a galaxy.",
      "avatar_url": "https://cosmic-s3.imgix.net/08544a00-eaa3-11e7-8c73-5dadcfada90e-wave.jpg",
      "website": "https://quasar.com",
      "twitter": "https://twitter.com/quasar",
      "linkedin": "http://linkedin.com/in/quasar",
      "github": "http://github.com/quasar",
      "company": "Quasar Inc.",
      "location": "Titan"
    }
  ],
  "total": 2
}

Get users in your Bucket. Authentication token is required in the header (see Authentication section). Must have admin level access.

Get User

Definition

GET https://api.cosmicjs.com/v1/:bucket_slug/users/:user_id
bucket.getUser()
const bucket = Cosmic.bucket({
  slug: 'bucket-slug'
})
const params = {
  id: '5357ef811693be2118000001'
}
bucket.getUser(params).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "user": {
    "_id": "5357ef811693be2118000001",
    "first_name": "Starman",
    "last_name": "Jones",
    "email": "starman@milkyway.com",
    "username": "starman",
    "bio": "Enjoy traveling at the speed of light, black holes and supernovas are my jam.",
    "avatar_url": "https://cosmicjs.imgix.net/1c3690c0-9dbc-11e7-b30d-b3b3f0076a4f-me.jpg",
    "website": "https://starman.com",
    "twitter": "https://twitter.com/starman",
    "linkedin": "http://linkedin.com/in/starman",
    "github": "http://github.com/starman",
    "company": "Starman Inc.",
    "location": "Neptune"
  }
}

Get a single user from your Bucket. Authentication token is required in the header (see Authentication section). Must have admin level access.

Parameter Required Type Description
id required String User's id (found as _id param)

Object Types

Add Object Type

Definition

POST https://api.cosmicjs.com/v1/:bucket_slug/add-object-type
bucket.addObjectType()

Example Request

{
  "title": "Pages",
  "singular": "Page",
  "slug": "pages",
  "metafields": [
    {
      "type": "text",
      "title": "Headline",
      "key": "headline",
      "required": true
    },
    {
      "type": "file",
      "title": "Hero",
      "key": "hero",
      "required": true
    }
  ]
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
const params = {
  "title": "Pages",
  "singular": "Page",
  "slug": "pages",
  "metafields": [
    {
      "type": "text",
      "title": "Headline",
      "key": "headline",
      "required": true
    },
    {
      "type": "file",
      "title": "Hero",
      "key": "hero",
      "required": true
    }
  ]
}
bucket.addObjectType(params).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "object_type": {
    "slug": "pages",
    "title": "Pages",
    "singular": "Page",
    "metafields": [
      {
        "type": "text",
        "title": "Headline",
        "key": "headline",
        "required": true
      },
      {
        "type": "file",
        "title": "Hero",
        "key": "hero",
        "required": true
      }
    ],
    "created_at": "2017-05-30T02:06:35.373Z",
    "metadata": null
  }
}

Add a new Object Type to your Bucket.

Parameter Required Type Description
title required String Plural title of your Object Type
slug String Plural slug of your Object Type
singular String Singular title of your Object Type
metafields Array Default Metafields for each Object in this type
pretty Enum true, Makes the response more reader-friendly
write_key String Restrict write access to your Bucket

Get Object Types

Definition

GET https://api.cosmicjs.com/v1/:bucket_slug/object-types
bucket.getObjectTypes()

Example Request

curl "https://api.cosmicjs.com/v1/wedding-site/object-types"

        
        

Get all Object Types in your Bucket.

Parameter Required Type Description
pretty Enum true, Makes the response more reader-friendly
read_key String Restrict read access to your Bucket

Edit Object Type

Definition

PUT https://api.cosmicjs.com/v1/:bucket_slug/edit-object-type
bucket.editObjectType()

Example Request

{
  "slug": "pages",
  "metafields": [
    {
      "type": "text",
      "title": "Headline",
      "key": "headline",
      "required": true
    },
    {
      "type": "file",
      "title": "Hero",
      "key": "hero",
      "required": true
    },
    {
      "type": "text",
      "title": "Tagline",
      "key": "tagline",
      "required": true
    }
  ]
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
bucket.editObjectType({
  slug: 'posts',
  title: 'New Posts Title'
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "object_type": {
    "slug": "pages",
    "title": "Pages",
    "singular": "Page",
    "metafields": [
      {
        "type": "text",
        "title": "Headline",
        "key": "headline",
        "required": true
      },
      {
        "type": "file",
        "title": "Hero",
        "key": "hero",
        "required": true
      },
      {
        "type": "text",
        "title": "Tagline",
        "key": "tagline",
        "required": true
      }
    ],
    "modified_at": "2017-05-30T02:10:35.373Z",
    "created_at": "2017-05-30T02:06:35.373Z",
    "metadata": null
  }
}

Edit an existing Object Type in your Bucket.

Parameter Required Type Description
slug required String Plural slug of your Object Type
title String Plural title of your Object Type
singular String Singular title of your Object Type
metafields Array Default Metafields for each Object in this type
write_key String Restrict write access to your Bucket

Delete Object Type

Definition

DELETE https://api.cosmicjs.com/v1/:bucket_slug/object-types/:type_slug
bucket.deleteObjectType()

Example Request Body

{
  "write_key": "your-key-added-in-bucket-settings" // optional
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
bucket.deleteObjectType({
  slug: 'posts'
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "status": "200",
  "message": "Object Type deleted."
}

Delete an existing Object Type from your Bucket. * This does not delete Objects in this Object Type.

Parameter Required Type Description
write_key String Restrict write access to your Bucket

Objects

The following endpoints allow you to add, edit and delete Objects in your Bucket. If you would like to restrict read or write access to your Bucket, you can do so in Your Bucket > Basic Settings.

Add Object

Definition

POST https://api.cosmicjs.com/v1/:bucket_slug/add-object
bucket.addObject()

Example Request

{
  "title": "Cosmic JS Example",
  "type_slug": "examples",
  "content": "Learning the Cosmic JS API is really fun and so easy",
  "metafields": [
    {
      "key": "Headline",
      "type": "text",
      "value": "Learn Cosmic JS!"
    },
    {
      "key": "Author",
      "type": "text",
      "value": "Quasar Jones"
    }
  ],
  "options": {
    "slug_field": false
  }
}
const params = {
  "title": "Cosmic JS Example",
  "type_slug": "examples",
  "content": "Learning the Cosmic JS API is really fun and so easy",
  "metafields": [
    {
      "key": "Headline",
      "type": "text",
      "value": "Learn Cosmic JS!"
    },
    {
      "key": "Author",
      "type": "text",
      "value": "Quasar Jones"
    }
  ],
  "options": {
    "slug_field": false
  }
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
bucket.addObject(params).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "object": {
    "slug": "cosmic-js-example",
    "title": "Cosmic JS Example",
    "content": "Learning the Cosmic JS API is really fun and so easy",
    "metafields": [
      {
        "title": "Headline",
        "key": "headline",
        "type": "text",
        "value": "Learn Cosmic JS!"
      },
      {
        "title": "Author",
        "key": "author",
        "type": "text",
        "value": "Quasar Jones"
      }
    ],
    "bucket": "568c5bbefd0dce302c000001",
    "type_slug": "examples",
    "created_at": "2016-01-06T00:28:39.982Z",
    "_id": "568c5fb72f0c5d532d000001",
    "options": {
      "slug_field": false
    }
  }
}

Add a new Object to your Bucket.

Parameter Required Type Description
type_slug required String Add Object to Object Type
title required String Your Object title
slug String Unique identifier for your Object
content String Add Content to your Object
status Enum draft, published, defaults to published
options.slug_field Bool Set to false to hide the slug field
options.content_editor Bool Set to false to hide the content editor
metafields Array Add Metafields to your Object. See Metafields Model.
locale String Add localization to the Object
write_key String Your Bucket write key
publish_at Number UNIX millisecond timestamp. Publish automatically at a later time.

Get Objects

Definition

GET https://api.cosmicjs.com/:bucket_slug/objects
bucket.getObjects()

Example Request

curl "https://api.cosmicjs.com/v1/wedding-site/objects?pretty=true&hide_metafields=true&limit=2"

        
        

Returns Objects from your Bucket.

Parameter Required Type Description
type String The Object Type slug
limit Number The number of Objects to return
skip Number The number of Objects to skip
status Enum all, Return published and draft status Objects
hide_metafields Enum true, Hides metafields
sort Enum created_at, -created_at,
modified_at, -modified_at,
random
locale String Filter by locale
q String Searches title and content properties for this string
metafield_key String Metafield key to search for
metafield_value String Metafield contains value
metafield_object_id String Object Metafield Object ID (stored as Metafield value)
filters[_id] String Filter by Object IDs (comma separated for multiple)
filters[connected_to] String Returns Objects that reference the specified Object ID (String)
pretty Enum true, Makes the response more reader-friendly
read_key String Your Bucket read key

Get Objects by Type

Definition

GET https://api.cosmicjs.com/v1/:bucket_slug/objects?type=:type_slug
bucket.getObjects({
  // params
})

Example Request

curl "https://api.cosmicjs.com/v1/wedding-site/objects?type=groomsmen&limit=3"

        
        

Get Objects from an Object Type using getObject method and the type param (the method getObjectsByType is now deprecated).

Search and Filter Objects

Search

GET https://api.cosmicjs.com/v1/:bucket_slug/objects?type=:type_slug&q=:search_text
GET https://api.cosmicjs.com/v1/:bucket_slug/objects?type=:type_slug&metafield_key=:metafield_key_text&metafield_value=:metafield_value_text
GET https://api.cosmicjs.com/v1/:bucket_slug/objects?type=:type_slug&filters[_id]=:object_id_1,:object_id_2
bucket.getObjects({
  // params
})

Example Request

curl "https://api.cosmicjs.com/v1/wedding-site/objects?type=groomsmen&metafield_key=official-title&metafield_value=Best%20Man"

        
        

Get Objects based on search variables. (the method searchObjectType is now deprecated)

Get Object

Definition

GET https://api.cosmicjs.com/:bucket_slug/object/:slug
bucket.getObject()

Example Request

curl "https://api.cosmicjs.com/v1/wedding-site/object/registry"

        
        

Returns a single Object from your Bucket.

Parameter Required Type Description
slug required String Unique identifier for your Object
status Enum all, Return published and draft status Objects
revision String The revision_id of the Object Revision
hide_metafields Enum true, Hides metafields
locale String Filter by locale
pretty Enum true, Makes the response more reader-friendly
read_key String Your Bucket read key

Edit Object

Definition

PUT https://api.cosmicjs.com/v1/:bucket_slug/edit-object
bucket.editObject()

Example Request

{
  "slug": "cosmic-js-example",
  "title": "New Title Edit",
  "content": "This is some rad test content...",
  "metafields": [
    {
      "title": "Headline",
      "key": "headline",
      "value": "Something Big is Coming",
      "type": "text"
    },
    {
      "title": "Subheadline",
      "key": "subheadline",
      "value": "I bet you want to know what it is...",
      "type": "text"
    }
  ]
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
bucket.editObject({
  slug: 'cosmic-js-example',
  title: 'New Title Edit'
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "object": {
    "_id": "568c5fb72f0c5d532d000001",
    "slug": "cosmic-js-example",
    "title": "New Title Edit",
    "content": "This is some rad test content...",
    "metafields": [
      {
        "title": "Headline",
        "key": "headline",
        "value": "Something Big is Coming",
        "type": "text"
      },
      {
        "title": "Subheadline",
        "key": "subheadline",
        "value": "I bet you want to know what it is...",
        "type": "text"
      }
    ],
    "bucket": "568c5bbefd0dce302c000001",
    "type_slug": "examples",
    "created": "2016-01-06T00:28:39.982Z"
  }
}

Edit an existing Object in your Bucket.

Parameter Required Type Description
slug required String Unique identifier for your Object
type_slug String Object Type
title String Your Bucket title
content String Add Content to your Object
status Enum draft, published, defaults to published
options.slug_field Bool Set to false to hide the slug field
options.content_editor Bool Set to false to hide the content editor
metafields Array Add Metafields to your Object. See Metafields Model.
locale String Edit Object locale
write_key String Your Bucket write key
publish_at Number UNIX millisecond timestamp. Publish automatically at a later time.

Delete Object

Definition

DELETE https://api.cosmicjs.com/v1/:bucket_slug/objects/:object_slug
bucket.deleteObject()

Example Request

{
  "write_key": "your-key-added-in-bucket-settings"
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
bucket.deleteObject({
  slug: 'cosmic-js-example'
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "status": "200",
  "message": "Object deleted"
}

Delete an existing Object in your Bucket.

Parameter Required Type Description
slug required String Unique identifier for your Object
write_key String Your Bucket write key

Metafields

Metafields are powerful components that can be added to Objects and Object Types. Metafields added to Object Types will be default for all new Objects in the type.

Model

Example Metafields

{
  "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": "<p>Some <strong>HTML content</strong> for <em>dramatic</em> effect!</p>"
    },
    {
      "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": "object",
      "title": "Pages",
      "key": "pages",
      "object_type": "pages",
      "value": "5a4806974fa85fc8a7000002"
    },
    {
      "type": "objects",
      "title": "Other Listings",
      "key": "other_listings",
      "object_type": "listings",
      "value": "5a4806974fa85fc8a7000007,5a4806974fa85fc8a7000008"
    },
    {
      "type": "file",
      "title": "Hero",
      "key": "hero",
      "value": "7d276450-5a95-11e7-b717-653f819d86b5.jpg",
      "url": "https://s3-us-west-2.amazonaws.com/cosmicjs/7d276450-5a95-11e7-b717-653f819d86b5.jpg",
      "imgix_url": "https://cosmic-s3.imgix.net/7d276450-5a95-11e7-b717-653f819d86b5.jpg"
    },
    {
      "type": "date",
      "title": "Listing Start Date",
      "key": "listing_start_date",
      "value": ""
    },
    {
      "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": "",
      "options": [
        {
          "value": "True"
        },
        {
          "value": "False"
        }
      ]
    },
    {
      "type": "check-boxes",
      "title": "Amenities",
      "key": "amenities",
      "value": [
        "Pool",
        "Gym"
      ],
      "options": [
        {
          "value": "Pool"
        },
        {
          "value": "Gym"
        },
        {
          "value": "Landscaping"
        }
      ]
    },
    {
      "type": "repeater",
      "title": "Testimonials",
      "key": "testimonials",
      "value": "Fiona Apple",
      "repeater_fields": [
        {
          "title": "Name",
          "key": "name",
          "value": "",
          "type": "text",
          "required": false
        },
        {
          "title": "Quote",
          "key": "quote",
          "value": "",
          "type": "text",
          "required": false
        }
      ],
      "children": [
        {
          "children": [
            {
              "type": "text",
              "title": "Name",
              "key": "name",
              "value": "Fiona Apple"
            },
            {
              "type": "text",
              "title": "Name",
              "key": "name",
              "value": "Jon Brion"
            }
          ]
        }
      ]
    }
  ]
}
Parameter Required Type Description
type required Enum text, textarea, html-textarea,
select-dropdown, object, objects,
file, date, radio-buttons, check-boxes,
repeater, parent, markdown, json
title required String Your Metafield title
key required String Unique identifier for your Metafield
value String Metafield value
required Bool A value is required
regex String Restrict the value to match a regular expresssion
regex_message Array 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
children Array Add nested Metafields

Validation

You can use optional validation parameters to make sure editors using the Web Dashboard enter the correct values.

Example Metafields with Validations

{
  "title": "Users",
  "singular": "User",
  "slug": "users",
  "metafields": [
    {
      "key": "first_name",
      "title": "First Name",
      "type": "text",
      "value": "",
      "required": true,
      "minlength": 2
    },
    {
      "key": "last_name",
      "title": "Last Name",
      "type": "text",
      "value": "",
      "required": true,
      "minlength": 2
    },
    {
      "key": "email",
      "title": "Email",
      "type": "text",
      "value": "",
      "regex": "/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/",
      "regex_message": "You must enter a valid email."
    },
    {
      "key": "avatar",
      "title": "Avatar",
      "type": "file",
      "value": ""
    },
    {
      "key": "tagline",
      "title": "Tagline",
      "type": "text",
      "value": "",
      "maxlength": 50
    }
  ]
}

Reference the Metafield model to learn more.

Optional Validation Parmeters

Parameter Required Type Description
required Bool A value is required
regex String Restrict the value to match a regular expresssion
regex_message Array 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

Connect Objects

Definition

POST https://api.cosmicjs.com/v1/:bucket_slug/add-object
bucket.addObject()

Example Request

{
  "title": "Blog Post Example",
  "type_slug": "blog-posts",
  "content": "This is some amazing blog content...",
  "metafields": [
    {
      "title": "Headline",
      "key": "headline",
      "type": "text",
      "value": "What I Learned Today"
    },
    {
      "title": "Author",
      "key": "author",
      "type": "object",
      "object_type": "authors",
      "value": "5a4ab6e0cf2289b18a2f7599"
    },
    {
      "title": "Categories",
      "key": "categories",
      "type": "objects",
      "object_type": "categories",
      "value": "5a4ab6e0cf2289b18a2f7599,5a49d524c1174db128ca2bce"
    }
  ]
}
const params = {
  "title": "Blog Post Example",
  "type_slug": "blog-posts",
  "content": "This is some amazing blog content...",
  "metafields": [
    {
      "title": "Headline",
      "key": "headline",
      "type": "text",
      "value": "What I Learned Today"
    },
    {
      "title": "Author",
      "key": "author",
      "type": "object",
      "object_type": "authors",
      "value": "5a4ab6e0cf2289b18a2f7599"
    },
    {
      "title": "Categories",
      "key": "categories",
      "type": "objects",
      "object_type": "categories",
      "value": "5a4ab6e0cf2289b18a2f7599,5a49d524c1174db128ca2bce"
    }
  ]
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
bucket.addObject(params).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

You can connect Objects to create "one to many" and "many to many" relationships between Objects using Single and Multiple Object Metafields.

Single Objects

For a Single Object Metafield, add the Object ID (_id) to the value to connect the Object. The full Object will be returned on the Metadata response in the object property.

Multiple Objects

For Multiple Object type Metafields, you can add the Object IDs as comma-separated values. The full Objects will be returned on the Metadata response in the objects property.

Parameter Required Type Description
type required Enum object, objects
title required String Your Metafield title
key required String Unique identifier for your Metafield
object_type required String Object Type slug
value String For single Object this is the _id property. For multiple Objects it is comma-separated _ids.

Media

Add Media

Definition

POST https://api.cosmicjs.com/v1/:bucket_slug/media
bucket.addMedia()

Example Request

{
  "media": "your-media-object",
  "folder": "your-folder-slug",
  "metadata": {
    "caption": "Beautiful picture of the beach",
    "credit": "Tyler Jackson"
  }
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})

const media_object = req.files[0] // Using Multer
// OR:
// const media_object = { originalname: filename, buffer: filedata } // Not using Multer

bucket.addMedia({
  media: media_object,
  folder: 'your-folder-slug',
  metadata: {
    caption: 'Beautiful picture of the beach',
    credit: 'Tyler Jackson'
  }
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

/*
As an example, another popular upload library for express is [express-fileupload](https://www.npmjs.com/package/express-fileupload). File objects obtained through this have the following properties:
req.files.foo.name: "car.jpg"
req.files.foo.mimetype: The mimetype of your file
req.files.foo.data: A buffer representation of your file
*/

// In order to pass the file `req.files.foo` to Cosmic you would do:
const media_object = {
  originalname: req.files.foo.name,
  buffer: req.files.foo.data,
}

Example Response

{
  "media": {
    "name": "c20391e0-b8a4-11e6-8836-fbdfd6956b31-bird.jpg",
    "original_name": "bird.jpg",
    "size": 457307,
    "type": "image/jpeg",
    "bucket": "5839c67f0d3201c114000004",
    "created": "2016-12-02T15:34:05.054Z",
    "location": "https://cosmicjs.com/uploads",
    "url": "https://s3-us-west-2.amazonaws.com/cosmicjs/c20391e0-b8a4-11e6-8836-fbdfd6956b31-bird.jpg",
    "imgix_url": "https://cosmic-s3.imgix.net/c20391e0-b8a4-11e6-8836-fbdfd6956b31-bird.jpg",
    "metadata": [
      {
        "key": "caption",
        "value": "Beautiful picture of the beach"
      },
      {
        "key": "credit",
        "value": "Tyler Jackson"
      }
    ]
  }
}

The only required post value is the media object. You can also add optional folder and metadata params.

Parameter Required Type Description
media required Media Object (see below) Media object with specific properties
folder String Media folder slug
metadata Object Key / value data store
write_key String Your Bucket write key

Media Object

The Media Object must be an object with certain properties indicated below. If using the multer NPM module the file objects have these by default. Otherwise you should create an object with these properties:

Parameter Required Type Description
originalname required String The name of your file (something.jpg)
buffer File Buffer The File Buffer

Get Media

Definition

GET https://api.cosmicjs.com/v1/:bucket_slug/media
Cosmic.getMedia()

Example Request

curl "https://api.cosmicjs.com/v1/wedding-site/media?pretty=true&folder=groomsmen&limit=3"

        
        

You can add the folder parameter to get Media from a certain folder.

Imgix

Imgix is included with every account. You can use the Imgix suite of image processing tools on the URL provided by the imgix_url property value. Check out the Imgix documentation for more info.

Parameter Required Type Description
pretty File Media object
folder String Media folder slug
read_key String Your Bucket read key

Delete Media

Definition

DELETE https://api.cosmicjs.com/v1/:bucket_slug/media/:media_id
Cosmic.deleteMedia()

Example Request

{
  "write_key": "your-key-added-in-bucket-settings"
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
bucket.deleteMedia({
 id: '5a4b18e12fff7ec0e3c13c65'
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "status": "200",
  "message": "Object Type deleted."
}

If a write key is enabled on the requested bucket, the parameter write_key will need to be present.

Parameter Required Type Description
write_key String Your Bucket write key

Webhooks

Add Webhook

Definition

POST https://api.cosmicjs.com/v1/:bucket_slug/webhooks
bucket.addWebhooks()

Example Request

{
  "event": "object.created.published",
  "endpoint": "http://my-listener.com",
  "write_key": "your-key-added-in-bucket-settings"
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
bucket.addWebhook({
  event: 'object.created.published',
  endpoint: 'http://my-listener.com'
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "webhook": {
      "id": "e39b2480-f043-11e7-ba08-234e3fae7762",
      "title": "Object created and published",
      "event": "object.created.published",
      "endpoint": "http://my-listener.com"
  }
}

Sends a POST request to the endpoint of your choice when the event occurs. The data payload in the same fomat as Object and Media. Read more about Webhooks including the payload sent to the endpoint on the Webhooks documentation page.

Parameter Required Type Description
event required Enum object.created.draft, object.created.published
object.edited.draft, object.edited.published
object.deleted, media.created
media.edited, media.deleted
endpoint required String The endpoint that will receive the data
write_key String Your Bucket write key

Delete a Webhook

Definition

DELETE https://api.cosmicjs.com/v1/:bucket_slug/webhooks/:webhook_id
Cosmic.deleteWebhook()

Example Request

{
  "write_key": "your-key-added-in-bucket-settings"
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
bucket.deleteWebhook({
  id: 'c62defe0-5f93-11e7-8054-873245f0e98d'
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "status": "200",
  "message": "Webhook deleted."
}

If a write key is enabled on the requested bucket, the parameter write_key will need to be present.

Parameter Required Type Description
write_key String Your Bucket write key

Extensions

Add Extension

Definition

POST https://api.cosmicjs.com/v1/:bucket_slug/extensions
bucket.addExtension()

Example Request

{
  "zip": "your-media-multipart-form-data",
  "write_key": "your-key-added-in-bucket-settings"
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})

const zip_object = req.files[0] // Using Multer
// OR:
// const zip_object = { originalname: filename, buffer: filedata } // Not using Multer

bucket.addExtension({
  zip: zip_object
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})
/*
As an example, another popular upload library for express is [express-fileupload](https://www.npmjs.com/package/express-fileupload). File objects obtained through this have the following properties:
req.files.foo.name: "car.jpg"
req.files.foo.mimetype: The mimetype of your file
req.files.foo.data: A buffer representation of your file
*/

// In order to pass the file `req.files.foo` to Cosmic you would do:
const media_object = {
  originalname: req.files.foo.name,
  buffer: req.files.foo.data,
}

Example Response

{
  "extension": {
    "id": "c62defe0-5f93-11e7-8054-873245f0e98d",
    "title": "Amazon Product Search",
    "image_url": "https://s3-us-west-2.amazonaws.com/cosmicjs/f1f1bd40-5dcd-11e7-b529-51f126a4b6ee-shopping-cart.jpg",
    "url": "http://localhost:3000/extensions/c62defe0-5f93-11e7-8054-873245f0e98d/dist",
    "zip_url": "http://localhost:3000/extensions/c62defe0-5f93-11e7-8054-873245f0e98d/src/build.zip",
    "installed_at": "2017-07-03T02:03:14.825Z",
    "font_awesome_class": "fa-shopping-basket"
  }
}

Adds an Extension to your Bucket. The only required post value is zip which is the name of your file sent. Read more about Extensions on the Extensions documentation page.

Parameter Required Type Description
zip required File Object (see below) Zip object with specific properties
write_key String Your Bucket write key

File Object

The File Object must be an object with certain properties indicated below. If using the multer NPM module the file objects have these by default. Otherwise you should create an object with these properties:

Parameter Required Type Description
originalname required String The name of your file (something.jpg)
buffer File Buffer The File Buffer (must be zip file)

Delete an Extension

Definition

DELETE https://api.cosmicjs.com/v1/:bucket_slug/extensions/:extension_id
Cosmic.deleteExtension()

Example Request

{
  "write_key": "your-key-added-in-bucket-settings"
}
const bucket = Cosmic.bucket({
  slug: 'bucket-slug',
  write_key: ''
})
bucket.deleteExtension({
  id: 'c62defe0-5f93-11e7-8054-873245f0e98d'
}).then(data => {
  console.log(data)
}).catch(err => {
  console.log(err)
})

Example Response

{
  "status": "200",
  "message": "Extension deleted."
}

If a write key is enabled on the requested bucket, the parameter write_key will need to be present.

Parameter Required Type Description
write_key String Your Bucket write key