AssetLibrary

View as Markdown

AssetLibrary

AssetLibrary builds a request for the published assets in a stack. Use this class to

  • list assets, one page at a time
  • filter, sort and shape the list before you send the request
  • get the number of matching assets without the assets themselves

To fetch one asset by its UID, use the Asset class instead.

client.AssetLibrary() creates the object. It takes no arguments and sends no request. Chain the options, then call FetchAll for the assets or Count for the number.

NameTypeDescription
Stack ContentstackClient

Client that sends the request.

AddParam

AddParam adds any query parameter to the request, for API options that have no method of their own.

NameTypeDescription
key (required)string

Name of the query parameter, for example include_dimension.

Default: Not applicable
value (required)string

Value of the query parameter, sent as written.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation of the parameter name or value.
  • A null key throws ArgumentNullException.
  • A key that this object already holds throws ArgumentException. This includes a key that another method on this class sets, such as limit after the Limit method.
  • environment passes AddParam, but FetchAll and Count then throw ArgumentException, because they add that parameter themselves.
  • A null value sends the parameter with an empty value.
  • An invalid parameter surfaces as an AssetException when FetchAll or Count sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. AddParam stores the pair and makes no request. The request carries it as key=value.
  • The SDK does not URL-encode the value. Encode a value that contains &, #, + or % yourself, for example with Uri.EscapeDataString.
  • For example, the API returns the height and width of each image with include_dimension set to true (Get all assets). The SDK reads them into the Dimension property of each asset.

Example

