Content Lake (Datastore)

Upload, query, and delete assets

Programmatically manage assets in your project dataset.

In cases where the UI doesn't offer enough control or automation, you can use Sanity's APIs to interact with assets.

The techniques in this guide apply to assets stored in a project's dataset. Reference the Managing assets portion of the Media Library documentation for details on working with Media Library assets.

For details on rendering and transforming assets for your front end applications, see the Presenting Images documentation.

Upload an asset

Gotcha

In cases where uploading assets in the UI is impractical, like batch uploads or migrations, you can use the API directly.

Query and browse assets

To browse project assets from the Studio interface, install the Sanity Media plugin. This adds a new tool to the toolbar and enables Studio users to browse and manage assets.

You can also query all images with GROQ using the following query:

Run GROQ queries through Vision, the client, or with the Query API.

You can also use this method to query Media Library assets that have been linked to your dataset.

If viewing asset data within another document type, you'll need to follow the asset's reference to view the metadata or URL. For example:

*[_type == 'post'] {
  mainImage {
    asset->
  }
}

Deleting assets

Deleting an asset can be performed by deleting the associated asset document.

import {createClient} from '@sanity/client'
const config = {
  projectId: 'myProjectID',
  dataset: 'mydataset',
  apiVersion: '2021-08-29',
  token: 'myToken'
}
const client = createClient(config)
// Note: this is the _id of the asset document.
client.delete('image-abc123_0G0Pkg3JLakKCLrF1podAdE9-538x538-jpg')
  .then(result => {
    console.log('deleted image asset', result)
  })

It's important to note that while the file is deleted, the CDN might have your asset cached so it may not disappear immediately.

Download assets

In order to download an asset you need to append ?dl=<asset-of-your-choice.jpg> to the asset URL. If you leave the filename blank, the original filename will be used if present. If the original filename is not available, the id of the file will be used instead.

// GROQ query

*[_type == "post"] {
  title,
  mainImage{
    asset->url
  }
}
// Then you can use the URL in HTML for example like this:
// <a href={`${mainImage}?dl=`}>Hero Image</a>

Was this page helpful?