Skip to content

Media

The following endpoints allow you to manage media in your Bucket.

🔑

Get your keys
Your Bucket slug,read_key, and write_key will be required to perform the following requests. These can be found in Bucket Settings > API Access in your Bucket Dashboard .

Data Model

AttributeTypeNotes
idStringUnique identifier for Media
nameStringUnique name of the uploaded file, used in Media Metafield value.
original_nameStringOriginal file name
sizeStringFile size in bytes
typeStringFile type
bucketStringBucket id
createdStringDate created
locationStringLocation of uploaded asset (used internally)
folderStringMedia folder
urlStringMedia CDN URL
imgix_urlStringimgix URL (used for image processing and optimizations)
metadataObjectUser-added metadata

Upload URL

https://upload.cosmicjs.com

Endpoints

GET /v2/buckets/${YOUR_BUCKET_SLUG}/media
GET /v2/buckets/${YOUR_BUCKET_SLUG}/media/:id
PATCH /v2/buckets/${YOUR_BUCKET_SLUG}/media/:id
POST ${UPLOAD_URL}/v2/buckets/${YOUR_BUCKET_SLUG}/media

Get Media List

Get Media List in your Bucket.

ParameterRequiredTypeDefaultDescription
read_keyrequiredStringRestrict read access to your Bucket
propsStringDeclare which properties to return in comma-separated string. Reference full Media for all available properties. Example: ?props=name,url,imgix_url,metadata
sortEnum-createdcreated, -created, size, -size, random
limitNumber1000The number of Media to return
skipNumber0The number of Media to skip
prettyEnumfalsetrue, Makes the response more reader-friendly
queryJSONA JSON string to perform media search and filtering. See Queries section for more detail.

Definition

GET /v2/buckets/${YOUR_BUCKET_SLUG}/media

Methods

Cosmic.getMedia()

Example Request

const Cosmic = require("cosmicjs")(); // empty init
const bucket = Cosmic.bucket({
slug: "YOUR_BUCKET_SLUG",
read_key: "YOUR_BUCKET_READ_KEY",
});
const data = await bucket.getMedia({
query: {
folder: "product-images", // Get media in folder
},
limit: 2,
});

Example Response

{
"media": [
{
"id": "5feb42f3601e2b3a6151289a",
"name": "9c4d6b70-49e5-11eb-98a2-810fade44566-logo-layout-1.jpg",
"original_name": "logo-layout-1.jpg",
"size": 256652,
"type": "image/jpeg",
"bucket": "5e6818d8e11cffafef7a6230",
"created": "2020-12-29T14:53:39.847Z",
"location": "https://cdn.cosmicjs.com",
"folder": "product-images",
"url": "https://cdn.cosmicjs.com/9c4d6b70-49e5-11eb-98a2-810fade44566-logo-layout-1.jpg",
"imgix_url": "https://imgix.cosmicjs.com/9c4d6b70-49e5-11eb-98a2-810fade44566-logo-layout-1.jpg"
},
{
"id": "5feb42f2601e2b3a61512899",
"name": "9c5a3cb0-49e5-11eb-98a2-810fade44566-logo-layout-2.jpg",
"original_name": "logo-layout-2.jpg",
"size": 170482,
"type": "image/jpeg",
"bucket": "5e6818d8e11cffafef7a6230",
"created": "2020-12-29T14:53:38.494Z",
"location": "https://cdn.cosmicjs.com",
"folder": "product-images",
"url": "https://cdn.cosmicjs.com/9c5a3cb0-49e5-11eb-98a2-810fade44566-logo-layout-2.jpg",
"imgix_url": "https://imgix.cosmicjs.com/9c5a3cb0-49e5-11eb-98a2-810fade44566-logo-layout-2.jpg"
}
],
"total": 10,
"limit": 2
}

Get Media

Returns a single Media by id from your Bucket.

ParameterRequiredTypeDefaultDescription
read_keyrequiredStringRestrict read access to your Bucket
propsStringDeclare which properties to return in comma-separated string. Reference full Media for all available properties. Example: ?props=name,url,imgix_url,metadata
prettyEnumfalsetrue, Makes the response more reader-friendly

Definition

GET /v2/buckets/${YOUR_BUCKET_SLUG}/media/:id

Methods

Cosmic.getSingleMedia()

Example Request

const Cosmic = require("cosmicjs")(); // empty init
const bucket = Cosmic.bucket({
slug: "YOUR_BUCKET_SLUG",
read_key: "YOUR_BUCKET_READ_KEY",
});
const data = await bucket.getMedia({
id: "5f331eac9d52b17aee21d1b4",
props: "id,name,metadata,imgix_url", // get only what you need
});

Example Response

{
"media": {
"id": "5f331eac9d52b17aee21d1b4",
"name": "d319ff30-13b7-11e9-acee-bd778576f320-default_profile.png",
"metadata": {
"ok": true
},
"imgix_url": "https://imgix.cosmicjs.com/d319ff30-13b7-11e9-acee-bd778576f320-default_profile.png"
}
}

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.

Before imgix

The image is full size and not optimized: Image

<img src="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 to the end of the URL: Image

<img src="https://imgix.cosmicjs.com/8d508870-9988-11ec-9edf-8d8ed23fd38e-starry.jpg?w=100&auto=format" />

There are lots of image processing capabilities with this library as well as a react imgix component to automate optimizations. Check out the imgix documentation for more info.

