Drupal 8 headless with BackboneJS, retrieve single entity with referenced field

Events happening in the community are now at Drupal community events on www.drupal.org.
robert ngo's picture

Hello friends,

I'm building up a contact directory search with Drupal 8 and Backbone. The idea is to benefit Drupal 8 to set up and expose search data via Views with Json format.

And I have 2 questions regarding setting up REST endpoint

  1. When retrieving a single node from Backbone, I'd call /node/[nid]?_format=json and get
    {
        "nid": [{
            "value": "55"
        }],
        "uuid": [{
            "value": "ec524ba2-5514-4179-a916-2213d40a0641"
        }],
        "vid": [{
            "value": "55"
        }],
        "field_acc_type": [{
            "target_id": "4",  // <- referenced field
            "url": "\/taxonomy\/term\/4"
        }],
       ...
    }

    field_acc_type returns with target_id and url, which mean I need to fire another request to server to retrieve that account type entity?
    Is there a better way to fire only 1 request and get all data I need ?

  2. Rather than calling /node/[nid]?_format=json, I'd prefer to create a views with REST export because JSON structure is more simple than the JSON in 1st question. However, data output of the view is an array (yes, I understand what views means to do). Is it a good practice to try altering the output to show only 1 JSON object (using hook_views_pre_render, or hook_views_post_execute ... )
    In stead of

    [
      {
         title: "Node 1",
         type: "account-drupal" 
         ....
      }
    ]

    to make it print out
    {
         title: "Node 1",
         type: "account-drupal" 
         ....
    }  <- not an array

    Any help is going to be much appreciated : )

Comments

Have you tried using a views

Lowell's picture

Have you tried using a views json display? I think what you are asking for is already part of core.

Yes, I tried it, it's

robert ngo's picture

Yes, I tried it, it's described in my 2nd question above, in Drupal 8, I just use Views with REST export.

The problem is that views return an array, but to conform Backbone model (not Backbone Collection), the output must be a single JSON object.

Headless Drupal

Group organizers

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds: