In this series of tutorials, we will go through the process of creating a cross-platform mobile app using a headless Drupal 8 backend with a REST API. The app will have native UI and navigation, ie, on iOS it will look and feel like a native iOS app, same for android. Various steps use *nix or OSX command-line instructions.
Enable the necessary modules: views, views_ui, jdrupal, restui, restful webservices, serialization.
drush en jdrupal -y; drush en restui -y;
The dependencies will be installed along with the above.
To configure REST, go to /admin/config/services/rest and ensure the appropriate endpoints are configured as such:
We will be authenticating our app via cookies.
Configure user permissions:
In order for the backend and external frontend to be able to share cookies which sit on different sub-domains, we need to tell Drupal it's ok to do so.
$settings['trusted_host_patterns'] = array( '^mysite\.local$', '^.+\.mysite\.local$', );
*Important note: Base domain needs at least 1 dot '.' in the domain name or cookies will not work, i found out the hard way!
cp sites/default/default.services.yml sites/default/services.yml
Update Frontpage view:
Our app will contain a simple page listing all published nodes, similar to the default Drupal homepge.
Go to: /admin/structure/views/view/frontpage
Add ‘REST export’ display, give it the path ‘front’. Save.
Add headers to host site.
The Drupal CORS module can be used to aid this, or add the following to services.yml:
cors.config: enabled: true # Specify allowed headers, like 'x-allowed-header'. allowedHeaders: ['Content-Type', 'X-CSRF-Token'] # Specify allowed request methods, specify ['*'] to allow all possible ones. allowedMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'] # Configure requests allowed from specific origins. allowedOrigins: ['*'] # Sets the Access-Control-Expose-Headers header. exposedHeaders: true # Sets the Access-Control-Max-Age header. maxAge: false # Sets the Access-Control-Allow-Credentials header. supportsCredentials: true
To allow cross-domain authentication, you must specify the domains that this site will send cookies to. Wildcards won't work.