Add Media

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

Required
Your Bucket write_key must be passed as Authorization Bearer in the header of the request. This can be found in Bucket Settings > API Access in your Admin Dashboard.

Quick Tip
The base endpoint is different than other REST API requests with a higher upload size limit of 900MB.

ParameterRequiredTypeDescription
mediarequiredMedia Object (see below)Media object with specific properties
folderStringMedia folder slug
metadataObjectKey / value data store
trigger_webhookBooleanTriggers corresponding Media action Webhook (See Webhooks).

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:

ParameterRequiredTypeDescription
originalnamerequiredStringThe name of your file (something.jpg)
bufferFile BufferThe File Buffer

Definition

POST https://upload.cosmicjs.com/v2/buckets/${YOUR_BUCKET_SLUG}/media

Methods

Cosmic.addMedia()

Example Request

const Cosmic = require("cosmicjs")(); // empty init
const bucket = Cosmic.bucket({
slug: "YOUR_BUCKET_SLUG",
read_key: "YOUR_BUCKET_READ_KEY",
write_key: "YOUR_BUCKET_WRITE_KEY",
});
const media_object = req.files[0]; // Using Multer
// OR:
// const media_object = { originalname: filename, buffer: filedata } // Not using Multer
const data = await bucket.addMedia({
media: media_object,
folder: "your-folder-slug",
metadata: {
caption: "Beautiful picture of the beach",
credit: "Tyler Jackson",
},
});
// 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": {
"id": "602fd622853cca45f4c9fd96",
"name": "c20391e0-b8a4-11e6-8836-fbdfd6956b31-test.png",
"original_name": "test.png",
"size": 457307,
"folder": "folder-name",
"type": "image/png",
"bucket": "5839c67f0d3201c114000004",
"created": "2016-12-02T15:34:05.054Z",
"location": "https://cdn.cosmicjs.com",
"url": "https://cdn.cosmicjs.com/c20391e0-b8a4-11e6-8836-fbdfd6956b31-test.png",
"imgix_url": "https://imgix.cosmicjs.com/c20391e0-b8a4-11e6-8836-fbdfd6956b31-test.png"
}
}

Examples

Next.js

The following example uses Next.js to create a route (POST /api/file) and formidable to accept data from a form that will upload a file to your Bucket Media area. View full page sandbox.

Multer: Server-Side

The following example uses Express and Multer to create a route (POST /upload) that will upload a file to your Bucket Media area. This is an example from the article Upload Media to Your Cosmic Bucket Using Multer.

// index.js
const fs = require("fs");
const Cosmic = require("cosmicjs")(); // empty init
const multer = require("multer");
const express = require("express");
var app = express();
/* Add your Bucket API access keys by going to Bucket > Settings > API Access
after logging in at https://app.cosmicjs.com/login
*/
const bucket = Cosmic.bucket({
slug: "YOUR_BUCKET_SLUG",
read_key: "YOUR_BUCKET_READ_KEY",
write_key: "YOUR_BUCKET_WRITE_KEY",
});
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + "/uploads");
},
filename: function (req, file, cb) {
cb(null, file.fieldname + "-" + Date.now());
},
});
var upload = multer({ storage: storage });
app.post("/upload", upload.single("file"), async function (req, res) {
try {
const media_object = {
originalname: req.file.originalname,
buffer: fs.createReadStream(req.file.path),
};
const response = await bucket.addMedia({ media: media_object });
return res.json(response);
} catch (e) {
console.log(e);
}
});
app.listen(5000);

React Dropzone: Client-side

React Dropzone is a popular file uploader on the client-side. For implementation, read the React Dropzone docs on GitHub.

View full screen / fork on StackBlitz

Edit Media

Edit an existing Media by id in your Bucket.

Required
Your Bucket write_key must be passed as Authorization Bearer in the header of the request. This can be found in Bucket Settings > API Access in your Admin Dashboard.

ParameterTypeDescription
folderStringSlug of the folder where you want to move the media
metadataObjectJSON object
trigger_webhookBooleanTriggers corresponding Media action Webhook (See Webhooks).

Note: At least one of the Parameters is required to process the request.

Definition

PATCH https://api.cosmicjs.com/v2/buckets/${YOUR_BUCKET_SLUG}/media/:id

Header

{
"Authorization": "Bearer YOUR_BUCKET_WRITE_KEY"
}

Example Body (JSON)

{
"metadata": {
"avatar": true
}
}

Example Response

{
"message": "Media with id ':id' edited successfully in bucket."
}

Delete Media

Delete an existing Media by id from your Bucket.

Required
Your Bucket write_key must be passed as Authorization Bearer in the header of the request. This can be found in Bucket Settings > API Access in your Admin Dashboard.

Query ParameterTypeDescription
trigger_webhookBooleanTriggers corresponding Media action Webhook (See Webhooks).

Methods

Cosmic.deleteMedia()

Example Request

const Cosmic = require("cosmicjs")(); // empty init
const bucket = Cosmic.bucket({
slug: "YOUR_BUCKET_SLUG",
read_key: "YOUR_BUCKET_READ_KEY",
});
const data = await bucket.deleteMedia({
id: "5a4b18e12fff7ec0e3c13c65",
});

Example Response

{
"message": "Media with id ':id' deleted successfully from bucket."
}