Media Library API reference
HTTP endpoints reference for the Media Library API
The Media Library API lets you programmatically interact with assets in your organization’s Media Library.
Authentication
- All requests to private data must be authenticated. Requests to public information, like public assets, are available without an authentication token.
- Manipulating documents requires read+write access permission for Media Library.
Base API server URL
Media Library API base URL
https://api.sanity.io/{apiVersion}Variables
- apiVersionstringdefault:
"v2025-02-19"API version
Endpoints
Mutate media in the Media Library
/media-libraries/{libraryId}/mutateYou can use this endpoint to create, update, or delete documents in the Media Library. This uses the same mutation syntax as Content Lake's Mutation API.
Path parameters
Media library identifier
Example:mlAbC123xYz9
Query parameters
Validate the mutations and return the result without saving any changes.
Request body application/json
Show child attributes
items
- createobject
Create a document. Fails if a document with the same
_idexists. - createIfNotExistsobject
Create a document only if no document with the same
_idexists. - createOrReplaceobject
Create a document, or replace the existing document with the same
_id. - deleteobject
Delete the document with the given
id.Show child attributes
Show child attributes
- ifRevisionIDstring
Responses
Mutation successful
ID of the transaction
application/json{
"transactionId": "2ytbpDyMzSFDiMWMZQvN1i",
"results": [
{
"id": "image-123",
"operation": "update"
}
]
}Query media in the Media Library
/media-libraries/{libraryId}/queryUse GROQ to query the Media Library.
Requests without a token are allowed, but return only data that is publicly readable. On a private library they return an empty result rather than an error.
See the GROQ documentation for more information on writing GROQ queries.
Path parameters
Media library identifier
Example:mlAbC123xYz9
Query parameters
- assets:
*[_type == "sanity.asset"]aspects:*[_type == "sanity.asset.aspect"]projections:*[_type == "sanity.asset"] { _id, _type, title }
Responses
OK
- querystring
The GROQ query and projection executed against the Media Library.
- resultstring|number|boolean|array|object|null
The result of the query. The type of the result depends on the query response.
For example, if the query returns a single document, the result will be an object. If it returns a list of documents, the result will be an array.
- syncTagsarray
A list of sync tags. Sync tags are used with the Live Content API to track document changes.
Show child attributes
items
- string
- msnumber
Server-side query time in milliseconds
Query media in the Media Library with a request body
/media-libraries/{libraryId}/querySame as the GET endpoint, with the query sent in a JSON body. Use this for long queries.
Path parameters
Media library identifier
Example:mlAbC123xYz9
Request body application/json
The GROQ query and projection to execute against the Media Library.
- paramsobject
Values for
$-prefixed parameters used in the query.
application/json{
"query": "*[_type == \"sanity.asset\" && title match $term]{_id, title}",
"params": {
"term": "chair"
}
}Responses
OK. Same response body as the GET endpoint.
- object
List references to an asset
/media-libraries/{libraryId}/references/documents/{assetId}/toGet references to an asset document from other documents and datasets. At this time, this does not support draft or version documents.
Note: this endpoint is currently only available on version vX of the API. Requests on dated API versions return 400.
Path parameters
Media library identifier
Example:mlAbC123xYz9The ID of the asset to get references for.
Query parameters
- cursorstring
A cursor to paginate through the results. The cursor is returned in the
nextCursorfield of the response. When
true,sourceFieldPathsis returned as an empty array.Only
publishedis supported. Any other value returns 400.
Responses
OK
- referencesarray
Show child attributes
items
- sourceDocumentRefstring
The global document reference ID of the document that references the asset.
This is made up of
{resourceType}:{resourceId}:{documentId}. For datasets, the resource ID is{projectId}.{dataset}.Example:dataset:y3d2bw.production:document-id1234 - sourceFieldPathsarray
A list of field path locations in the document that reference the asset.
Example["mainImage.media._ref","body[4].media._ref"]Show child attributes
items
- string
- totalCountinteger
Number of references in this page of results. Pages hold at most 100 references.
- nextCursorstring
Cursor for the next page of results. It can be returned even when no more results exist, so keep requesting pages until the response has no
nextCursor.
application/json{
"references": [
{
"sourceDocumentRef": "dataset:y856rro4.production:196167ef-8c0b-4d7c-ae18-71179e424c19",
"sourceFieldPaths": [
"mainImage.media._ref"
]
},
{
"sourceDocumentRef": "dataset:y856rro4.production:503cceed-a1b5-4552-9cc1-c6fddf28de59",
"sourceFieldPaths": [
"body[4].media._ref"
]
},
{
"sourceDocumentRef": "dataset:y856rro4.production:drafts.196167ef-8c0b-4d7c-ae18-71179e424c19",
"sourceFieldPaths": [
"gdrImage._ref",
"mainImage.media._ref"
]
}
],
"totalCount": 3,
"nextCursor": "gdr1:eyJucyI6Ink4NTZycm80LnByb2R1Y3Rpb24uS2RSS2c4Z0tJQVFhIiwiaWQiOiJkcmFmdHMuMTk2MTY3ZWYtOGMwYi00ZDdjLWFlMTgtNzExNzllNDI0YzE5In0"
}Upload an asset to the media library
/media-libraries/{libraryId}/uploadPath parameters
Media library identifier
Example:mlAbC123xYz9
Query parameters
- typestring
Type of asset being uploaded. If omitted, the type is detected from the file content.
- filenamestring
Original filename
- titlestring
Asset title. Cannot be combined with
autoGenerateTitle. If omitted andfilenameis provided, the filename is used as the initial title. - autoGenerateTitleboolean
Generate a title from image content during image processing. Cannot be combined with
title, even when set to false. - assetIdstring
Existing asset ID to add a new version to. Omit to create an asset. The upload must be the same asset type as the existing asset, and cannot be combined with an
aspectspart. - sessionIdstring
Upload session identifier. Must not be empty.
- cdnAccessPolicystring
CDN access policy. When
assetIdis set, defaults to the existing asset's policy, and a different value returns 400. - sha1string
SHA-1 hash of the file. If an asset with this hash already exists, the request returns 409. Otherwise, the uploaded content is checked against the hash and a mismatch returns 400.
- parentstring
Document ID of the
sanity.directoryto place the uploaded asset in. If omitted, the uploaded asset is not placed in a folder. Must reference asanity.directory,sanity.treeis not a valid value. - rootDirectorystring
Document ID of the root
sanity.directoryfor the uploaded asset. Requiresparentto also be set.
Request body multipart/form-data
- aspectsobject
Optional JSON object of aspect values to set on the asset at creation. JSON
nullis accepted and treated as equivalent to omitting the field. Capped at 1 MiB; larger payloads return 400. The asset file to upload. Must be the last part in the multipart body — any parts after
fileare not read, because the file's reader is consumed lazily by the upload pipeline.
application/octet-streamResponses
Asset uploaded successfully
Show child attributes
Asset container ID
Document type
Type of asset
CDN access policy for the asset
- urlstring (uri)
Asset URL, when set
- parentobject
- rootDirectoryobject
- _revstring
- _createdAtstring (date-time)
- _updatedAtstring (date-time)
Asset instance with metadata
Upload session information, or null when no upload session is returned.
Search for assets and references
/media-libraries/{libraryId}/refsearchPath parameters
Media library identifier
Example:mlAbC123xYz9
Query parameters
Search term
- filterstring
GROQ filter expression, combined with the search using AND.
- projectionstring
GROQ projection for each result. Include
_id, ornextCursoris never returned. Perspective to search. Use
published,preview,raw, or a release name.- cursorstring
The
nextCursorvalue from the previous page. Results are ordered by_iddescending. Maximum number of results to return
Responses
Search results
- resultsrequired
The matching documents, shaped by
projection Cursor for the next page, or
nullwhen the page isn't full or results have no_idNumber of results in this page
Create a new signing key
/media-libraries/{libraryId}/signing-keysPath parameters
Media library identifier
Example:mlAbC123xYz9
Responses
Signing key created successfully
Signing key ID
Signing key name
Public key
Key type
Private key (returned only once)
Status of the signing key
Creation timestamp
Last update timestamp.
nullon create.Revocation timestamp.
nullon create.
List all signing keys
/media-libraries/{libraryId}/signing-keysPath parameters
Media library identifier
Example:mlAbC123xYz9
Responses
List of signing keys
Get a specific signing key
/media-libraries/{libraryId}/signing-keys/{keyId}Path parameters
Media library identifier
Example:mlAbC123xYz9Signing key identifier
Responses
Signing key details
Revoke a signing key
/media-libraries/{libraryId}/signing-keys/{keyId}Revokes the signing key. The key isn't removed; it's still returned by the get and list endpoints with status set to revoked.
Get video playback information
/media-libraries/{libraryId}/video/{videoId}/playback-infoPublic videos don't need a token. Videos with signed playback require a bearer token; without one, the request returns 404.
Path parameters
Media library identifier
Example:mlAbC123xYz9Video asset instance ID or asset container ID. If a container ID is provided, resolves to the current version.
Query parameters
- thumbnailWidthinteger
Thumbnail width in pixels
- thumbnailHeightinteger
Thumbnail height in pixels
- thumbnailTimenumber
Time in seconds of the frame to use for the thumbnail
- thumbnailFitstring
How the thumbnail fits the requested width and height
Thumbnail image format
- animatedWidthinteger
Animated image width in pixels
- animatedHeightinteger
Animated image height in pixels
- animatedStartnumber
Start time in seconds for the animated image
- animatedEndnumber
End time in seconds for the animated image
- animatedFpsinteger
Frame rate of the animated image
Animated image format
Storyboard image format
Format for subtitle URLs
- expirationstring
How long signed playback URLs stay valid, as a duration string such as
90s,30m, or2h. Only applies to videos with signed playback. Defaults to the video's duration plus a buffer.Example:2h
Responses
Video playback information
Playback ID of the video
Show child attributes
Playback URL
- tokenstring
Access token if required
- expires_atstring (date-time)
Expiration timestamp
Show child attributes
Playback URL
- tokenstring
Access token if required
- expires_atstring (date-time)
Expiration timestamp
Show child attributes
Playback URL
- tokenstring
Access token if required
- expires_atstring (date-time)
Expiration timestamp
Show child attributes
Playback URL
- tokenstring
Access token if required
- expires_atstring (date-time)
Expiration timestamp
Video duration in seconds
- aspectRationumber|null
Video aspect ratio, or
nullif unknown - subtitlesarray
Available subtitle tracks
Show child attributes
items
- renditionsarray
Available downloadable MP4 renditions
Show child attributes
items
Get video playback information headers
/media-libraries/{libraryId}/video/{videoId}/playback-infoRedirect to video playback URL
/media-libraries/{libraryId}/video/{videoId}/playback/{type}Redirects to the playback URL for the given resource type. Accepts the same query parameters as the playback-info endpoint, which shape the redirect target (for example, thumbnail size). Public videos don't need a token. Videos with signed playback require a bearer token; without one, the request returns 404.
Path parameters
Media library identifier
Example:mlAbC123xYz9Video asset instance ID or asset container ID. If a container ID is provided, resolves to the current version.
Type of playback resource
Query parameters
- thumbnailWidthinteger
Thumbnail width in pixels
- thumbnailHeightinteger
Thumbnail height in pixels
- thumbnailTimenumber
Time in seconds of the frame to use for the thumbnail
- thumbnailFitstring
How the thumbnail fits the requested width and height
Thumbnail image format
- animatedWidthinteger
Animated image width in pixels
- animatedHeightinteger
Animated image height in pixels
- animatedStartnumber
Start time in seconds for the animated image
- animatedEndnumber
End time in seconds for the animated image
- animatedFpsinteger
Frame rate of the animated image
Animated image format
Storyboard image format
Format for subtitle URLs
- expirationstring
How long signed playback URLs stay valid, as a duration string such as
90s,30m, or2h. Only applies to videos with signed playback. Defaults to the video's duration plus a buffer.Example:2h
Responses
Redirect to playback URL
Get playback redirect headers
/media-libraries/{libraryId}/video/{videoId}/playback/{type}Redirect to video rendition URL
/media-libraries/{libraryId}/video/{videoId}/renditions/{name}Returns a redirect to the rendition (downloadable MP4) for the specified video. The signed redirect URL is valid for one hour. Public videos don't need a token. Videos with signed playback require a bearer token; without one, the request returns 404.
Path parameters
Media library identifier
Example:mlAbC123xYz9Video asset instance ID or asset container ID. If a container ID is provided, resolves to the current version.
Rendition name (e.g., "720p.mp4", "1080p.mp4")
Query parameters
- dlstring
Download trigger. Boolean true uses rendition name as filename, string value uses as custom filename.
Responses
Redirect to rendition URL
Get video rendition redirect headers
/media-libraries/{libraryId}/video/{videoId}/renditions/{name}Path parameters
Media library identifier
Example:mlAbC123xYz9Video asset instance ID or asset container ID. If a container ID is provided, resolves to the current version.
Rendition name (e.g., "720p.mp4", "1080p.mp4")
Responses
Redirect headers
Generate subtitles using AI
/media-libraries/{libraryId}/video/{videoId}/subtitlesTriggers AI-powered subtitle generation for the specified video. Returns immediately with a processing status; the subtitle will be updated via webhook when generation completes. Requires the organization to have AI features enabled; returns 400 if they are disabled for the org.
Path parameters
Media library identifier
Example:mlAbC123xYz9Video asset instance ID or asset container ID
Request body application/json
Language code for the generated subtitles, or
autofor auto-detection. Only these languages are supported for generation.
Responses
Subtitle generation started
Subtitle document ID
ISO 639-1 language code
Whether this subtitle represents closed captions
Current processing status
- originstring
How the subtitle was created
Upload a subtitle file
/media-libraries/{libraryId}/video/{videoId}/subtitles/uploadUploads a VTT or SRT subtitle file for the specified video. The subtitle file content is sent as the raw request body (not JSON). Metadata is passed via query parameters. If format is omitted, content starting with WEBVTT is treated as VTT and anything else as SRT. Empty or unparseable content returns 400.
Path parameters
Media library identifier
Example:mlAbC123xYz9Video asset instance ID or asset container ID
Query parameters
ISO 639-1 two-letter language code (e.g., "en", "fr")
- formatstring
Subtitle format. Auto-detected from content if omitted.
- closedCaptionsboolean
Whether this subtitle track represents closed captions (includes non-speech audio descriptions)
Request body text/plain
- string
Raw subtitle file content (VTT or SRT)
application/octet-streamResponses
Subtitle upload accepted
Subtitle document ID
ISO 639-1 language code
Whether this subtitle represents closed captions
Current processing status
- originstring
How the subtitle was created
Delete a subtitle
/media-libraries/{libraryId}/video/{videoId}/subtitles/{subtitleId}Deletes the specified subtitle and its associated track from the video provider.
Path parameters
Media library identifier
Example:mlAbC123xYz9Video asset instance ID or asset container ID
Subtitle document ID
Responses
Subtitle deleted successfully
Upload an asset to the media library from a URL
/media-libraries/{libraryId}/from-urlFetches a public or preauthorized HTTPS URL through Sanity's bounded
egress proxy, then processes the response with the ordinary Media
Library upload pipeline. The source is limited to 50 MiB and the fetch
may take up to 300 seconds. Caller credentials and headers are not
forwarded to the source. Provide filename in the JSON request body;
the filename query parameter used by /upload is not accepted here.
Follows up to three redirects. The source and each redirect destination must use HTTPS without embedded credentials and pass the source policy. The JSON request body is limited to 1 MiB plus 4 KiB, including aspects.
The request stays open while the asset is fetched and uploaded. Allow more than 300 seconds for the client request. Media processing can continue after the response. If the connection closes or the request times out, check the library before retrying: an asset or version may already have been created.
Path parameters
Media library identifier
Example:mlAbC123xYz9
Query parameters
- typestring
Optional asset type override. If omitted, the type is detected from the source content.
- titlestring
Asset title. Cannot be combined with
autoGenerateTitle. If omitted andfilenameis provided, the filename is used as the initial title. - autoGenerateTitleboolean
Generate a title from image content during image processing. Cannot be combined with
title, even when set to false. - assetIdstring
Existing asset ID to add a version to. Omit to create an asset. Cannot be combined with an
aspectsobject. - sessionIdstring
Upload session identifier. Must not be empty.
- cdnAccessPolicystring
CDN access policy. When
assetIdis set, defaults to the existing asset's policy, and a different value returns 400. - sha1string
SHA-1 hash of the file. If an asset with this hash already exists, the request returns 409. Otherwise, the uploaded content is checked against the hash and a mismatch returns 400.
- parentstring
Document ID of the
sanity.directoryto place the uploaded asset in. If omitted, the uploaded asset is not placed in a folder. Must reference asanity.directory,sanity.treeis not a valid value. - rootDirectorystring
Document ID of the root
sanity.directoryfor the uploaded asset. Requiresparentto also be set.
Request body application/json
Public or preauthorized HTTPS source URL
- filenamestring
Optional original filename. It is not inferred from the URL.
- aspectsobject|null
Optional JSON object of aspect values to set on the asset at creation. JSON
nullis equivalent to omitting the field. Capped at 1 MiB. Cannot be combined with theassetIdquery parameter.
application/json{
"url": "https://example.com/photos/chair.jpg",
"filename": "chair.jpg"
}Responses
Asset uploaded successfully
Show child attributes
Asset container ID
Document type
Type of asset
CDN access policy for the asset
- urlstring (uri)
Asset URL, when set
- parentobject
- rootDirectoryobject
- _revstring
- _createdAtstring (date-time)
- _updatedAtstring (date-time)
Asset instance with metadata
Upload session information, or null when no upload session is returned.