The third video in my series on using GraphQL with Sitecore is now online. In this video, I look at variables, built in fields, and the use of Fragments to improve query re-use.
Hope that people find it useful.
The third video in my series on using GraphQL with Sitecore is now online. In this video, I look at variables, built in fields, and the use of Fragments to improve query re-use.
Hope that people find it useful.
I’m pleased to release the second video in my series on using GraphQL with Sitecore. In this second video, I look at Item Queries and strong typing of items and fields.
Hope that people find it useful.
Recently I needed to expose a GraphQL query that accepted a list of Sitecore item IDs and returned the item data for those IDs. I wanted to use the Content Search API for efficiency reasons and because the items might not all be colocated in a folder.
Out of the box, the Sitecore GraphQL Search query does not allow you to do this, but a look into the GraphQL assembly revealed that the ListGraphType might do the job.
The resulting extensions to Sitecore.Services.GraphQL.Content.Queries.SearchQuery looked like this:
public class MySearchQuery : Sitecore.Services.GraphQL.Content.Queries.SearchQuery
{
public MySearchQuery()
{
Arguments.Add(new QueryArgument<ListGraphType<StringGraphType>>()
{
Name = "itemIds",
Description = "Filter by Sitecore item IDs"
});
}
//override the ContentSearchResults method here...
}
The GraphQL query was then able to pass in an array of item IDs which looked something like this:
query ExtendedSearch {
searchItemsById(itemIds:["6a6f0d75-2a1d-4f70-b639-622d308d9e11","{EF1848D8-6C43-4E52-A04F-287A12E19D12}"]) {
results {
items {
item {
id
field(name:"myItemField"){
value
}
}
}
}
}
}
One thing to note is that, although you are passing in a Guid like “6a6f0d75-2a1d-4f70-b639-622d308d9e11”, the Sitecore GraphQL content search results will come back with a value like “6A6F0D752A1D4F70B639622D308D9E11”.
Today I released Part 1 of a video series on using GraphQL with Sitecore. In this first part, I cover getting up and running with GraphQL through:
In later videos we’ll dig deeper into configuration, item and search queries, fragments, integrated GraphQL, and extending and customising GraphQL in the context of Sitecore.
Hope that people find it useful.
In a typical Sitecore ASP.NET server-side rendered solution, redirects are handled by returning a 301 or 302 HTTP status code to the client browser to signal that the client should redirect to a particular URL.
In a Sitecore Headless solution, things might not be quite so simple. For one thing, the Layout Service does not readily provide a way to return a 301/302 redirect status code in the HTTP response from the API. In addition, even if you convinced the Layout Service to return a 301, if you were using the JSS SDK in a JavaScript application running on the client browser, in-app routing might need to handle redirects returned from the API call and identify which route to use and redirect accordingly (in the app itself, not with a full page reload.) Turns out that isn’t as simple as it might appear either.
There are at least two distinct types of redirect that we might want to handle in our headless Sitecore application:
This is the typical “vanity URL” scenario. For example we might have published a nice, friendly URL for potential customers such as https://mysite.com/newmodels which will redirect to https://mysite.com/catalogues/cars/2021-models. It’s easier to remember and easier for the user to digest. It might also have SEO benefits to use the first URL rather than the second one.
Sure, we can handle this using a CDN or via web server modules like URL Rewrite, but that isn’t very helpful to our digital producers who want to manage redirects themselves in the CMS and publish the new vanity URL alongside a marketing campaign.
This is where modules like the 301 Redirect Module or SXA Redirects come in. Both of these empower your users to manage redirects in the Sitecore tree, but they were not designed to work with Sitecore Headless Services. That said, you could leverage either option, or roll your own, and patch it in. I’ve outlined how you might do that later in this post.
In this scenario we might have a node in the Sitecore content tree that has no content but has descendants that do. Perhaps a Category page that holds all items in a particular category, but that has no actual content itself.
Now you might argue that we shouldn’t have nodes in our IA that have no useful content – and I’d be on your side in that argument! – however some clients would appear to disagree, and so here we are.
Let’s look at each scenario and see how they might be achieved in the Layout Service, as well as some pointers on what to avoid.
As mentioned earlier, patching into the usual MVC pipelines is no use with the Layout Service because it just blows right past those suckers and does its own thing in a Controller API. The controller that runs the show is in:
Sitecore.LayoutService.Mvc.Controllers.LayoutServiceController
It inherits from System.Web.Mvc.Controller and exposes the “placeholder” and “render” actions in the Layout Service API via MVC controller action methods. The first thing that I looked at was overriding the virtual methods, but after going down a rabbit hole it became apparent that, although overriding the methods would be simple enough, setting up the constructor was more problematic and needed quite a bit of hackery which would prove hard to maintain and upgrade in the future. I then looked into patching the pipeline.
Finding the right place to patch was the key to doing this. Long story short, the place to patch is in the <mvc.requestBegin> pipeline, just after Sitecore.LayoutService.Mvc.Pipelines.RequestBegin.ContextItemResolver like so:
Then in your RedirectHandler you can add whatever approach floats your boat to identify and process redirects, returning the appropriate 301/302 status code and URL.
As an Australian politician and Prime Minister once said, “Life wasn’t meant to be easy”. In this case there’s a couple of gotchas.
In a JSS application, a client browser requests the initial app from the server and on subsequent requests calls back to the Layout Service API for the route data. This means that there are actually two scenarios to consider: the initial request to the server and the subsequent calls to the API. How you handle this is dependent on your topology and your choice of SDK.
For example, in an SSR setup with a Node.js proxy, your proxy app will need to be able to handle redirects both from the initial request, and on subsequent proxied API requests. In a CSR setup this will be handled by your JSS app. In either case, your JSS app will need to be able to handle HTTP responses with redirect status codes.
Working on this with my front end colleague in an SSR topology using the React JSS SDK, we encountered issues with Axios following 301s without any way of trapping it. It was fine for the initial request, but we were unable to handle Layout Service API calls that returned 301 in the React app. Your mileage may vary, and if you are using .NET rendering host then this should not be an issue.
Another gotcha is CORS. The LayoutServiceController has a bunch of ActionFilterAttributes, one of which is EnableApiKeyCors. This adds some CORS magic to the response and you might need to add this code to the response your redirect handler, depending on your scenario. For reference, you might add something like this to your response code:
Phew. This post is longer than I had intended. Nearly there.
This one is a bit easier. Option one is to have a fight with the customer and convince them to just put some content on the “node with no content”.
If that fails, you could create a custom item type in Sitecore to handle the redirection. I created a NavigationRedirectNode template that had a Treelist field from which you could pick an item from the site tree. Then in the code I just checked for that template ID and returned the redirect. In my case, because of the Axios issues mentioned above, we opted to return the route to which we wanted to redirect via the ItemContext (similar to this post) and handled that in the app. I’m not saying this is the only or best way – it’s just where we ended up.
However! There was a gotcha. The item has to have layout. It doesn’t have to have anything on it, but if you don’t have a Sitecore layout applied to the item then Sitecore jumps in, hijacks the request, and you end up at “The layout for the requested document was not found” with a red screen of doom.
As you can see, there’s a bit more to redirects when using Sitecore Headless Services compared to a “traditional” Sitecore MVC solution. The above represents my own experiences with applying redirects in a JSS React SSR solution, and is by no means comprehensive, but I hope that it provides some pointers on your own headless travels 🙂
Consuming data from a “headless” CMS is a pretty popular approach these days, as the trend towards the delivery of API-driven front end rendering solutions continues to grow. Sitecore has been increasing its footprint in this space for several years now, and has developed some offerings that leverage the legacy of Sitecore’s content management, personalisation, and analytics features whilst also enabling the delivery of content to headless rendering apps. In this post I outline the options available for delivering and shaping Sitecore content via APIs using the features that Sitecore Headless Services adds on to the base platform, and also mention a couple of methods that are already available without the need for a JSS license.
Sitecore Headless Services (formerly JSS Server Components) provides additional server-side functionality that exposes Sitecore content and rendering information via APIs. Released as part of Sitecore JavaScript Services 9 Tech Preview, nearly four years ago now, it’s moved on considerably since then and provides a number of different methods by which we can extract and query data for consumption by apps using the JSS JavaScript Rendering SDK’s or the ASP.NET Core Rendering SDK, or any solution that needs to consume content from your Sitecore platform. It’s available with an Enterprise license, or as an add-on for other editions, and you can try it out via the Front End Developer Trial program at no cost.
[N.B. The following methods require Headless Services to be installed on your Sitecore instance]
The Layout Service exposes a REST endpoint (or endpoints, you can have multiple) through which content items can be retrieved using an API key and the results are returned in a specific JSON structure. I won’t go into the specifics of it here, but you can read more details in one of my earlier blog posts.
The API is quite flexible and extensible, and you can use a few different approaches to tailor the data to your needs:
Requesting an item (a route in JSS parlance) from the API returns a fully assembled description of the route content, as well as the renderings assigned to the placeholders on that route. One of the key differentiators of the layout service is that it leverages the Sitecore rendering engine to include rendering information along with content, and this means that you can use Sitecore personalisation and content management techniques to customise the data returned to your headless solution. Thus your digital producers and content authors can take advantage of the tools with which they are already familiar, such as Experience Editor, to add renderings to placeholders, apply rules based personalisation, and create and deploy tests, all of which are fully supported in headless mode when using the API.
The Headless SDKs have been specifically developed to consume the data structures returned by the Layout Serivce, so this is the “go to” option for consuming Sitecore content and rendering information in headless solutions based off the SDKs in both JavaScript or .NET versions.
One lesser known option available in the layout service API is that you can use it to retrieve only the contents of a specific placeholder. This might not sound like much but it is really quite a powerful and useful feature. In a headless delivery model, once the layout data has been retrieved from the API for a given route, the user can continue to interact with the site UI without the need for additional calls to the Sitecore delivery server (unless they request a new route of course.) Using the placeholder API call, you can dynamically retrieve and update the contents of specific placeholders in your headless application based on interactions that your user has had with your site.
For example you could append a querystring to the placeholder API call and personalise the rendering data in the placeholder on the server side, then dynamically update the UI with the freshly customised rendering information. Or you could send data to a custom endpoint, update a goal or a facet, and then pull the personalised rendering data based on the new information about your user. Or perhaps you could lazy load content into your UI to improve performance.
In addition, the JSON returned from the placeholder API call is very lean compared to the route API data, so requests are lightweight and fast.
Headless Services introduced the concept of Rendering Contents Resolvers. These are a set of 6 “resolvers” that can be used to tailor the data returned for a specific rendering. The tailored rendering contents are then passed back to the Layout Service. The out-of-the-box resolvers are quite flexible and provide a quick and simple way to tailor rendering contents without the need for custom code. They can be easily extended and you can read more details about how to do that here.
GraphQL was added to Headless Services and announced at Sitecore Symposium back in 2018, along with the “official” release of JSS. The Sitecore docs describe it as “a generic GraphQL service platform on top of Sitecore. It hosts your data and presents it through GraphQL queries. The API supports real-time data using GraphQL subscriptions.”
What this means in practical terms is that you can query Sitecore items and perform Content Search queries via GraphQL. Integrated GraphQL is the use of GraphQL queries to shape your rendering contents. This is done by simply pasting the query code into a multi-line text field in your rendering (what could go wrong?). This will override any other rendering behaviours and return the query results instead of a datasource, or the output of a rendering contents resolver. GraphQL always wins.
One key difference that should be borne in mind, however, is that the JSON contract returned by an integrated GraphQL query will be quite different to the rendering contracts returned when using out-of-the-box options like rendering contents resolvers. This can result in a bit of a mixed bag of data structures being returned to your headless data consumers, some using the “standard” approach and some using a variety of GraphQL shaped rendering contents.
GraphQL can also be extended. For an example of extending Content Search in GraphQL, see Aaron Bickle’s excellent blog post on the subject.
This is Sitecore: everything is extensible! So it is not difficult to extend the code that powers the API and customise the data contract. You can read about extending the context here.
That pretty much sums up the options for using the Layout Service but it’s not the end of the story. More techniques are available for powering headless solutions.
This approach uses the same schema as Integrated GraphQL, but exposes API endpoints to which you can send your queries. Using this feature your apps can query Sitecore content and send variables with those queries, perhaps based on client interactions. One example might be to provide a headless search feature, passing user-supplied search terms back to the API endpoint which would in turn use the Content Search API to query Sitecore. Or perhaps use it to retrieve configuration settings or other values on-the-fly without the need to use the Layout Service. Customised GraphQL approaches such as that described in Aaron Bickle’s post mentioned earlier can also be leveraged to customise the default functionality available via Connected GraphQL.
Don’t have JSS and Headless Services? Not to worry! There are other options available to feed data to your headless solutions.
Using SXA? Great! SXA is awesome! This also means that you can use SXA data modelling and JSON renderings and variants to return data to your headless app without a JSS license. This approach is pretty flexible because you have the power of SXA rendering variants and Scriban at your disposal.
The Sitecore Services Client has been around for quite a while and in a headless scenario it would most likely be used to provide read-only access to items via the ItemService. It’s a flexible API and if you want to simply pull content items out of Sitecore and consume that data in a headless app, then this is a great alternative to Headless Services. One downside is that you don’t get the rendering information that you would have been able to retrieve via the Layout Service, but if you only need items then this is your simplest, best, and cheapest option.
Finally, you can always create your own API endpoints using .NET. In ASP.NET MVC this will probably be a Controller API or Web API endpoint with custom routing. This approach is very flexible, is something that any .NET developer will be comfortable with creating, and it doesn’t require any additional licenses to serve content.
No doubt there are other ways to pull content out of Sitecore for consumption in your headless solutions (e.g. the Item WebAPI – does that still exist?) but these are the mainstream approaches. If you want to take full advantage of the headless rendering SDKs and leverage analytics, personalisation, content testing, and the power of Sitecore’s content management feature set (placeholders, renderings, templates, datasources, etc) then Headless Services is probably the best option, but if you don’t need those features, or if your client/employer doesn’t want to foot the bill for headless, then there are still some solid options available for pulling data out of Sitecore to power your headless solutions.
Recently I had the opportunity to present to the friendly folks at the Pittsburgh Sitecore User Group. The session on March 26 was an updated version of the presentation that I made to the Perth SUG back in December.
Thanks Bala and Madhu for having me! The slides are available below:
Out of the box, the Layout Service returns the Context and Route objects (see my earlier post for more info on the Layout Service.) On my current JSS React project we wanted to add various metadata fields to the route and render them in the HEAD tag via Helmet, which was fine until we hit the need to add a URL for the OpenGraph og:url metadata tag.
The requirement was:
if no value is supplied in the Canonical URL field or the OpenGraph URL metadata field in the Sitecore route item, then show the current URL of the route.
In server-side MVC land we would do this all the time, and in Sitecore JSS you’d think we could use Window.location (because JavaScript). But (and there’s always a “but”) this project uses React with Server Side Rendering (SSR), so the Window.location object isn’t available when the app is first rendered and delivered to the browser by Node.js. Now maybe there’s a clever way to handle this with React, Node, and a handful of magic beans, but that’s not something I am particularly comfortable with, so I chose to do it in .NET on the server by modifying the data returned by the Layout Service. And aside from that, this approach can be used to populate the context with other data that isn’t available client-side.
Given that the Layout Service returns something much like this:
Then where is the right place to put the URL in the layout service JSON in order to populate the og:url metadata?
The first option I considered was to add it to the Route, but this appeared to entail overriding the Sitecore.LayoutService.ItemRendering.Render method and extending the RenderedItem class so that it returned a URL property, but the amount of change required was extensive, or so it seemed to me anyway.
Option 2 was to add it to the Context which was much simpler and used some typical pipeline processor code that can be patched in. Looking at the pipeline config for GetLayoutServiceContext:
it was apparent that it would be simple to add another pipeline processor that would add the data to the Context. Using LinkManager to calculate the URL for the context item, and patching the processor into the Layout Service pipeline required minimal code:
Which resulted in the expected JSON output with an “itemUrl” property containing the URL of the context item:
And the Sitecore config was patched to be:
Another approach might be to use a rendering with a datasource, but that would not be a great editor experience.
You could argue that the context item URL doesn’t belong in the Context and ideally the route is the best place for this data, but given the changes needed to change the rendering of the route, this seemed the best option. I’d be interested to hear of a low-touch method to amend the route properties.
In my previous post, I covered the basics of how the Layout Service and Rendering Contents Resolvers work together to deliver component rendering data via the API for consumption by rendering hosts using Sitecore’s headless delivery options such as the JSS or .NET Core SDKs.
In this post we will look at why we might want to customise the structure and content of component rendering data returned via the API.
Let’s start with an example.
Everyone knows that Australia is stuffed to the gills with lethal creatures such as sharks, spiders, jellyfish, snakes, ants, and scorpions. In fact it is so dangerous that you should never come here. To warn people of the dangers, I’ve created a blog about the perils of these creatures.
Within a JSS site and JSS tenant hosted in SXA there is a root Blog node based on a Blog route template (which extends the default JSS App Route) and some child routes created using a Blog Article route template:
On individual Blog Article routes I’ve added a rendering via Standard Values presentation details which is called Recommended For You and which renders out some promo cards that point to recommended blog articles.
This rendering uses a datasource containing a Multilist field which content managers can use to assign specific articles as “Recommended” articles:
The JSS app will iterate through these and render a promo card with an image, teaser text, and a link to the actual article.
Let’s take a look at what the output of this looks like using the default features of the Layout Service.:
As you can see, there is a single rendering Recommended Blogs that has a datasource assigned which contains 2 fields: moduleTitle and recommendedItems.
The recommendedItems field is a Multilist and that presents in the field value as a | separated list of item IDs representing the recommended blog articles. The first problem here is, well, what the heck are we supposed to do with a bunch of IDs? Our front end devs won’t be able to render a list of promo items that link to the recommended blogs when they only have some ID values to work with. We could use GraphQL but I’m going to use a rendering contents resolver because it will provide a more consistent, familiar data structure for the devs to work with (and if I didn’t, then this blog post would be called something else.)
As I mentioned in my previous post, the rendering contents resolvers (except Sitecore Forms) all use the same code, just with different parameters. That code is in:
Sitecore.LayoutService.ItemRendering.ContentsResolvers.RenderingContentsResolver, Sitecore.LayoutService
To extend this functionality we can override the ResolveContents method (or implement IRenderingContentsResolver):
public override object ResolveContents(Sitecore.Mvc.Presentation.Rendering rendering, IRenderingConfiguration renderingConfig)
From there it’s a simple matter to get the datasource using GetContextItem. For this to work you can either set UseContextItem to false in the code, or uncheck the checkbox in the Sitecore Content Editor:
The first version of the code looks like this:
The code is pretty straightforward, it:
[The Nuget packages required for this code are Sitecore.Kernel and Sitecore.LayoutService]
A new rendering contents resolver is added in Sitecore using this assembly:
And then applied to the rendering:
The rendering data in the Layout Service JSON now looks like this:
Which is much better. We now have an array of Sitecore Items and all the fields that we need (and some we don’t).
There’s a couple of things about the above output that are not ideal:
You could look at using ContentSearch for retrieving the data, but the Rendering Contents Resolver serializer expects only items so a content search results model would still have to be mapped onto an item before serialization, which seems kind of pointless. I looked at extending the serializer code, but it was Items all the way down and not worth the effort. In terms of efficiency, this rendering will probably take advantage of the item cache and other caching options can be applied so that it doesn’t hit the database as frequently.
Another option you might think would be to modify the Fields property of the Item…..
So in the end I settled on creating a model Sitecore template for the blog promo card which contained only the fields that I wanted to return, and then mapped the Blog item data onto an in-memory “fake” Item and serialized that. The model template has only a few fields:
The new code looks like this:
Instead of adding raw Blog Article Items to the items collection, this code maps the retrieved Items onto a BlogCardRenderingModel which is created on the fly in code and returns a collection of those instead. I used Alistair Deneys’ (@adeneys) excellent blog post on this as a guide for creating the “fake” model item, although there are a few changes here. In particular:
The mapping also calculates the URL for the item using LinkManager. The final JSON output now looks like this:
Each item in the rendering data now only contains the fields articleTitle, categories, image, teaserText, url, id and name, which is a lot leaner and prevents the Layout Service from becoming unnecessarily bloated.
Modifying or extending the contents resolver allows us to reduce bloat and return exactly the data we need, but it also opens up opportunities to pull data in from other sources for use in renderings, combine data from the Content Search API with Sitecore item queries, and filter, sort, and group the data in different ways.
[The code and content for this post and the previous one are on Github]
When developing JSS or.NET Core headless solutions, one of the key components is the Layout Service. The Layout Service composes and serves a JSON description of the context, route, placeholders, renderings (components), and datasources that can be used to populate the data which the rendering engine uses to render the final UI of the application. The Layout service is part of Sitecore Headless Services (previously known as JSS Server Components) and powers both JSS and the newer .NET Core headless rendering approaches. You can find out more about the Layout Service here.
In this post we’ll look at the Layout Service payload and at how Sitecore uses a Rendering Contents Resolver to determine the contents and structure of the component rendering data returned via the Layout Service. In a subsequent post we will look at why and how we might extend a Rendering Contents Resolver to suit our needs.
The Rendering Contents Resolver is not the only way to return rendering data to the API – you can also use GraphQL, however that will be the topic of a future post.
Sitecore Headless Services can be used to expose endpoints that return Sitecore route data as JSON, but you need to create and configure a Sitecore Services Client (SSC) API key in order to query it. For details on how to create an SSC API key, see section 2 of this page. Once created, don’t forget to publish your API key if you are using the API endpoint to query the Web database.
The Layout Service API call has the following structure:
https://[siteUrl]/sitecore/api/layout/render/jss?item=[item ID or sitecore path]&sc_apikey=[your api key]
For example:
https://sc10.sc.dev.local/sitecore/api/layout/render/jss?item=/&sc_apikey={6369DDCB-6A77-439F-8A73-C47496DA1CEE}
or
https://sc10.sc.dev.local/sitecore/api/layout/render/jss?item={66C56C12-F526-4E61-9D75-D76895AC2587}&sc_apikey={6369DDCB-6A77-439F-8A73-C47496DA1CEE}
In the first example above the API will return the Layout Service representation of the site root (since we’ve provided the path “/” ). In the second example it will return the layout for a specific item ID (in this case it’s the Blog Home route). You don’t actually have to use curly braces {} to wrap the ID nor the hyphen in the ID – it will work without them. i.e. jss?item=66C56C12F5264E619D75D76895AC2587&sc_apikey=6369DDCB6A77439F8A73C47496DA1CEE will work just the same.
Let’s look at the JSON output:
In the example above, the layout service represents a route called Blog in the context of the jss-demo site and we can see the item Name (Blog), ID, and a few other properties such as databaseName (in this case it’s the Sitecore master database.)
The root of the JSON contains the context and the route data:
Looking at the route, we can see it contains route-level fields such as pageContent, pageTitle, as well as item name, version, ID, etc:
Basically this is all the stuff you’d expect see about the item, although quite a lot has been filtered out for us already, since we don’t want to send ALL the item data down the pipe in the JSON because that would (a) increase the size of the JSON payload, and (b) expose a lot of irrelevant data or data that should be hidden from the browser. I’m using JSS on top of SXA, so the Page Design field has been returned as well, however there isn’t a page design applied currently.
Within the route, we can also see 3 placeholders:
Each placeholder can contain an array of zero or more renderings (aka “components” in JSS terminology.)
In this case, only one of these placeholders has been populated (jss-demo-ph-content). That placeholder contains a rendering “Blog Promo” which has a datasource {621726E6-4D0C-4C4E-9081-44A874C98A38} that represents a blog article:
As we can see, the fields on the datasource have been serialised and returned in the Layout Service data, as well as the (currently empty) params object which would contain rendering parameters if populated. Back on the Sitecore server the datasource item has been retrieved and serialised for us to use in the rendering engine. This is where the Rendering Contents Resolver fits in.
Note that you can return whatever JSON data you like as component rendering data, but the structure above is what the default serialised item data looks like.
Out of the box, Sitecore Headless Services provides 6 resolvers, and these are in sitecore/System/Modules/Layout Service/Rendering Contents Resolvers
The default resolver is the Datasource Resolver which, as the name suggests, serializes the datasource item.
The various OOTB resolvers are summarised below
Resolver | Function |
Context Item Children Resolver | Serializes the children of the context item |
Context Item Resolver | Serializes the context item |
Datasource Item Children Resolver | Serializes the children of the datasource item |
Datasource Resolver | Serializes the datasource item |
Folder Filter Resolver | Serializes the descendants of the datasource item, excluding folders |
Sitecore Forms Resolver | Retrieves and serializes a Sitecore Form and its associated items |
[tip of the hat to Gary Wenneker who covered this a while ago]
It is important to note however, that although the default is the Datasource Resolver, it only uses the resolver code with default properties and does not reference the actual Datasource Resolver item. Therefore if you change the properties of the Datasource Resolver item in the Layout Service/Rendering Contents Resolvers section of the tree it will have no effect on your rendering output unless you go into the rendering settings and set the value for Rendering Contents Resolver as per below:
All of the resolvers above (except Sitecore Forms Resolver) use exactly the same code, just with some properties passed in that define what to retrieve and how to serialize it. The type is: Sitecore.LayoutService.ItemRendering.ContentsResolvers which is in the Sitecore.LayoutService assembly.
The properties that can be set are:
Type: the .NET type that retrieves and serialises the output. As is usual with Sitecore, you can create your own, which we will cover the in my next post.
Include Server URL in Media URLs: Fairly self explanatory, fully qualifies the URL for the media item src.
Use Context Item: retrieves the context item instead of the datasource item. You might want to use this to populate route level data into a rendering (e.g. for route metadata values perhaps, although you could do this client side without needing to set this value.) In the code, there is a not very well named method GetContextItem(rendering, renderingConfig) which will return the context item if this property is true, otherwise it will do a GetItem on the datasource item (if one has been provided).
Item Selector Query: Sitecore query to select and filter items for inclusion in the rendering data
All of the above will cover simple rendering data requirements, but there may be situations where it is preferable to modify the structure and the contents of the data returned to a rendering. In my next post I will look at extending the OOTB resolver code and why this might be useful.
[The code and content for this post and the subsequent one are on Github]