Using strongly typed models

Strongly typed models are programmatic representations of the content types in your Kentico Kontent project. They help you map the content retrieved from the Delivery API (which comes in the form of JSON objects) directly to a model you can use in your code.

Table of contents

    This practice has several advantages:

    • type safety during compile-time
    • convenience (IntelliSense remembers content type properties for you)
    • support of type-dependent functionalities (such as display templates in MVC)

    Life without strongly typed models

    When retrieving content directly from the API, you receive your content items as JSON objects. Your application then needs to parse the JSON to display your content.

    For example, in TypeScript, you would access a Headline element of your content item like this: response.item.elements.headline.value. Here is an example of retrieving, parsing and displaying a small content item.

    In a more complicated scenario, this approach quickly becomes cumbersome. You have to remember the JSON structure of your item and the codenames of your content elements.

    To make this easier, our Delivery SDKs allow you to map the retrieved content items to their strongly typed models.

    Defining strongly typed models

    The models are plain classes that don't have any attached behavior or dependency on an external framework. Each model corresponds to a content type in your Kentico Kontent project.

    Here is the Homepage content type used in the previous TypeScript code example.

    Sample Homepage Content Type

    To create the content type's representation in code, you need a class with properties representing the individual content elements:

    • Each property is mapped to its content element's codename either explicitly or using a naming convention (for example, body_text becomes bodyText).
    • Properties are usually typed using classes provided by the SDK.
    • Depending on the SDK, simple content elements (Text, Number, etc.) are sometimes represented using native types (string, integer, etc.).

    The following example is a strongly typed model of the Homepage content type in several languages.

    • Java
    import com.kenticocloud.delivery.Asset; import com.kenticocloud.delivery.ContentItemMapping; import com.kenticocloud.delivery.ElementMapping; import com.kenticocloud.delivery.System; import java.lang.String; import java.util.List; /** * This code was generated by a <a href="https://github.com/Kentico/cloud-generators-java">cloud-generators-java tool</a> * * Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. * For further modifications of the class, create a separate file and extend this class. */ @ContentItemMapping("homepage") public class Homepage { @ElementMapping("body_text") String bodyText; @ElementMapping("headline") String headline; @ElementMapping("picture") List<Asset> picture; System system; public String getBodyText() { return bodyText; } public void setBodyText(String bodyText) { this.bodyText = bodyText; } public String getHeadline() { return headline; } public void setHeadline(String headline) { this.headline = headline; } public List<Asset> getPicture() { return picture; } public void setPicture(List<Asset> picture) { this.picture = picture; } public System getSystem() { return system; } public void setSystem(System system) { this.system = system; } }
    import com.kenticocloud.delivery.Asset; import com.kenticocloud.delivery.ContentItemMapping; import com.kenticocloud.delivery.ElementMapping; import com.kenticocloud.delivery.System; import java.lang.String; import java.util.List; /** * This code was generated by a <a href="https://github.com/Kentico/cloud-generators-java">cloud-generators-java tool</a> * * Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. * For further modifications of the class, create a separate file and extend this class. */ @ContentItemMapping("homepage") public class Homepage { @ElementMapping("body_text") String bodyText; @ElementMapping("headline") String headline; @ElementMapping("picture") List<Asset> picture; System system; public String getBodyText() { return bodyText; } public void setBodyText(String bodyText) { this.bodyText = bodyText; } public String getHeadline() { return headline; } public void setHeadline(String headline) { this.headline = headline; } public List<Asset> getPicture() { return picture; } public void setPicture(List<Asset> picture) { this.picture = picture; } public System getSystem() { return system; } public void setSystem(System system) { this.system = system; } }
    • C#
    // This code was generated by a kontent-generators-net tool // (see https://github.com/Kentico/kontent-generators-net). // // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. // For further modifications of the class, create a separate file with the partial class. using System; using System.Collections.Generic; using Kentico.Kontent.Delivery; namespace KenticoKontentModels { public partial class Homepage { public const string Codename = "homepage"; public const string HeadlineCodename = "headline"; public const string BodyTextCodename = "body_text"; public const string PictureCodename = "picture"; public string Headline { get; set; } public IRichTextContent BodyText { get; set; } public IEnumerable<Asset> Picture { get; set; } public ContentItemSystemAttributes System { get; set; } } }
    // This code was generated by a kontent-generators-net tool // (see https://github.com/Kentico/kontent-generators-net). // // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. // For further modifications of the class, create a separate file with the partial class. using System; using System.Collections.Generic; using Kentico.Kontent.Delivery; namespace KenticoKontentModels { public partial class Homepage { public const string Codename = "homepage"; public const string HeadlineCodename = "headline"; public const string BodyTextCodename = "body_text"; public const string PictureCodename = "picture"; public string Headline { get; set; } public IRichTextContent BodyText { get; set; } public IEnumerable<Asset> Picture { get; set; } public ContentItemSystemAttributes System { get; set; } } }
    • TypeScript
    import { ContentItem, Elements } from "@kentico/kontent-delivery"; /** * Generated by "@kentico/kontent-model-generator" * Timestamp: Tue Sep 24 2019 15:07:22 GMT+0200 (GMT+02:00) * * Tip: You can replace "ContentItem" with another generated class to fully leverage strong typing. */ export class Homepage extends ContentItem { public headline: Elements.TextElement; public bodyText: Elements.RichTextElement; public picture: Elements.AssetsElement; constructor(){ super({ propertyResolver: ((elementName: string) => { if (elementName === "body_text"){ return "bodyText"; } return elementName; }) }) } }
    import { ContentItem, Elements } from "@kentico/kontent-delivery"; /** * Generated by "@kentico/kontent-model-generator" * Timestamp: Tue Sep 24 2019 15:07:22 GMT+0200 (GMT+02:00) * * Tip: You can replace "ContentItem" with another generated class to fully leverage strong typing. */ export class Homepage extends ContentItem { public headline: Elements.TextElement; public bodyText: Elements.RichTextElement; public picture: Elements.AssetsElement; constructor(){ super({ propertyResolver: ((elementName: string) => { if (elementName === "body_text"){ return "bodyText"; } return elementName; }) }) } }

    Generating models

    To avoid having to write models manually, you can generate them using model generators. Currently, there are generators available for JavaScript/TypeScript, .NET and Java:

    To download and install a specific model-generator utility, follow instructions in their respective README files.

    You can then use the utility to generate strongly typed models from your Kentico Kontent project by passing it your Project ID.

    • Java
    // For instructions on using the Java model generator, visit https://github.com/Kentico/cloud-generators-java // Configures Gradle plugin apply plugin: "java" kenticoModel { projectId = "8d20758c-d74c-4f59-ae04-ee928c0816b7" packageName = "com.helloheadlessworld.models" outputDir = file("generated-sources") } dependencies { compile("com.kenticocloud:delivery-sdk-java:1.0.3") } // Runs generateModels task ./gradlew generateModels
    // For instructions on using the Java model generator, visit https://github.com/Kentico/cloud-generators-java // Configures Gradle plugin apply plugin: "java" kenticoModel { projectId = "8d20758c-d74c-4f59-ae04-ee928c0816b7" packageName = "com.helloheadlessworld.models" outputDir = file("generated-sources") } dependencies { compile("com.kenticocloud:delivery-sdk-java:1.0.3") } // Runs generateModels task ./gradlew generateModels
    • shell
    kontent-generate --projectId=8d20758c-d74c-4f59-ae04-ee928c0816b7 --codeType=JavaScript --moduleResolution=ES2015
    kontent-generate --projectId=8d20758c-d74c-4f59-ae04-ee928c0816b7 --codeType=JavaScript --moduleResolution=ES2015
    • shell
    KontentModelGenerator.exe --projectid 8d20758c-d74c-4f59-ae04-ee928c0816b7 --withtypeprovider --structuredmodel
    KontentModelGenerator.exe --projectid 8d20758c-d74c-4f59-ae04-ee928c0816b7 --withtypeprovider --structuredmodel
    • shell
    kontent-generate --projectId=8d20758c-d74c-4f59-ae04-ee928c0816b7 --codeType=TypeScript --moduleResolution=ES2015
    kontent-generate --projectId=8d20758c-d74c-4f59-ae04-ee928c0816b7 --codeType=TypeScript --moduleResolution=ES2015

    Retrieving strongly typed content

    With your models defined and included in your application, you can use them when retrieving content from Kentico Kontent.

    • Java
    import com.kenticocloud.delivery.DeliveryClient; import java.io.IOException; import java.lang.System; // Creates an instance of the DeliveryClient DeliveryClient client = new DeliveryClient("8d20758c-d74c-4f59-ae04-ee928c0816b7"); // Gets a content item from Kentico Cloud by its codename and maps it to its strongly-typed model try { Homepage homepage = client.getItem("hello_headless_world", Homepage.class); // Use homepage // System.out.println(homepage.getHeadline()); } catch (IOException e) { e.printStackTrace(); }
    import com.kenticocloud.delivery.DeliveryClient; import java.io.IOException; import java.lang.System; // Creates an instance of the DeliveryClient DeliveryClient client = new DeliveryClient("8d20758c-d74c-4f59-ae04-ee928c0816b7"); // Gets a content item from Kentico Cloud by its codename and maps it to its strongly-typed model try { Homepage homepage = client.getItem("hello_headless_world", Homepage.class); // Use homepage // System.out.println(homepage.getHeadline()); } catch (IOException e) { e.printStackTrace(); }
    • C#
    using Kentico.Kontent.Delivery; using KenticoKontentModels; // Initializes a content delivery client IDeliveryClient client = DeliveryClientBuilder .WithProjectId("8d20758c-d74c-4f59-ae04-ee928c0816b7") .Build(); // Gets a content item by codename and maps it to the item"s strongly typed model DeliveryItemResponse<Homepage> response = await client.GetItemAsync<Homepage>("hello_headless_world"); var homepage = response.Item; // Use homepage // Console.WriteLine(homepage.Headline);
    using Kentico.Kontent.Delivery; using KenticoKontentModels; // Initializes a content delivery client IDeliveryClient client = DeliveryClientBuilder .WithProjectId("8d20758c-d74c-4f59-ae04-ee928c0816b7") .Build(); // Gets a content item by codename and maps it to the item"s strongly typed model DeliveryItemResponse<Homepage> response = await client.GetItemAsync<Homepage>("hello_headless_world"); var homepage = response.Item; // Use homepage // Console.WriteLine(homepage.Headline);
    • TypeScript
    import { ContentItem, DeliveryClient, Elements, SortOrder, TypeResolver } from "@kentico/kontent-delivery"; import { Homepage } from "./models/homepage"; // Creates an instance of the Delivery client and registers your model in type resolvers const deliveryClient = new DeliveryClient({ projectId: "8d20758c-d74c-4f59-ae04-ee928c0816b7", typeResolvers: [ new TypeResolver("homepage", (rawData) => new Homepage) ] }); var homepage: Homepage; // Gets a content item from Kentico Cloud by its codename and maps it to its strongly typed model deliveryClient.item<Homepage>("hello_headless_world") .toObservable() .subscribe(response => { homepage = response.item; // Use homepage; // console.log(homepage.headline.value); });
    import { ContentItem, DeliveryClient, Elements, SortOrder, TypeResolver } from "@kentico/kontent-delivery"; import { Homepage } from "./models/homepage"; // Creates an instance of the Delivery client and registers your model in type resolvers const deliveryClient = new DeliveryClient({ projectId: "8d20758c-d74c-4f59-ae04-ee928c0816b7", typeResolvers: [ new TypeResolver("homepage", (rawData) => new Homepage) ] }); var homepage: Homepage; // Gets a content item from Kentico Cloud by its codename and maps it to its strongly typed model deliveryClient.item<Homepage>("hello_headless_world") .toObservable() .subscribe(response => { homepage = response.item; // Use homepage; // console.log(homepage.headline.value); });

    A complete example

    This code example is equivalent to the first one but maps the retrieved content item to a strongly typed model.

    What's next?

    In practice, you often have to define how your application resolves Rich text elements containing assets, links, components, and other content items. This works a little differently for each platform, so we recommend that you have a look at the documentation of the SDK you are using:

    For more advanced examples of using strongly typed models, see our sample applications.