Query

View as Markdown

Query

Query lists the items of one stack resource, such as the entries of a content type or the assets of a stack, in the Contentstack.Management.Core.Queryable namespace.

When to Use This Class: Use this class to read a page of items. Page through a collection with Limit and Skip. Get the total number of items with IncludeCount.

Conceptual Role: Acts as the list request builder of the SDK. The Query() method of a resource object returns it, and Find or FindAsync sends the request.

Returns: Query. A new query for the items of one resource.

Instance State

A Query has no public constructor. Call Query() on a resource object that has no UID, for example stack.ContentType().Query() or stack.ContentType("<CONTENT_TYPE_UID>").Entry().Query(). The object you call it on decides which list the query reads:

Created fromRequest path
stack.ContentType()/content_types
stack.ContentType("<CONTENT_TYPE_UID>").Entry()/content_types/<CONTENT_TYPE_UID>/entries
stack.Asset()/assets
stack.GlobalField()/global_fields. With stack.GlobalField(null, "<API_VERSION>"), Find also sends the api_version header.
stack.Environment()/environments
stack.Locale()/locales
stack.Label()/labels
stack.Role()/roles
stack.Extension()/extensions
stack.Webhook()/webhooks
stack.Release()/releases
stack.Taxonomy()/taxonomies
stack.Taxonomy("<TAXONOMY_UID>").Terms()/taxonomies/<TAXONOMY_UID>/terms
stack.Branch()/stacks/branches
stack.DeliveryToken()/stacks/delivery_tokens
stack.ManagementTokens()/delivery_tokens

Calling Query() on a resource object that has a UID throws InvalidOperationException, because a query lists a collection. The Method Index below lists every method.

Class-Level Notes

Set each parameter once.

  • Limit, Skip, and IncludeCount each add a key to the query's own ParameterCollection, and a key holds one value. Calling one of them twice throws ArgumentException at once.
  • Find and FindAsync copy the entries of the collection you pass into that same collection. A key that a chained method already set throws ArgumentException.
  • The query keeps every parameter after the request. Calling Find again with a collection that repeats a key throws ArgumentException. Create a new query for each request.

Authentication.

  • Find and FindAsync throw InvalidOperationException when the client has no authtoken and the stack has no management token, and when the stack has no API key.

Errors.

  • Limit, Skip, and IncludeCount send no request. An invalid value reaches you as a ContentstackErrorException from Find or FindAsync.

Capability Matrix

CapabilitySupportedNotes / Alternative
Read every page in one callNoCall Find once per page with a new query and a higher Skip value.
Filter by field value with a chained methodNoPass a JSON filter through the AddQuery method of ParameterCollection to Find.
Reuse a query for a second pageNoSkip throws on a second call. Create a new query.

Method Index

Set options. Available on every query. Chain these before Find or FindAsync.

Method NameReturnsDescription
LimitThe same query, for chaining.Sets the number of items per page.
SkipThe same query, for chaining.Sets the number of items to skip.
IncludeCountThe same query, for chaining.Adds the total item count to the response.

Send the request. Available on every query.

Method NameReturnsDescription
FindThe API response with the matching items.Sends the list request.
FindAsyncThe API response with the matching items.Sends the list request asynchronously.

Class-Level Snippet

This snippet reads the second page of ten entries of a content type, with the total count.

