So Gin basically uses the whole design patterns from the Drupal design system so it inherits that. But then on top, it adds all the new features and the new design language or the new layout for editing and other stuff. The Drupal community organizes events all over the globe, both virtually and in-person. To find an event near you, or to submit your own event for listing, check out our community events portal.
We now have a full series on Web Services in Drupal 8, which is much more detailed and accurate, and will be kept up to date with the latest versions of Drupal 8.
This article was last updated on April 14, 2016 by trainer Blake Hall and tested with Drupal 8.0.6. There will be no further updates to this article for newer versions of Drupal core.
One of the Drupal 8 initiatives that really excites me is Web Services. Drupal has never been easy to work with as a web service, but all that is about to change! In this article I am going to explore what has been going on behind the scenes with RESTful Web Services in Drupal Core and attempt to implement some working examples. After reading, you will be able to create a new node on your site via the Drupal 8 Core REST API.
What is REST?
It's best that I first make sure everyone is on the same page. Web Services make it possible for external applications to interact with our application (in this case our Drupal site). The most common interactions are reading, creating, updating, and deleting resources.
REST is one of the most popular ways of making Web Services work. There are other formats such as SOAP or XML-RPC, but we are only going to focus on REST because it is the Drupal standard. REST utilizes HTTP methods, such as GET, POST, and DELETE.
As an example, a popular usage of a REST interface is a mobile application that needs to read and write data from your site's database.
Drupal 8 Core
Web Services have been implemented in Drupal 8 Core with the following modules:
RESTful Web Services (rest)
Exposes entities and other resources via a RESTful web API. It depends on the Serialization module for the serialization of data that is sent to and from the API.
Provides a service for serialization of data to and from formats such as JSON and XML.
Hypertext Application Language (hal)
Extends the Serialization module to provide the HAL hypermedia format. This is what is used as the primary format in Drupal 8 Core. It only adds two reserved keywords, ‘_links’ for link relations (also used by Github's Pull Request API) and ‘_embedded’ for embedded resources. The HAL hypermedia format can be encoded in both JSON and XML. For more details see the initial HAL proposal.
HTTP Basic Authentication (basic_auth)
This module implements basic user authentication using the HTTP Basic authentication provider. It facilitates the use of an username and password for authentication when making calls to the REST API. It is required for the examples shown in this blog post, and I would advise configuring SSL if you use it in production. For anyone looking for a more secure option, check out the contributed OAuth module which already has a Drupal 8 release.
Start by grabbing the latest release of Drupal 8 Core and installing your site. I am using 8.0.6 at the time of writing this post. See the Releases for Drupal Core to find the latest download.
Enable the following modules: REST, Serialization, HAL, and HTTP Basic Authentication.
By default, the REST module enables the node entity resource for all GET, POST, PATCH, and DELETE operations. It supports basic or cookie authentication and the HAL or JSON formats. You can see these default settings in sites/default/files/config_XXXX/active/rest.settings.yml. To enable REST on other entities (e.g. users, files, or fields), you'll need to edit this file. There is, however, a handy contributed module created by our very own Juampy named REST UI. This module provides a user interface for enabling and disabling resources, serialization formats, and authentication providers. See the screenshot below for an example of the configuration options REST UI provides.
Let me take this opportunity to explain the available resource options, GET, POST, PATCH, and DELETE. These are all common HTTP methods. Each operation signifies a type of action to be performed on a resource. For example, your browser used GET when you requested to view this blog post. To read a resource, we GET. To create a resource, we POST. To update a resource, we PATCH. And to delete a resource, we DELETE. Read this post if you're wondering why we use PATCH and not PUT.
Now back to our setup. For all enabled resources, the REST module can set user permissions. Go to admin/people/permissions and set up your permissions, as required. Here is an example of how I set mine:
You should create also a new authenticated user for testing purposes. If you test your API with User 1 administrator account credentials, you will likely miss permission settings that you need to be set.
Using the REST API
Now we're ready to start using our REST API. I recommend the Dev HTTP Client Chrome extension for testing calls to any API. You can also write scripts in Guzzle, which is a great new tool included in Drupal 8 Core or cURL via the command line or PHP.
Start by creating a node entity. To do this, we must send a POST to /entity/node with the Content-Type header set to application/hal+json and declare the required type and title fields in the request BODY. But don't forget that because we are using Basic Auth, we need to set the headers PHP_AUTH_USER and PHP_AUTH_PW to authenticate as our user. Here is how it looks in the Dev HTTP Client:
Or, if you prefer, you can try cURL from the command line:
You'll notice the request is returning 403 Forbidden. It's important to remember that although you have given authenticated users permission to Access POST on Content resource they still need permission to perform the underlying action which, in this case, is creating a new page node. So head back to the permissions page and make sure authenticated users have at least the Page: Create new content, Page: Edit own content and Page: Delete own content permissions.
Another recent addition is the requirement of a CSRF token that needs to be sent along with your POST request. You can get this token by making a GET request to rest/session/token. It's also worth noting that this token is user specific, so any nodes created by POST requests with this token will be authored by the user associated with this token.
Try again, adding an additional X-CSRF-Token header with your token, and you'll now get a nice green
201 Created response. Congratulations! You just created a node entirely via your new REST API!
You can now GET the node we just created. Send a GET to /node/<nid>?_format=hal+json and you should receive a
200 OK with the BODY containing a HAL representation of the entire node entity. For a simpler JSON representation, set the
_format query parameter to
json and compare the results.
You should now have a general understanding of REST in Drupal 8 and the basics behind manipulating single Drupal entities via the REST API. We only used POST and GET, but PATCH and DELETE work similarly. Feel free to try them in your own time!
I hope to write more posts about REST in Drupal 8 on topics such as setting custom entity field values and retrieving lists of entities using Views. I'd like to look also into setting up more secure REST API authentication using modules such as OAuth.
Update: My blog post on RESTful Views in Drupal 8 has been released.
Please leave your comments and queries below and we'll do our best to answer what we can!
- REST and Serialization in Drupal 8 - DrupalCon Prague 2013 presentation by Lin Clark and Klaus Purer.
- The future is a RESTful Drupal—A blog post discussing RESTful Web Services in Core by Dries Buytaert.
- REST API Tutorial—A useful introduction to REST for beginners.
- Announcing the Web Services and Context Core Initiative— The initial announcement of the Web Services Core Initiative.
- The Serializier Component—Documentation on the Symfony 2 component which a lot of REST in Drupal 8 Core is based upon.
Web Mapping in Drupal, GIS Applications
What is GIS and why is it important for Drupal?
A geographic information system (GIS) is a system designed to capture, store, manipulate, analyze, manage, and present all types of spatial or geographical data. A GIS lets us visualize, question, analyze, and interpret data to understand relationships, patterns, and trends <<read more about GIS from ESRI>>
Drupal has a diverse user group which spans from small businesses and organizations to global organizations. These users use Drupal for news publishing, education, emergency relief, information dissemination, discussion forums, etc. An increasing trend in websites today is providing strong visualization mediums in order to capture the attention of users and present information to users in an easy to understand manner. GIS does this effortlessly as maps present information in ways that are inherent to users. Most of the large organizations that use Drupal also have separate GIS systems which are mostly Desktop based; however current trends show increased adoption of web based GIS systems, this is where the importance of GIS to Drupal or vice versa comes in. In this blog we look at the use of GIS tools in Drupal, the focus is kept on the current tools and future direction of GIS adoption in Drupal. This discussion is under 3 main themes:
1. Early GIS tools in DrupalEarly GIS tools in Drupal involved a concept known as 'dots on a map'. The early map plugins on Drupal focused on simple map tasks as providing location in a form of geocoding and address fields, some of these early plugins include: location, and Geofield. The Geofield module for instance supported storage of all geographic data such as points, lines and polygons. It provided users with multiple widgets for data input supporting latitude and longitude, bounding box, Well Known Text (WKT). In the past it was mainly used for storing longitude and latitude information to display points and addresses in a simple map, however the beauty of Drupal and Open source for that matter is its ever evolving nature. Geofield like most of the early mapping modules has evolved to become a much more dynamic and powerful Drupal mapping module. It now has full integration with more current and widely used modules such as OpenLayers and Leaflet; these modules are further elaborated in later paragraphs. A key component that has strengthened the GIS in Drupal has been the GeoPHP library; an open source PHP library for geometric operations. Drupal is written in the PHP programming language, hence the creation of a custom GeoPHP module for Drupal enabled all the benefits this library has to offer available to other Drupal mapping modules. This is one of the bases of the current Drupal GIS trends which involve a combination of modules like Geofield, OpenLayers, Leaflet, Views GeoJSON and PostGIS.
2. Current trendsCurrent trends in Drupal mapping revolves around two main modules mentioned earlier; the OpenLayers module and Leaflet module. These modules have become the most popular Drupal mapping modules for complex display and interactivity. The OpenLayers module brings all the features of the open source JS OpenLayers library into Drupal; it provides an API for building rich web-based geographical applications. The Leaflet module which is quite similar to OpenLayers is also an incorporation of the Leaflet JS library in Drupal; it is the module of choice for mobile friendly interactive maps and despite being lightweight it still provides all the powerful web map features that bigger libraries / applications provide. As was mentioned early there is good compatibility between most of the mapping modules as well as their dependency on other widely used non-mapping Drupal modules. A current approach is to use the Geofield and its related modules for gathering and storing the geographic data, and then the OpenLayers and Leaflet modules are used for presenting the data in interactive mediums.
Gin Drupal 2An area which hasn’t been fully explored is modules that allow processing of geographical data mostly on the Server side; however there are some powerful modules like Cartaro and the GeoServer modules that take advantage of the benefits GeoServer and PostGIS provide, enabling better processing of geospatial data. This aspect makes mapping in Drupal look really promising as they provide solutions to some of the challenges faced with processing geospatial data which is better handled on the server-side.
GIS modules in Drupal continue to increase as more people become aware of the numerous benefits maps and GIS applications provide. There are currently stable modules in Drupal that enable gathering, storage, processing and display of geospatial data; improvements in these modules allows one to take advantage of all the benefits the Drupal CMS provides as well. GIS data can be large and require a lot of computer processing, which is a challenging area for using Drupal and a CMS for GIS processing in general. However the integration of Drupal with GeoServer and PostGIS and the respective modules getting better, this situation is improving and the future is bright for a comprehensive Drupal mapping system that combines all the best geospatial modules.
In summary, mapping in Drupal consists of modules that address specific GIS areas. Geofield module is the best for gathering and storing data, PostGIS and GeoServer modules provides integration with the respective program for better processing, and OpenLayers and Leaflet modules are the best for data display as well as interactivity. The Cartaro module is a Drupal distribution that attempts to harness the strengths of the best Drupal GIS modules into one web mapping platform.
Drupal Gin Toolbar
View the discussion thread.