Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more

PuneetGarg
Oct 15, 2024
  32
(0 votes)

Headless with Content Delivery API

Hello Everyone,

This blog will help anyone who wants to start or build an architecture of headless using content delivery api.

When we shifted to headless CMS 12 my first question was how content would be fetched from the front end (I know we have direct API's for them) it's about the building JSON for those pages or blocks.

So I'll share my code experience step by step (I'm taking an example of a page but we can do the same for blocks)

  1. Create a normal Page Type.
  2. Now how will your compiler know which page it has to run we are not directly calling it from view to controller as we are used to it in normal architecture so for that we will create ApiFilters(it will run all every call)
    • Register that Api Filter as Singleton like this  _services.AddSingleton<IContentApiModelFilter, ProductCollectionPageApiModelFilter>();
    • Inside your filter, you need to check if the current request matches your type If not return and do nothing.
    • If it matches your type then we need to create custom code to add our contentarea to our JSON results for that we will create a method where we will do our filtering and binding our model that will be passed in JSON.
    • public void AddContentAreaItemsToContentApiModel(string key, ContentArea contentArea, ContentApiModel contentApiModel)
      {
          var items = new Dictionary<string, object>();
      
          if (contentArea == null || contentArea.FilteredItems == null)
          {
              contentApiModel.Properties.Add(key, items);
              return;
          }
      
          var Filtereditems = contentArea.FilteredItems;
          var index = 0; //Will be appended to the item name in the contentApiModel to prevent duplicate keys in case we have multiples of the same block type 
      
          foreach (var contentAreaItem in Filtereditems)
          {
              _contentLoader.TryGet<IContent>(contentAreaItem.ContentLink, out var content);
      
              if (content == null)
                  continue;
      
              switch (content)
              {
                  // all blocks and pages that will be there in the content area create a case for it like this 
                  case PageType x:
                      {
                          items.Add(nameof(PageType ) + "_" + index, _commerceViewModelBuilder.GetPageDetails(x));
                          index++;
                          break;
                      }
                  default:
                      {
                          index++;
                          break;
                      }
              }
          }
      
          contentApiModel.Properties.Add(key, items);
      }
             
    • this filter will create a key-value pair which will be our JSON result.
    • GetPageDetails -> method that will accept that type and create the model we want to add.
  3. Add this method to our Page type filter, and call your content area in that to filter all things example 
      public class PageApiModelFilter : ContentApiModelFilter<ContentApiModel>
        {
            public override void Filter(ContentApiModel contentApiModel, ConverterContext converterContext)
            {
                try
                {
                    if (!_contentLoader.TryGet(converterContext.ContentReference, out ProductCollectionPage productCollectionPage) || productCollectionPage is not ProductCollectionPage)
                    {
                        return;
                    }
                   
                    AddContentAreaItemsToContentApiModel(nameof(productCollectionPage.TopContentArea), productCollectionPage.TopContentArea, contentApiModel);
                    AddContentAreaItemsToContentApiModel(nameof(productCollectionPage.MainContentArea), productCollectionPage.MainContentArea, contentApiModel);
                    AddContentAreaItemsToContentApiModel(nameof(productCollectionPage.BottomContentArea), productCollectionPage.BottomContentArea, contentApiModel);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
      

4. Now you can call your API from the front end using ID or any other means and in JSON you will have all data that was serialized.

If you want to remove extra data pre and post serialization you can refer to my other blog here is the link https://world.optimizely.com/blogs/puneetgarg/dates/2024/9/remove-unwanted-properties-for-headless-implementation-using-content-delivery-api-/

Hope that helps!

Thank you 

 

Oct 15, 2024

Comments

Please login to comment.
Latest blogs
Optimizely Configured Commerce and Spire CMS - Figuring out Handlers

I recently entered the world of Optimizely Configured Commerce and Spire CMS. Intriguing, interesting and challenging at the same time, especially...

Ritu Madan | Mar 12, 2025

Another console app for calling the Optimizely CMS REST API

Introducing a Spectre.Console.Cli app for exploring an Optimizely SaaS CMS instance and to source code control definitions.

Johan Kronberg | Mar 11, 2025 |

Extending UrlResolver to Generate Lowercase Links in Optimizely CMS 12

When working with Optimizely CMS 12, URL consistency is crucial for SEO and usability. By default, Optimizely does not enforce lowercase URLs, whic...

Santiago Morla | Mar 7, 2025 |

Optimizing Experiences with Optimizely: Custom Audience Criteria for Mobile Visitors

In today’s mobile-first world, delivering personalized experiences to visitors using mobile devices is crucial for maximizing engagement and...

Nenad Nicevski | Mar 5, 2025 |

Unable to view Optimizely Forms submissions when some values are too long

I discovered a form where the form submissions could not be viewed in the Optimizely UI, only downloaded. Learn how to fix the issue.

Tomas Hensrud Gulla | Mar 4, 2025 |

CMS 12 DXP Migrations - Time Zones

When it comes to migrating a project from CMS 11 and .NET Framework on the DXP to CMS 12 and .NET Core one thing you need to be aware of is the...

Scott Reed | Mar 4, 2025