using System;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>")
        .ContentType("<CONTENT_TYPE_UID>")
        .Entry()
        .Query()
        .Limit(10)
        .Skip(10)
        .IncludeCount()
        .FindAsync();

    JsonObject body = response.OpenJsonObjectResponse();
    Console.WriteLine($"Showing {body["entries"]?.AsArray().Count} of {body["count"]} entries");
}
catch (ContentstackErrorException e)
{
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

Methods

Each method of the Query class has its own section below, with its parameters, validation rules, behavior, and examples.

Find

Find sends the list request with every option of the query, and returns the matching items.

NameTypeDescription
collectionParameterCollection?

More query parameters, such as locale or query.

Default: null

Returns: ContentstackResponse. The API response with the matching items.

Validation

  • Throws InvalidOperationException if the client has no authtoken and the stack has no management token, because the Content Management API (CMA) needs one of the two.
  • Throws InvalidOperationException if the stack has no API key, because every list request belongs to one stack.
  • Throws ArgumentException if collection has a key that the query already holds, from Limit, Skip, IncludeCount, or an earlier Find call.
  • collection set to null sends only the options of the query.
  • Throws ContentstackErrorException when the API rejects the request.

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

Behavior

  • Find sends one GET request to the path of the resource that created the query, for example /content_types or /content_types/<CONTENT_TYPE_UID>/entries. See the Query class page for each path.
  • The request carries every option of the query and every entry of collection as query parameters. Which parameters the API accepts depends on the request. Each resource's Get all request in the CMA reference lists them, for example Get all content types.
  • Find copies the entries of collection into the query, and the query keeps them. Create a new query for each request.
  • Returns the raw API response. The items sit under a key named after the resource, such as entries, assets, or content_types, and count holds the total when you call IncludeCount.
  • Does not page through the results for you. One call returns one page.

Example

Basic usage: list the content types of a stack

using System;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType().Query().Find();
    JsonArray? contentTypes = response.OpenJsonObjectResponse()["content_types"]?.AsArray();
    Console.WriteLine($"{contentTypes?.Count} content types");
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

All parameters: filter entries with a management token

using System;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient();

ParameterCollection collection = new ParameterCollection();
collection.Add("locale", "<LOCALE_CODE>");
collection.AddQuery(new JsonObject { ["title"] = "Blog Post" });

try
{
    ContentstackResponse response = client.Stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .ContentType("<CONTENT_TYPE_UID>")
        .Entry()
        .Query()
        .Find(collection);
    Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

Edge case: a second Find with the same collection

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
Query query = client.Stack("<API_KEY>").ContentType().Query();

ParameterCollection collection = new ParameterCollection();
collection.Add("include_global_field_schema", true);

try
{
    query.Find(collection);

    // The query kept "include_global_field_schema", so adding it again fails.
    query.Find(collection);
}
catch (ArgumentException e)
{
    // Fires before the second request
    Console.WriteLine(e.Message);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

FindAsync

FindAsync sends the list request with every option of the query without blocking the calling thread, and returns the matching items.

NameTypeDescription
collectionParameterCollection?

More query parameters, such as locale or query.

Default: null

Returns: Task<ContentstackResponse>. The API response with the matching items.

Validation

  • Throws InvalidOperationException if the client has no authtoken and the stack has no management token, or if the stack has no API key.
  • Throws ArgumentException if collection has a key that the query already holds.
  • The SDK throws the exceptions above when you call FindAsync, before it returns a task.
  • Throws ContentstackErrorException when you await the task and the API rejects the request.

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

Behavior

  • Otherwise behaves like Find.

Example

Basic usage: list the content types of a stack

using System;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>").ContentType().Query().FindAsync();
    JsonArray? contentTypes = response.OpenJsonObjectResponse()["content_types"]?.AsArray();
    Console.WriteLine($"{contentTypes?.Count} content types");
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

All parameters: filter entries with a management token

using System;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient();

ParameterCollection collection = new ParameterCollection();
collection.Add("locale", "<LOCALE_CODE>");
collection.AddQuery(new JsonObject { ["title"] = "Blog Post" });

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .ContentType("<CONTENT_TYPE_UID>")
        .Entry()
        .Query()
        .FindAsync(collection);
    Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

IncludeCount

IncludeCount asks the API to add the total number of matching items to the response.

This method takes no parameters.

Returns: Query. The same query, for chaining.

Validation

  • Throws ArgumentException if the query already has an include_count value, because each parameter holds one value.
  • Errors that do occur come from the Find or FindAsync call that follows, not from IncludeCount.

Behavior

  • Client-side only. IncludeCount adds include_count=true to the query and sends no request.
  • The API returns the total in the count key of the response, next to the list of items, as the Get all content types request describes.
  • The count covers every matching item, not only the page that Limit and Skip select.

Example

Basic usage: count the entries of a content type

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType("<CONTENT_TYPE_UID>").Entry().Query().Limit(1).IncludeCount().Find();
    Console.WriteLine($"The content type has {response.OpenJsonObjectResponse()["count"]} entries");
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

Limit

Limit sets the largest number of items that the query returns in one response.

NameTypeDescription
value (required)double

Number of items per page.

Default: Not applicable

Returns: Query. The same query, for chaining.

Validation

  • Throws ArgumentException if the query already has a limit value, from an earlier Limit call, because each parameter holds one value.

Limit does not check the number. A value the API does not accept, such as one above the maximum that the API reference lists for the request, fails on the Find or FindAsync call that follows, with ContentstackErrorException`.

Behavior

  • Client-side only. Limit adds limit=<value> to the query and sends no request.
  • Without Limit, the SDK sends no limit parameter and the API applies its own page size.
  • Pair Limit with Skip to read one page at a time, and with IncludeCount to get the total number of items.

Example

Basic usage: read ten content types

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType().Query().Limit(10).Find();
    Console.WriteLine(response.OpenJsonObjectResponse()["content_types"]?.AsArray().Count);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

Edge case: calling Limit twice

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
Query query = client.Stack("<API_KEY>").ContentType().Query().Limit(10);

try
{
    query.Limit(20);
}
catch (ArgumentException e)
{
    // Fires at once, because the query already has a limit
    Console.WriteLine(e.Message);
}

Skip

Skip sets the number of items that the query skips before the first item it returns.

NameTypeDescription
value (required)double

Number of items to skip.

Default: Not applicable

Returns: Query. The same query, for chaining.

Validation

  • Throws ArgumentException if the query already has a skip value, because each parameter holds one value. Create a new query for the next page.
  • Skip does not check the number. A value the API does not accept fails on the Find or FindAsync call that follows, with ContentstackErrorException.

Behavior

  • Client-side only. Skip adds skip=<value> to the query and sends no request.
  • Without Skip, the SDK sends no skip parameter and the API returns items from the start.
  • To read page n with a page size of size, call Limit(size) and Skip(size * (n - 1)) on a new query.

Example

Basic usage: read every page of assets

using System;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
Stack stack = client.Stack("<API_KEY>");

try
{
    int pageSize = 100;
    int skip = 0;
    int received;
    do
    {
        // A query takes one Skip value, so create a new query for each page.
        ContentstackResponse response = stack.Asset().Query().Limit(pageSize).Skip(skip).Find();
        JsonArray assets = response.OpenJsonObjectResponse()["assets"]?.AsArray() ?? new JsonArray();
        received = assets.Count;
        skip += received;
        Console.WriteLine($"Read {received} assets");
    }
    while (received == pageSize);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}