Links

Extension API for querying

Learn how to extend the Content Delivery API with custom selecting, filtering, and sorting options for the multi-item-based endpoint.
The Delivery API allows you to retrieve multiple items by utilizing the /umbraco/delivery/api/v1/content endpoint. With the built-in query parameters, you have the flexibility to get any number of content nodes based on your needs. For a comprehensive list of supported query options, please refer to the Endpoints section.
For the query endpoint, we have created a new Examine index (DeliveryApiContentIndex) that facilitates fast retrieval of the desired content. This index ensures quick indexing and searching of data, with the possibility for future extensions.
In this article, we'll explore creating custom selecting, filtering, and sorting options to enhance the querying capabilities of the Delivery API.

Query options

Let's take a look at an example of using the query endpoint with query parameters for fetch, filter, and sort. A request might look like this:
GET /umbraco/delivery/api/v1/content?fetch=xxx&filter=yyy&filter=zzz&sort=aaa&sort=bbb
The placeholders in the example (xxx, yyy, etc.) represent the values that each query option evaluates in order to determine the suitable query handler.
You can include only one fetch parameter, while multiple filter and sort parameters are allowed. Additionally, the order of the sort parameters influences the sorting behaviour. Refer to the Query parameters section for the currently supported options.
The implementation of each querying option consists of a class for indexing the data into the DeliveryApiContentIndex and another one for handling the query. By implementing the IContentIndexHandler interface, you can control how your relevant data is indexed and made available for querying through our index. And you can customize the querying behaviour to suit your needs by implementing the ISelectorHandler, IFilterHandler, and ISortHandler interfaces.
In the following sections, we will explore the implementation details of creating custom querying functionality for the Delivery API.

Custom selector

