Drupal 8: Enabling Facets for Restful web services.

When there is a need of providing search as a RESTFUL web service, it is important that we need to send facets with the search results with in the data.

If you have facets in your drupal instance configured for search pages then you have your Facets module enabled. If not download and install the module from https://www.drupal.org/project/facets.

If you configured facets for the Restful search web service, the following web service results will be

[
   {
      "node_id":"101",
      "title":"Lorem ipsum one",
   },
   {
      "node_id":"102",
      "title":"Lorem ipsum two",
   },
   {
      "node_id":"103",
      "title":"Lorem ipsum three",
   },
   {
      "node_id":"104",
      "title":"Lorem ipsum four",
   }
]

If you need to enable facet data with above result, Enable the module “Rest Facets" which comes as a sub module with ”Facets” module.

After enabling the “Rest Facets” you can able to see a new formatter as “Facets serializer” in your Rest Enabled Search views.

Choose the request formatters in the settings,

Hence the result with facets will be

{
   "search_results":[
      {
         "node_id":"101",
         "title":"Lorem ipsum one"
      },
      {
         "node_id":"102",
         "title":"Lorem ipsum two"
      },
      {
         "node_id":"103",
         "title":"Lorem ipsum three"
      },
      {
         "node_id":"104",
         "title":"Lorem ipsum four"
      }
   ],
   "facets":[
      [
         {
            "facet1":[
               {
                  "url":"http:\/\/baseurl.com\/rest\/path?facet[0]=keyone:value1",
                  "values":{
                     "value":"value1",
                     "count":10
                  }
               },
               {
                  "url":"http:\/\/baseurl.com\/rest\/path?facet[0]=keyone:value2",
                  "values":{
                     "value":"value2",
                     "count":13
                  }
               },
               {
                  "url":"http:\/\/baseurl.com\/rest\/path?facet[0]=keyone:value3",
                  "values":{
                     "value":"value3",
                     "count":2
                  }
               }
            ]
         }
      ],
      [
         {
            "facet2":[
               {
                  "url":"http:\/\/baseurl.com\/rest\/path?facet[0]=keytwo:value10",
                  "values":{
                     "value":"value10",
                     "count":5
                  }
               },
               {
                  "url":"http:\/\/baseurl.com\/rest\/path?facet[0]=keytwo:value11",
                  "values":{
                     "value":"value11",
                     "count":9
                  }
               }
            ]
         }
      ]
   ]
}
Category: