Raster

Client

createRasterClient, the functions for libraries, assets, uploads, variants, and search, and the image URL helpers and formatters.

createRasterClient creates a client for the Raster REST API. It runs in the browser and Node.js, and @raster-app/react re-exports it.

import {
  createRasterClient,
  listAssets,
  listLibraries,
  localStorageCredentialStore,
} from '@raster-app/sdk'

const raster = createRasterClient({
  host: { name: 'My App', openExternal: (url) => window.open(url, '_blank') },
  credentials: localStorageCredentialStore(),
})

const libraries = await listLibraries(raster, { organizationId: 'acme' })
const assets = await listAssets(raster, {
  organizationId: 'acme',
  libraryId: 'lib-1',
})

Create one client and reuse it. Each client keeps its own session.

Every function that calls Raster takes the client first. Your bundle keeps only the functions you import.

Configuration

OptionTypeDescription
hostRasterHostRequired with credentials. Your app's name and openExternal function. See The host.
credentialsCredentialStoreRequired unless you pass apiKey. Where the credential is stored. See Where the credential is stored.
apiKeystringAn organization API key, held in memory, in place of host and credentials. See A server client.

A server client

On a server, make the client from an organization API key:

import { createRasterClient } from '@raster-app/sdk'

const raster = createRasterClient({ apiKey: process.env.RASTER_API_KEY! })

Keep the key out of browser code.

The host

host.name is your app's name on Raster's Connect page and in Profile settings → Connected apps.

host.openExternal(url) opens a URL in the user's browser: the sign-in page, and Open in Raster in RasterPicker. Its return value is ignored, so window.open and async functions both work.

Functions

FunctionResolves with
getMe(raster)The organizations and libraries the credential reaches.
listLibraries(raster, options)Every library in an organization.
getLibrary(raster, options)One library, with its assetsCount.
listAssets(raster, options)One page of a library's assets.
listAssetPage(raster, options)One page of a library's assets, with hasMore, total and nextCursor.
iterateAssets(raster, options)Each page of a library in turn, as an async iterator.
getAsset(raster, options)One asset, with its variants.
uploadAsset(raster, options)The new asset, once Raster has the file.
waitUntilProcessed(raster, options)The processed asset, or null.
promoteVariant(raster, options)The ids the promote touches, once Raster accepts it.
waitUntilPromoted(raster, options)The asset once the promote lands, or null.
searchAssets(raster, options)One page of search results.
signInWithDevice(raster, options)The stored credentials. See Device sign-in.
connectApiKey(raster, { apiKey })The stored credentials. See API keys.
connectSharedApiKey(raster, { apiKey, organizationId })The credentials, in memory only. See Share an API key with every user.
checkApiKey(raster, { apiKey, organizationId })Nothing, once Raster accepts the key. See Check a key before saving it.
signOut(raster)Nothing. See Sign out.

Failed calls reject with a RasterApiError.

Cancelling a call

Library, asset, and search functions take an optional signal. Aborting it rejects the call with ABORTED; a signal from AbortSignal.timeout() rejects with TIMEOUT. isAbortError(error) tells a cancel from a failure:

import { isAbortError, searchAssets, toUserMessage } from '@raster-app/sdk'

const controller = new AbortController()

try {
  await searchAssets(raster, {
    organizationId: 'acme',
    query: 'sunset',
    signal: controller.signal,
  })
} catch (error) {
  if (!isAbortError(error)) alert(toUserMessage(error))
}

Sign-in takes a signal too.

What the credential reaches

getMe(raster) resolves with GET /me. To read it:

  • meOrganizationList(me): { id, name, libraryCount } per organization.
  • meOrganizations(me): { organizationId, organizationName, plan, organizationAccess, libraries } per organization. organizationAccess is 'read' or 'write' when an API key reaches every library in the organization, including ones created later, and null otherwise.
  • meLibraryAccess(me, organizationId, libraryId): 'read', 'write', or null.

