Using Views to provide custom data sources

The RESTful Web Services module provides Views plugins that allow you to expose data over Views for your RESTful API. This allows you to create a view that has a path and outputs data using a serializer plugin. You can use this to output entities, such as JSON, HAL JSON, or XML, and it can be sent with appropriate headers.

In this recipe, we will create a view that outputs the users of the Drupal site, providing their username, e-mail, and picture if provided.

How to do it…

  1. Visit Extend from the administrative toolbar and install the Web Services modules: Serialization, RESTful Web Services, and HAL.
  2. Visit Structure and then Views. Click on Add new view. Name the view API Users and have it show Users.
  3. Check the Provide a REST export checkbox, and use the api/users path. This is where requests will be made:
    How to do it…
  4. Click on Save and edit.
  5. Change the format of the row plugin from Entity to Fields instead so that we can control the specific output.
  6. Ensure that your view has the following user entity fields: Name, Email, and Picture.
  7. Change the User: Name field to the Plain text formatter and do not link it to the user, so the response does not contain any HTML.
  8. Save your view.
  9. Access your view by visiting /api/users and you will receive a JSON response containing the user information:
    [
      {
        "name": "houotrara",
        "mail": "[email protected]",
        "user_picture": "  <img src="http://example.com/sites/default/files/pictures/2016-01/generateImage_a7JEUp.jpeg" width="89" height="87" alt="Abdo bene blandit comis esse eum lobortis minim qui." title="Abdo aptent bene saepius si vulputate." typeof="foaf:Image" />
    
    "
      },
      {
        "name": "cragedrelohi",
        "mail": "[email protected]",
        "user_picture": "  <img src="http://example.com/sites/default/files/pictures/2016-01/generateImage_pQDdBa.jpeg" width="94" height="98" alt="Aliquip decet eu iaceo jus obruo praesent premo." title="Exerci turpis wisi. Commodo gravis scisco venio." typeof="foaf:Image" />
    
    "
      }
    ]

How it works…

The RESTful Web Services module provides a display, row, and format plugin that allows you to export content entities to a serialized format. The REST Export display plugin is what allows you to specify a path to access the RESTful endpoint, and properly assigns the Content-Type header for the requested format.

The Serializer style is provided as the only supported style plugin for the REST Export display. This style plugin only supports row plugins that identify themselves as data display types. It expects data from the row plugin to be raw so that it can be passed to the appropriate serializer.

You then have the option of using the Data entity or Data field row plugins. Instead of returning a render array from their render method, they return raw data that will be serialized into the proper format.

With the row plugins returning raw format data and the data then serialized by the style plugin, the display plugin will then return the response, converted into the proper format via the Serialization module.

There's more…

Views provide a way to deliver specific RESTful endpoints. We will explore some additional features in the next recipe.

Controlling the key name in JSON output

The Data fields row plugin allows you to configure field aliases. When the data is returned through the view, it will have Drupal's machine names. This means that custom fields will look something like field_my_field, which may not make sense to the consumer. By clicking on Settings next to Fields you can set aliases in the modal form:

Controlling the key name in JSON output

When you provide an alias, the fields will match. For example, user_picture can be changed to avatar and the mail key can be changed to e-mail:

[{
  "name": "houotrara",
  "mail": "[email protected]",
  "avatar": "
}]

Controlling access of RESTful Views

When you create a RESTful endpoint with Views, you are not using the same permissions created by the RESTful Web Services module. You need to define the route permissions within the view, allowing you to specify specific roles or permissions for the request.

The default GET method provided by the EntityResource plugin does not provide a way to list entities, and allows any entity to be retrieved by an ID. Using Views, you can provide a list of entities, limiting them to specific bundles and many more.

Using Views, you can even provide a new endpoint to retrieve a specific entity. Using Contextual filters, you can add route parameters and filters to limit and validate entity IDs. For example, you may want to expose the article content over the API, but not pages.

Add a URL formatter for the image field

As you may have noticed, our user_picture field returned the complete HTML for the image and not a URL for the image directly. In fact, currently, there is no option, as of 8.0.x, to return the URL or endpoint resource for the image file. There is, however, an item in the issue queue to resolve this, which is available at https://www.drupal.org/node/2517030, slated for 8.1.x.

You have the option of implementing your own field formatter or applying the patch in your build to get the formatter. Or, you can use the Backports module. At the time of writing this module, the URL field formatter is the only patch provided by the module. However, the purpose of the module is to implement a functionality that is not provided by Drupal but will be provided in the near future. You can get the Backports module at https://www.drupal.org/project/backports.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset