React and EPiServer: Moving to EPiServer Headless (EPiServer.ContentDeliveryApi) with friendly URLs – Quick POC

So EPiServer released a beta version of the ContentDeliveryApi. Nice. My current client uses the JOS Content Serializer for creating JSON data from EPiServer pages for view, preview and on-page-editing with React, as described in previous articles. However, sooner or later it will be neccessary to start using EPiServer’s own methods for this.

I had a quick look at the API functionality, and it seems like you get pretty JSON requesting URLs like /api/episerver/v1.0/content/3 and so on. However, what I really wanted was friendly URLs delivering JSON for the page in question. For instance, requesting /en/alloy-plan/download-alloy-plan/start-downloading/ would give me JSON for the Start Downloading page.

So I made a quick and somewhat dirty POC on how to do this, just until I find a better way. Here is what I came up with:

Making EPiServer Content Delivery Api give you JSON for friendly URLs

The package you need is called EPiServer.ContentDeliveryApi and is available on the EPiServer NuGet stream. I installed a fresh Alloy template MVC website and added the package.

After a bit of digging into the ContentApiController in EPiServer’s assembly EPiServer.ContentApi I found that they are in fact using a mapping service to get serializable content. This seems to be similar to the way as the JOS Content Serializer did it.

The interface you want is called IContentModelMapper and resides in EPiServer.ContentApi.Core. Below is a slightly altered version of the DefaultPageController in the Alloy project.

public class DefaultPageController : PageControllerBase<PublicBasePage>
  public ActionResult Index(PublicBasePage currentPage)
    var mapper = ServiceLocator.Current.GetInstance<IContentModelMapper>();
    var transformed =  mapper.TransformContent(currentPage);

    var serializer = ServiceLocator.Current.GetInstance<ISerializer<ContentApiModel>>();
    return PartialView("_ApiPoc", serializer.Serialize(transformed));

The overall paradigm is the same as how we did it with the JOS Content Serializer. Just use the internal mapping method on the relevant content, serialize it and pass it as a string model.

The implementation of ISerializer above is just giving us a standard Newtonsoft JSON Serializer. Pass the IContent into EPiServer’s TransformContent method and you’re done. This stuff would probably go in a base class, and perhaps be customizable through headers or whatnot, but just to test the functionality. Also, you would probably want to add your own custom non-EPiServer properties for passing processed data, before actually serializing it.

@model string
<!DOCTYPE html>
    <meta charset="utf-8" />

For now I just outputted the JSON in the body tag. Surfing to the URL this is what I got:

JSON generated by EPiServer using their new headless functionality for Friendly URLs