Libraries

listLibraries(raster, { organizationId, organizationName?, signal? }) resolves with every Library in the organization, each with organizationId and organizationName (what you passed, or null).

getLibrary(raster, { organizationId, libraryId, organizationName?, signal? }) resolves with one Library, including its assetsCount. A library the credential can't reach rejects with a 404.

Assets

listAssets(raster, { organizationId, libraryId, page?, after?, pageSize?, approval?, mediaType?, uploaderRef?, uploader?, signal? }) resolves with one page of assets. page starts at 1; pageSize defaults to 50. hasMorePages(pageLength, pageSize?) is true when a page came back full.

listAssetPage(raster, options) takes the same options and resolves with { assets, hasMore, total, nextCursor }. hasMore is true when another page may follow; total is the library's asset count, or null when unknown. Pass nextCursor as after for the page that follows it:

import { listAssetPage } from '@raster-app/sdk'

const first = await listAssetPage(raster, { organizationId: 'acme', libraryId: 'lib-1' })
if (first.nextCursor !== null) {
  const second = await listAssetPage(raster, {
    organizationId: 'acme',
    libraryId: 'lib-1',
    after: first.nextCursor,
  })
}

approval (in_review, approved, needs_changes or none) lists only assets in that approval state, and total counts them. mediaType (image or video) lists only assets of that kind, and total counts them. uploaderRef lists only the assets uploaded for one of your users, and uploader: 'external' lists the assets uploaded for any of them; total counts only those. See Uploads.

iterateAssets(raster, { organizationId, libraryId, pageSize?, approval?, mediaType?, uploaderRef?, uploader?, signal? }) reads every page of a library in turn, following nextCursor:

import { iterateAssets } from '@raster-app/sdk'

for await (const assets of iterateAssets(raster, { organizationId: 'acme', libraryId: 'lib-1' })) {
  console.log(assets.length)
}

getAsset(raster, { organizationId, libraryId, assetId, signal? }) resolves with one asset and its variants.

Uploads

import { uploadAsset, waitUntilProcessed } from '@raster-app/sdk'

async function uploadFile(file: File) {
  const uploaded = await uploadAsset(raster, {
    organizationId: 'acme',
    libraryId: 'lib-1',
    source: file,
  })
  return waitUntilProcessed(raster, {
    organizationId: 'acme',
    libraryId: 'lib-1',
    assetId: uploaded.id,
    parentId: uploaded.parentId,
  })
}
OptionDescription
organizationId, libraryIdRequired. The target library.
sourceRequired. A Blob, a File, or { bytes, filename, contentType } with Uint8Array bytes.
filenameOverrides the source's name. An unnamed Blob is named upload.
parentIdUploads the file as a variant of this asset.
uploader{ ref, name?, email?, avatarUrl? }: attributes the upload to one of your own users. API keys only.
signalCancels the upload.

uploadAsset resolves once Raster has the file, with id, parentId, url, appUrl, and name. Raster then adds dimensions, sizes, and blurhash. waitUntilProcessed resolves with the processed Asset, or null if it's still processing when the wait ends. For a variant, it resolves with the parent. Limits and accepted files: POST …/assets.

uploader is optional. If your app uploads files for its users, pass it to say which user an upload is for: ref is your ID for them, and name, email and avatarUrl are optional. Raster shows that user as the asset's uploader and remembers their details for each ref, so later uploads can send ref alone. To count a user's uploads, filter by uploaderRef and read total:

await uploadAsset(raster, {
  organizationId: 'acme',
  libraryId: 'lib-1',
  source: file,
  uploader: { ref: 'guest-4821', name: 'John Doe', email: 'john@example.com' },
})

const { total } = await listAssetPage(raster, {
  organizationId: 'acme',
  libraryId: 'lib-1',
  uploaderRef: 'guest-4821',
  pageSize: 1,
})

For the REST fields and limits, see Attribute an upload to your user.

Variants

import { promoteVariant, waitUntilPromoted } from '@raster-app/sdk'

const promotion = {
  organizationId: 'acme',
  libraryId: 'lib-1',
  assetId: 'abc123',
  variantId: 'var789',
}

await promoteVariant(raster, promotion)
const asset = await waitUntilPromoted(raster, promotion)

promoteVariant makes a variant the asset's default, served at the same URL. It resolves with assetId, promotedVariantId, and demotedVariantId (the new variant holding the previous default). waitUntilPromoted resolves with the asset once the promote lands, or null. Rules: POST …/promote.

import { searchAssets } from '@raster-app/sdk'

const { hits, found } = await searchAssets(raster, {
  organizationId: 'acme',
  query: 'sunset',
})

searchAssets resolves with one page of a SearchResult: assets whose name, description, or tags match, ranked by relevance.

Search also matches by meaning on paid plans; see how search ranks results.

OptionDescription
organizationIdRequired. The organization to search.
queryRequired. The search text.
libraryIdsLimits the search to these libraries. Defaults to every library the credential reaches.
pageThe page, starting at 1.
pageSizeHits per page. Defaults to 50.
signalCancels the search.

Blank queries and unreachable library ids: GET …/search/assets.

Session

Outside React, these functions read the credential in use. In React, use useSession().

import { isConfigured, loadSession, onSessionChange } from '@raster-app/sdk'

const credentials = await loadSession(raster)
console.log(isConfigured(credentials))

const unsubscribe = onSessionChange(raster, (next) => {
  console.log(isConfigured(next))
})
FunctionDescription
loadSession(raster)Reads the stored credential and resolves with it. Call it at startup, before the others.
getSession(raster)The stored credentials, or undefined until read.
onSessionChange(raster, listener)Calls listener with the credentials when they change. Returns an unsubscribe function.
isConfigured(credentials)true when there is a sign-in or an API key.
getCredentialIdentity(raster)An id for the credential in use, the same until the next sign-in. null when signed out.

Image helpers

Each helper takes an Asset, AssetVariant, or SearchHit.

HelperReturns
getThumbUrl(asset)A small URL for grids. undefined when there's none.
getPreviewUrl(asset)A large URL for previews. undefined when there's none.
getFullSizeUrl(asset)The full-size URL to hand your app on pick. null when there's none.
getShareUrl(asset)The original file's URL, versioned. null without a url.
getBlurhashPlaceholder(asset)A blurred data: URL to show while loading. null without a blurhash or outside a browser.
isReady(asset)true once the asset is processed and has a full-size URL.

These URLs change when the asset's file is replaced, as by a promote.

To choose a size yourself:

  1. parseSizes(asset.sizes) returns an object from size to URL, or null.
  2. pickSizeUrl(sizes, targetEdge) returns the smallest size at least targetEdge pixels on its longest edge, or the largest one.
  3. versionedUrl(url, asset.contentVersion) makes the URL change when the file is replaced.

Formatters

Formatters match the Raster app: decimal units (1 MB is 1,000,000 bytes) and en-US dates.

FunctionReturns
formatBytes(bytes)512 B, 2 KB, 4.2 MB, 3.00 GB.
formatFileSize(bytes)formatBytes, or '' for null, undefined, negative, or non-finite.
formatDate(date)Jan 15, 2024.
formatDateLong(date)The date with weekday and time.
formatRelativeTime(date)just now, 5m ago, 3h ago, 2d ago, then formatDate from 7 days on.

Date formatters take a Date or Unix milliseconds (as in created and updated) and return '' for null.

Constants and types

ExportDescription
API_VERSIONThe Api-Version the client sends. See The Api-Version header.
ASSETS_PAGE_SIZE, SEARCH_PAGE_SIZEDefault pageSize for listAssets and searchAssets: 50.

Asset, AssetVariant, Library, Tag, Uploader, SearchHit, and SearchResult match the API's objects.

On this page