Selectors handle the fetch part of a query.
To showcase how to build a custom selector, consider a site structure with a few blog posts. A post is linked to an author, which is another content item.
Authors can be marked as 'Featured' using a toggle, granting them additional visibility and recognition. We will use this marker as part of the indexing implementation for our selector option.
The following example demonstrates the implementation of an AuthorSelector, which allows you to customize the querying behaviour specifically for finding all featured authors. This class contains both indexing and querying responsibilities. However, keep in mind that it is generally recommended to separate these responsibilities into dedicated classes.
AuthorSelector.cs
1
using Umbraco.Cms.Core.DeliveryApi;
2
using Umbraco.Cms.Core.Models;
3
4
namespace Umbraco.Docs.Samples;
5
6
public class AuthorSelector : ISelectorHandler, IContentIndexHandler
7
{
8
private const string FeaturedAuthorsSpecifier = "featuredAuthors";
9
private const string FieldName = "featured";
10
11
// Querying
12
public bool CanHandle(string query)
13
=> query.StartsWith(FeaturedAuthorsSpecifier, StringComparison.OrdinalIgnoreCase);
14
15
public SelectorOption BuildSelectorOption(string selector) =>
16
new SelectorOption
17
{
18
FieldName = FieldName,
19
Values = new[] { "y" }
20
};
21
22
// Indexing
23
public IEnumerable<IndexFieldValue> GetFieldValues(IContent content, string? culture)
24
{
25
if (content.ContentType.Alias.InvariantEquals("author") == false)
26
{
27
return Enumerable.Empty<IndexFieldValue>();
28
}
29
30
var isFeatured = content.GetValue<bool>("featured");
31
32
return new[]
33
{
34
new IndexFieldValue
35
{
36
FieldName = FieldName,
37
Values = new object[] { isFeatured ? "y" : "n" }
38
}
39
};
40
}
41
42
public IEnumerable<IndexField> GetFields()
43
=> new[]
44
{
45
new IndexField
46
{
47
FieldName = FieldName,
48
FieldType = FieldType.StringRaw,
49
VariesByCulture = false`
50
}
51
};
52
}
The AuthorSelector class implements the ISelectorHandler and IContentIndexHandler interfaces.
ISelectorHandler allows for handling the fetch value in API queries through the CanHandle() and BuildSelectorOption() methods.
  • CanHandle() determines if the given fetch query corresponds to the "featuredAuthors" value.
  • BuildSelectorOption() constructs the selector option to search for authors with a positive value (for example, "y") in a "featured" index field.
The GetFields() and GetFieldValues() methods each play a role in defining how the data should be indexed and made searchable.
  • GetFields() defines the behaviour of fields that are added to the index. In this example, the "featured" field is added as a "raw" string for efficient and accurate searching.
  • GetFieldValues() is responsible for retrieving the values of the defined index fields. In this case, the "featured" field of content items of type "author". It creates an IndexFieldValue with the appropriate field value ("y" for featured, "n" otherwise), which will be added to the index.
Since our custom query option modifies the index structure, we will need to rebuild the DeliveryApiContentIndex. You can find it by navigating to the "Examine Management" dashboard in the "Settings" section. Once rebuilt, we can make a request to the Delivery API query endpoint as follows:
Request
GET /umbraco/delivery/api/v1/content?fetch=featuredAuthors
Response
{
"total": 3,
"items": [
...
]
}

Custom filter

Filters handle the filter part of a query.
Staying within the topic of blog posts and their authors, we will create a custom filter to find posts by specific author(s).
This filter allows specifying the desired author(s) by their key (Guid) in an author: filter option. Multiple authors can be included by listing their keys as comma-separated-values, like:
Request
GET /umbraco/delivery/api/v1/content?filter=author:7c630f15-8d93-4980-a0fc-027314dc827a,75380b4f-6d6e-47a1-9222-975cdfb2ac5f
The response will include the blog posts associated with the provided authors, enabling us to retrieve only the relevant results from the API.
Response
{
"total": 4,
"items": [
...
]
}
Our filter implementation follows a similar structure to the custom selector we discussed earlier. We continue to utilize the IContentIndexHandler interface, but this time we introduce the IFilterHandler. This combination gives us flexibility and control over the filtering behaviour.
The procedure remains the same - we store and query the author key in a new "authorId" field within the index. Consequently, we will need to rebuild the index to reflect the changes.
To illustrate the implementation, consider the following code example:
AuthorFilter.cs
1
using Umbraco.Cms.Core;
2
using Umbraco.Cms.Core.DeliveryApi;
3
using Umbraco.Cms.Core.Models;
4
5
namespace Umbraco.Docs.Samples;
6
7
public class AuthorFilter : IFilterHandler, IContentIndexHandler
8
{
9
private const string AuthorSpecifier = "author:";
10
private const string FieldName = "authorId";
11
12
// Querying
13
public bool CanHandle(string query)
14
=> query.StartsWith(AuthorSpecifier, StringComparison.OrdinalIgnoreCase);
15
16
public FilterOption BuildFilterOption(string filter)
17
{
18
var fieldValue = filter.Substring(AuthorSpecifier.Length);
19
20
// There might be several values for the filter
21
var values = fieldValue.Split(',');
22
23
return new FilterOption
24
{
25
FieldName = FieldName,
26
Values = values,
27
Operator = FilterOperation.Is
28
};
29
}
30
31
// Indexing
32
public IEnumerable<IndexFieldValue> GetFieldValues(IContent content, string? culture)
33
{
34
GuidUdi? authorUdi = content.GetValue<GuidUdi>("author");
35
36
if (authorUdi is null)
37
{
38
return Array.Empty<IndexFieldValue>();
39
}
40
41
return new[]
42
{
43
new IndexFieldValue
44
{
45
FieldName = FieldName,
46
Values = new object[] { authorUdi.Guid }
47
}
48
};
49
}
50
51
public IEnumerable<IndexField> GetFields() => new[]
52
{
53
new IndexField
54
{
55
FieldName = FieldName,
56
FieldType = FieldType.StringRaw,
57
VariesByCulture = false
58
}
59
};
60
}
The principal difference from the selector is that the filter implements BuildFilterOption() instead of BuildSelectorOption(). Here, the filter performs an exact match for any specified Guid in the query. Efficiently, this makes the filter perform an OR operation against the index.
Since we need to perform an exact match, the index field (authorId) is once again defined as a "raw" string. Other options include "analyzed" and "sortable" strings. These support "contains" searches and alpha-numeric sorting, respectively.

Filter operations

To define your custom filter, you currently have four options: Is, IsNot, Contains and DoesNotContain.
It is possible to pass multiple values to each operator, and these values will be treated inclusively as an or operator. For example, if tag1 and tag2 were passed into a filter using the Is operator, any document containing either tag1 or tag2 would return. The request for this might look like this:
GET /umbraco/delivery/api/v1/content?filter=customTagFilter:tag1,tag2
If you require this functionality to be restrictive i.e. tag1 and tag2, then the current approach would be to chain the custom filter. The request would change to look more like this:
GET /umbraco/delivery/api/v1/content?filter=customTagFilter:tag1&filter=customTagFilter:tag2

Custom sort

Finally, we can also add custom handling for the sort part of the query.
We'll add a custom sort handler that allows us to sort blog posts based on a custom "publishDate" Date Picker property. The implementation will allow for sorting the posts in ascending or descending order.
This sorting should only be used with query results that have a published date to ensure accurate results.
To demonstrate this, consider the following implementation example:
PublishDateSort.cs
1
using Umbraco.Cms.Core;
2
using Umbraco.Cms.Core.DeliveryApi;
3
using Umbraco.Cms.Core.Models;
4
5
namespace Umbraco.Docs.Samples;
6
7
public class PublishDateSort : ISortHandler, IContentIndexHandler
8
{
9
private const string SortOptionSpecifier = "publishDate:";
10
private const string FieldName = "publishDate";
11
12
// Querying
13
public bool CanHandle(string query)
14
=> query.StartsWith(SortOptionSpecifier, StringComparison.OrdinalIgnoreCase);
15
16
public SortOption BuildSortOption(string sort)
17
{
18
var sortDirection = sort.Substring(SortOptionSpecifier.Length);
19
20
return new SortOption
21
{
22
FieldName = FieldName,
23
Direction = sortDirection.StartsWith("asc", StringComparison.OrdinalIgnoreCase)
24
? Direction.Ascending
25
: Direction.Descending
26
};
27
}
28
29
// Indexing
30
public IEnumerable<IndexFieldValue> GetFieldValues(IContent content, string? culture)
31
{
32
var publishDate = content.GetValue<DateTime?>("publishDate");
33
34
if (publishDate is null)
35
{
36
return Enumerable.Empty<IndexFieldValue>();
37
}
38
39
return new[]
40
{
41
new IndexFieldValue
42
{
43
FieldName = FieldName,
44
Values = new object[] { publishDate }
45
}
46
};
47
}
48
49
public IEnumerable<IndexField> GetFields()
50
=> new[]
51
{
52
new IndexField
53
{
54
FieldName = FieldName,
55
FieldType = FieldType.Date,
56
VariesByCulture = false
57
}
58
};
59
}
The implementation follows the same structure as the other examples, defined by the IContentIndexHandler and ISortHandler interfaces.
One point to highlight is that we store the "publishDate" value as a "date" field in the index, which allows for correct date sorting.
Once more, when adding fields to the index, we need to rebuild it to reflect the changes.
In the following example request, we also apply the author filter to retrieve only "blogpost" content nodes, which we know have the "publishDate" field.
Request
GET /umbraco/delivery/api/v1/content?filter=author:7c630f15-8d93-4980-a0fc-027314dc827a&sort=publishDate:asc
Response
{
"total": 2,
"items": [
...
]
}