Headless

In a headless Brightspot implementation, the View System delivers content via a JSON API to a consuming application; that application processes and transforms the content using its own logic. In headless Brightspot implementations, two scenarios are common:

  • Delivering APIs to mobile applications
  • Delivering APIs to JavaScript frameworks (React, Angular, or others)

Producing your JSON API requires two steps:

  1. Create a Model
  2. Create a ViewModel

The following sections provide examples for each of those steps.

Model

The following snippet is a basic Model for an article.

import com.psddev.cms.db.Content;
import com.psddev.dari.db.Recordable;

public class Article extends Content {

    private String headline;

    private String body;

    public String getHeadline() {
        return headline;
    }

    public void setHeadline(String headline) {
        this.headline = headline;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}

ViewModel

The following snippet is a headless ViewModel that receives data from the Article Model (line 8) and transforms it into JSON format (line 6).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import com.psddev.cms.view.JsonView;
import com.psddev.cms.view.PageEntryView;
import com.psddev.cms.view.ViewInterface;
import com.psddev.cms.view.ViewModel;

@JsonView
@ViewInterface
public class ArticleViewModel extends ViewModel<Article> implements PageEntryView {

    public String getBody() {
        return model.getBody();
    }

    public String getHeadline() {
        return model.getHeadline();
    }
}

At run time, Brightspot manages the interaction between the Model and ViewModel to produce the JSON file containing field names and associated values.

{
  "headline" : "JSON Example",
  "body" : "Brightspot automatically produces JSON from the ViewModel."
}

The consuming application has the responsibility of processing the JSON output for downstream purposes.