Basic usage: include the image dimensions

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary()
        .AddParam("include_dimension", "true")
        .FetchAll();

    foreach (Asset asset in assets)
    {
        if (asset.Dimension != null)
        {
            Console.WriteLine($"{asset.FileName}: {asset.Dimension["width"]} x {asset.Dimension["height"]}");
        }
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

AssetFields

AssetFields requests additional field groups for each asset, such as its visual markups.

NameTypeDescription
fields (required)string[]

Field group names, for example visual_markups. Adds each group to the response.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation of the field group names.
  • A call with no arguments, null or an empty array changes nothing.
  • A second call with at least one field group throws ArgumentException, because the SDK stores the asset_fields[] parameter once. Pass every group in one call.
  • An invalid group name surfaces as an AssetException when FetchAll sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. AssetFields adds one asset_fields[] query parameter per group and makes no request.
  • With visual_markups, the API returns the hotspot and bounding-box annotations of each asset under the visual_markups key. An asset with no markups returns an empty array (Get all assets).
  • The SDK code comments also name user_defined_fields, embedded_metadata and ai_generated_metadata as accepted values.
  • Asset has no property for these groups. Read each one with the Asset Get method under the key of the same name.

Example

Basic usage: request visual markups for every asset

using System;
using System.Collections.Generic;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary()
        .AssetFields("visual_markups", "user_defined_fields")
        .FetchAll();

    foreach (Asset asset in assets)
    {
        int markupCount = asset.Get("visual_markups") is List<object> markups ? markups.Count : 0;
        Console.WriteLine($"{asset.FileName}: {markupCount} visual markups");
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

Count

Count sends the request and returns only the number of published assets that match the options on the instance.

Returns: Task<JsonObject>. The response body as a JSON object.

Validation

  • There is no client-side validation.
  • Count throws AssetException when the API rejects the request. StatusCode, ErrorCode, Message and Errors carry the details from the error response.
  • Count also throws AssetException when it cannot send the request or read the response body, with the original error as InnerException.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Count adds count=true to the instance, then sends one GET /assets request with every option on the instance.
  • With count=true, the API returns only the count, not the assets (Count).
  • Filters such as Where and Tags apply, so the count covers only the matching assets.
  • Count returns the whole response body as a JsonObject (System.Text.Json.Nodes). The SDK does not extract the number.
  • To get the assets and the total in one request, use the IncludeCount method with FetchAll instead.

Example

Basic usage: count the assets in a stack

using System;
using System.Text.Json.Nodes;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    JsonObject result = await client.AssetLibrary().Count();
    Console.WriteLine(result.ToJsonString());
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

Edge case: count first, then list, with separate instances

using System;
using System.Text.Json.Nodes;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    // Count leaves count=true on its instance, so list with a new one.
    JsonObject total = await client.AssetLibrary().Where("content_type", "image/png").Count();
    ContentstackCollection<Asset> page = await client.AssetLibrary().Where("content_type", "image/png").FetchAll();

    Console.WriteLine(total.ToJsonString());
    foreach (Asset asset in page)
    {
        Console.WriteLine(asset.FileName);
    }
}
catch (ContentstackException e)
{
    Console.WriteLine(e.Message);
}

Except

Except sends the list of top-level fields to leave out of each asset in the response.

NameTypeDescription
fieldUids (required)string[]

Field UIDs to leave out, for example description.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation of the field UIDs.
  • null or an empty array changes nothing.
  • A second call with at least one field throws AssetException, because the SDK stores each query parameter once. Pass every field in one call.
  • An invalid value surfaces as an AssetException when FetchAll sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. Except adds one except[BASE][] query parameter per field and makes no request.
  • The Exclude Operator section of the API reference documents except[BASE][] for entries only, and the Get all assets request does not list it. Check the response before you rely on it for assets.
  • Properties for fields the response leaves out keep their default values, for example null.

Example

Basic usage: leave out the description and tags

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary()
        .Except(new string[] { "description", "tags" })
        .FetchAll();

    foreach (Asset asset in assets)
    {
        Console.WriteLine($"{asset.FileName}: {asset.Url}");
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

FetchAll

FetchAll sends the request and returns one page of the published assets that match the options on the instance.

Returns: Task<ContentstackCollection<Asset>>. The matching assets.

Validation

  • There is no client-side validation.
  • FetchAll throws AssetException when the API rejects the request. StatusCode, ErrorCode, Message and Errors carry the details from the error response.
  • FetchAll also throws AssetException when it cannot send the request or read the response body, with the original error as InnerException.
  • FetchAll throws ArgumentException before it sends anything when you passed environment to the AddParam method, because FetchAll adds that parameter itself.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • FetchAll sends one GET /assets request (Get all assets). It adds the client's environment, then every option on the instance, as query parameters.
  • The result holds one page. Without Limit, the API returns the first 100 assets (Pagination). The SDK does not request further pages.
  • Items holds the assets, and the collection itself is enumerable. When nothing matches, Items is empty and no exception occurs.
  • Count holds the total number of matching assets only after the IncludeCount method. Otherwise it is 0.
  • Skip and Limit on the result stay 0, because the API does not return them. See the ContentstackCollection class.
  • Each asset carries the full response data, so its getters such as GetCreateAt work.
  • FetchAll does not clear the options, so a second call on the same instance sends the same request. Do not call FetchAll on an instance that the Count method already used, because the count flag stays on the instance.

Example

Basic usage: list the assets in a stack

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary().FetchAll();
    foreach (Asset asset in assets)
    {
        Console.WriteLine($"{asset.Uid}: {asset.FileName}");
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

Edge case: read every asset, one page at a time

using System;
using System.Collections.Generic;
using System.Linq;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

const int pageSize = 100;
List<Asset> all = new List<Asset>();

try
{
    int skip = 0;
    while (true)
    {
        // Options stay on an instance, so build a new one for each page.
        ContentstackCollection<Asset> page = await client.AssetLibrary()
            .Skip(skip)
            .Limit(pageSize)
            .FetchAll();

        all.AddRange(page.Items);
        if (page.Items.Count() < pageSize)
        {
            break;
        }
        skip += pageSize;
    }
    Console.WriteLine($"Read {all.Count} assets");
}
catch (ContentstackException e)
{
    Console.WriteLine(e.Message);
}

IncludeBranch

IncludeBranch adds the _branch key, which names the branch each asset belongs to, to the FetchAll response.

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation.
  • A second call on the same instance throws AssetException, because the SDK stores each query parameter once. The original ArgumentException is the InnerException.
  • An invalid request surfaces as an AssetException when FetchAll sends it.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. IncludeBranch adds include_branch=true to the request and makes no request itself.
  • The API adds the _branch key with the unique ID of the branch (Get all assets). Asset has no property for it. Read it with the Asset Get method.
  • IncludeBranch does not choose the branch. The Branch option of the client sends the branch header that selects it.

Example

Basic usage: list assets from a branch

using System;
using Contentstack.Core;
using Contentstack.Core.Configuration;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient(new ContentstackOptions
{
    ApiKey = "<API_KEY>",
    DeliveryToken = "<DELIVERY_TOKEN>",
    Environment = "<ENVIRONMENT>",
    Branch = "<BRANCH>"
});

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary().IncludeBranch().FetchAll();
    foreach (Asset asset in assets)
    {
        Console.WriteLine($"{asset.FileName}: {asset.Get("_branch")}");
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

IncludeCount

IncludeCount adds the total number of matching assets to the FetchAll result.

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation.
  • A second call on the same instance throws ArgumentException, because the SDK stores each query parameter once.
  • An invalid request surfaces as an AssetException when FetchAll sends it.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. IncludeCount adds include_count=true to the request and makes no request itself.
  • The API returns the assets and their total count (Count). The SDK puts the total in the Count property of the result. Without IncludeCount, Count is 0.
  • The total covers every matching asset, not only the current page. Compare it with Skip plus the page size to decide whether more pages remain.
  • IncludeCount returns nothing, so you cannot chain after it. Call it as a separate statement.
  • To get only the number, without the assets, use the Count method.

Example

Basic usage: list assets with the total count

using System;
using System.Linq;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

AssetLibrary library = client.AssetLibrary().Limit(10);
library.IncludeCount();

try
{
    ContentstackCollection<Asset> assets = await library.FetchAll();
    Console.WriteLine($"Showing {assets.Items.Count()} of {assets.Count} assets");
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

IncludeFallback

IncludeFallback returns each asset from the fallback locale when the requested locale has no published version.

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation.
  • A second call on the same instance throws AssetException, because the SDK stores each query parameter once. The original ArgumentException is the InnerException.
  • An invalid request surfaces as an AssetException when FetchAll or Count sends it.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. IncludeFallback adds include_fallback=true to the request and makes no request itself.
  • The API includes the published asset details from the fallback locale when the specified locale does not contain published content (Get all assets).
  • Pair it with the SetLocale method, which names the locale that the fallback starts from.

Example

Basic usage: list assets with locale fallback

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary()
        .SetLocale("<LOCALE>")
        .IncludeFallback()
        .FetchAll();

    foreach (Asset asset in assets)
    {
        Console.WriteLine(asset.Title);
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

IncludeMetadata

IncludeMetadata adds the metadata of each asset, which extensions store on it, to the FetchAll response.

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation.
  • A second call on the same instance throws AssetException, because the SDK stores each query parameter once. The original ArgumentException is the InnerException.
  • An invalid request surfaces as an AssetException when FetchAll sends it.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. IncludeMetadata adds include_metadata=true to the request and makes no request itself.
  • The API returns the metadata of each asset under its _metadata key (Get all assets).
  • Asset has no property for _metadata. Read it with the Asset Get method, which returns it as a Dictionary<string, object>.

Example

Basic usage: read the metadata of each asset

using System;
using System.Collections.Generic;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary().IncludeMetadata().FetchAll();

    foreach (Asset asset in assets)
    {
        // Metadata is keyed by the UID of the extension that added it.
        int extensions = asset.Get("_metadata") is Dictionary<string, object> metadata ? metadata.Count : 0;
        Console.WriteLine($"{asset.FileName}: metadata from {extensions} extensions");
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

IncludeRelativeUrls

IncludeRelativeUrls adds the relative_urls=true flag to the FetchAll request.

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation.
  • A second call on the same instance throws ArgumentException, because the SDK stores each query parameter once.
  • An invalid request surfaces as an AssetException when FetchAll sends it.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. IncludeRelativeUrls adds relative_urls=true to the request and makes no request itself.
  • The SDK reads whatever the API returns in url into the Url property of each asset, without changing it.
  • The Get all assets request in the API reference does not list a relative_urls parameter. Check the Url values before you rely on the format.
  • IncludeRelativeUrls returns nothing, so you cannot chain after it. Call it as a separate statement.

Example

Basic usage: list assets with the relative URL flag

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

AssetLibrary library = client.AssetLibrary();
library.IncludeRelativeUrls();

try
{
    ContentstackCollection<Asset> assets = await library.FetchAll();
    foreach (Asset asset in assets)
    {
        Console.WriteLine(asset.Url);
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

Limit

Limit caps the number of assets that FetchAll returns.

NameTypeDescription
number (required)int

Maximum number of assets to return. Sets the page size.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation. Limit accepts zero or a negative number and sends it as written.
  • The API accepts positive integers only. With 0 or a non-numeric value, it returns the default number of assets rather than all of them (Limit).
  • A second call on the same instance throws AssetException, because the SDK stores each query parameter once. The original ArgumentException is the InnerException.
  • An invalid value surfaces as an AssetException when FetchAll sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. Limit adds the limit query parameter and makes no request.
  • Without Limit, the API returns the first 100 assets (Pagination).
  • Combine it with the Skip method to read one page at a time. The Limit property of the result stays 0, so track the value you sent.

Example

Basic usage: return the first 5 assets

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary().Limit(5).FetchAll();
    foreach (Asset asset in assets)
    {
        Console.WriteLine(asset.FileName);
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

Only

Only sends the list of top-level fields to keep in each asset of the response.

NameTypeDescription
fieldUid (required)string[]

Field UIDs to keep, for example title and url.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation of the field UIDs.
  • null or an empty array changes nothing.
  • A second call with at least one field throws AssetException, because the SDK stores each query parameter once. Pass every field in one call.
  • An invalid value surfaces as an AssetException when FetchAll sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. Only adds one only[BASE][] query parameter per field and makes no request.
  • The Only Operator section of the API reference documents only[BASE][] for entries only, and the Get all assets request does not list it. Check the response before you rely on it for assets.
  • Properties for fields the response leaves out keep their default values, for example null or an empty Url.

Example

Basic usage: keep only the title and URL

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary()
        .Only(new string[] { "title", "url" })
        .FetchAll();

    foreach (Asset asset in assets)
    {
        Console.WriteLine($"{asset.Title}: {asset.Url}");
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

Query

Query adds a JSON query to the request, for conditions that need an operator such as $regex or $lt.

NameTypeDescription
QueryObject (required)JsonObject

Query conditions in Content Delivery API syntax. Filters the assets.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation of the query. The SDK sends it as written.
  • null on the first call sends an empty query parameter. null after an earlier Where or Query call changes nothing.
  • Query wraps any failure while it stores the conditions in an AssetException.
  • An invalid query surfaces as an AssetException when FetchAll or Count sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. Query stores the object as the query parameter and makes no request.
  • Query and the Where method share one query parameter. A later call merges into it:
    • a key that is new adds a condition
    • two objects under the same key merge key by key
    • two arrays under the same key combine, and the SDK skips items already present
    • any other value under the same key replaces the earlier one
  • The first object you pass becomes the stored query, and later Where or Query calls edit it in place. Do not reuse that JsonObject for another request.
  • Not every operator works for assets. For example, Less Than, Search by Regex and AND Operator work for assets, and $exists works for entries only.
  • The SDK does not URL-encode the query, so &, # or + in a value changes the meaning of the request URL.

Example

Basic usage: match file names with a regular expression

using System;
using System.Text.Json.Nodes;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

JsonObject query = new JsonObject
{
    ["filename"] = new JsonObject { ["$regex"] = "^banner" }
};

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary().Query(query).FetchAll();
    foreach (Asset asset in assets)
    {
        Console.WriteLine(asset.FileName);
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

Edge case: combine two conditions with $and

using System;
using System.Linq;
using System.Text.Json.Nodes;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

JsonObject query = new JsonObject
{
    ["$and"] = new JsonArray
    {
        new JsonObject { ["content_type"] = "image/png" },
        new JsonObject { ["title"] = new JsonObject { ["$regex"] = "banner" } }
    }
};

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary().Query(query).FetchAll();
    Console.WriteLine($"Matched {assets.Items.Count()} assets on this page");
}
catch (ContentstackException e)
{
    Console.WriteLine(e.Message);
}

RemoveHeader

RemoveHeader removes a header that the SetHeaderForKey method added to this instance.

NameTypeDescription
key (required)string

Header name. Identifies the header to remove.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation.
  • A null key throws ArgumentNullException.
  • A key that this instance does not hold changes nothing.

Behavior

  • Client-side only. RemoveHeader deletes the header from this instance and makes no request.
  • It does not remove a client-level header, such as api_key or access_token. When SetHeaderForKey overrode a client-level header, removing it makes the request send the client value again.

Example

Basic usage: remove a header before the request

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    // FetchAll sends only the client-level headers.
    ContentstackCollection<Asset> assets = await client.AssetLibrary()
        .SetHeaderForKey("x-request-id", "asset-sync-42")
        .RemoveHeader("x-request-id")
        .FetchAll();

    foreach (Asset asset in assets)
    {
        Console.WriteLine(asset.FileName);
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

SetHeaderForKey

SetHeaderForKey adds an HTTP header to the requests of this asset library instance only.

NameTypeDescription
key (required)string

Header name. Identifies the header to send.

Default: Not applicable
value (required)string

Header value. Sent with the header name.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation of the name or value.
  • A null key or a null value changes nothing. SetHeaderForKey ignores the call.
  • A header name that HTTP does not allow, such as an empty string, passes SetHeaderForKey. FetchAll and Count then drop the header without an error.

Behavior

  • Client-side only. SetHeaderForKey stores the header and makes no request.
  • A second call with the same key replaces the value.
  • FetchAll and Count send these headers together with the client-level headers. When both name the same header, the value from SetHeaderForKey wins.
  • The header applies to this instance only. Other asset libraries, assets and entries from the same client do not get it.

Example

Basic usage: add a custom header to one request

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary()
        .SetHeaderForKey("x-request-id", "asset-sync-42")
        .FetchAll();

    foreach (Asset asset in assets)
    {
        Console.WriteLine(asset.FileName);
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

SetLocale

SetLocale sets the locale that FetchAll lists the assets in.

NameTypeDescription
Locale (required)string

Locale code, for example en-us. Selects the asset localizations.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation of the locale code.
  • A null or empty Locale replaces any locale set before and sends the locale parameter with an empty value.
  • An invalid value surfaces as an AssetException when FetchAll or Count sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. SetLocale stores the locale query parameter and makes no request.
  • A second call replaces the locale. Unlike most options on this class, it does not throw.
  • The localized title of each asset arrives in its Title property.
  • Chain the IncludeFallback method to get the fallback locale version of assets that have no published localization in Locale (Get all assets).

Example

Basic usage: list assets in a locale with fallback

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary()
        .SetLocale("<LOCALE>")
        .IncludeFallback()
        .FetchAll();

    foreach (Asset asset in assets)
    {
        Console.WriteLine(asset.Title);
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

Skip

Skip skips a number of assets at the start of the result, for pagination.

NameTypeDescription
number (required)int

Number of assets to skip. Sets the start of the page.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation. Skip accepts a negative number and sends it as written.
  • A second call on the same instance throws AssetException, because the SDK stores each query parameter once. The original ArgumentException is the InnerException.
  • An invalid value surfaces as an AssetException when FetchAll sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. Skip adds the skip query parameter and makes no request.
  • The skip parameter works for both entries and assets (Skip).
  • Without Skip, the result starts at the first asset.
  • Combine it with the Limit method to read one page at a time. The Skip property of the result stays 0, so track the value you sent.

Example

Basic usage: read the second page of 20 assets

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> page = await client.AssetLibrary()
        .Skip(20)
        .Limit(20)
        .FetchAll();

    foreach (Asset asset in page)
    {
        Console.WriteLine(asset.FileName);
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

SortWithKeyAndOrderBy

SortWithKeyAndOrderBy sorts the assets by the value of one field, in ascending or descending order.

NameTypeDescription
key (required)string

Asset field UID to sort by, for example created_at.

Default: Not applicable
order (required)OrderBy

Sort direction. Sets ascending or descending order.

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation of the field UID.
  • A second call with the same direction throws ArgumentException, because the SDK stores each query parameter once.
  • A null key sends the sort parameter with an empty value.
  • An invalid field surfaces as an AssetException when FetchAll sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. SortWithKeyAndOrderBy stores the sort parameter and makes no request.
  • The asc and desc parameters work for both entries and assets (Order by asc, Order by desc).
  • One call in each direction sends both asc and desc in the same request. Sort by one field per request.
  • SortWithKeyAndOrderBy returns nothing, so you cannot chain after it. Call it as a separate statement.

Example

Basic usage: newest assets first

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

AssetLibrary library = client.AssetLibrary();
library.SortWithKeyAndOrderBy("created_at", OrderBy.OrderByDescending);

try
{
    ContentstackCollection<Asset> assets = await library.FetchAll();
    foreach (Asset asset in assets)
    {
        Console.WriteLine($"{asset.GetCreateAt():u} {asset.FileName}");
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

All parameters: file names in ascending order

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

AssetLibrary library = client.AssetLibrary().Limit(20);
library.SortWithKeyAndOrderBy("filename", OrderBy.OrderByAscending);

try
{
    ContentstackCollection<Asset> assets = await library.FetchAll();
    foreach (Asset asset in assets)
    {
        Console.WriteLine(asset.FileName);
    }
}
catch (ContentstackException e)
{
    Console.WriteLine(e.Message);
}

Tags

Tags adds tags to the request, to list the assets that carry them.

NameTypeDescription
tags (required)string[]

Tag names, for example banner. Sent as the tag filter.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation of the tag names.
  • null or an empty array changes nothing, and any tags set before stay.
  • An invalid value surfaces as an AssetException when FetchAll or Count sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. Tags stores the array and makes no request. The request carries one tags query parameter per tag, for example tags=banner&tags=hero.
  • A second call replaces the tags from the first call. It does not add to them.
  • The Get all assets request in the API reference does not list a tags parameter. Check the response before you rely on it.

Example

Basic usage: list assets tagged banner or hero

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary()
        .Tags(new string[] { "banner", "hero" })
        .FetchAll();

    foreach (Asset asset in assets)
    {
        Console.WriteLine($"{asset.FileName}: {string.Join(", ", asset.Tags ?? new object[0])}");
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

Where

Where matches assets whose field equals a text value.

NameTypeDescription
key (required)string

Asset field UID, for example filename. Names the field to compare.

Default: Not applicable
value (required)string

Value the field must equal. Filters the assets by it.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation of the field or the value.
  • A null or empty key changes nothing. Where ignores the call.
  • A null value stores a JSON null condition for the field.
  • If storing the condition fails, Where throws a plain System.Exception, not a ContentstackException, with the original error as InnerException. A catch (ContentstackException) block does not catch it.
  • An invalid condition surfaces as an AssetException when FetchAll or Count sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. Where writes {"<key>": "<value>"} into the query parameter and makes no request.
  • The equals condition works for both entries and assets (Equals Operator).
  • Calls on different fields combine, and an asset must match all of them. A second call on the same field replaces the first value.
  • Where and the Query method share one query parameter, so their conditions combine.
  • Where compares text only. For numbers, booleans or operators such as $regex, use the Query method.
  • The SDK does not URL-encode the condition, so &, # or + in a value changes the meaning of the request URL.

Example

Basic usage: find assets by file name

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    ContentstackCollection<Asset> assets = await client.AssetLibrary()
        .Where("filename", "banner.png")
        .FetchAll();

    foreach (Asset asset in assets)
    {
        Console.WriteLine($"{asset.Uid}: {asset.Url}");
    }
}
catch (ContentstackException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.Message}");
}

Edge case: two conditions that must both match

using System;
using Contentstack.Core;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;

ContentstackClient client = new ContentstackClient("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

try
{
    // The query parameter holds both conditions: content_type and title.
    ContentstackCollection<Asset> assets = await client.AssetLibrary()
        .Where("content_type", "image/png")
        .Where("title", "Home banner")
        .FetchAll();

    foreach (Asset asset in assets)
    {
        Console.WriteLine(asset.FileName);
    }
}
catch (ContentstackException e)
{
    Console.WriteLine(e.Message);
}