Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Building an API with Drupal 8

Karine Chor
February 06, 2018

Building an API with Drupal 8

Drupal 8 is the latest version of Drupal CMS and has been released in 2015.
You might have heard of “headless Drupal” websites… Well, it refers to using Drupal as a backend only to manage contents and creating the frontend part with a different technology.
In this kind of architecture, contents can be provided through an API.

We'll see how to build an API with Drupal and give you some feedback based on our experience.

Karine Chor

February 06, 2018
Tweet

More Decks by Karine Chor

Other Decks in Programming

Transcript

  1. – Building an API with Drupal 8 Karine Chor -

    Webmardi Lausanne, February 6, 2018
  2. What I will cover – General – Use case 1:

    building an API with views – Use case 2: building an API with code – To go further – Conclusion – Questions – Apéro :-) 2
  3. Hello, it’s me! – Multimedia engineer – Web developer –

    Druids team at Liip Fribourg – Drupal 6/7/8 – Mail: [email protected] – Twitter: @karinechor 4
  4. Drupal is... – Content Management System – Open source project

    – Core – 1000’s of modules – Flexible – Latest version: Drupal 8 5
  5. Traditional Drupal website – Backend – Contents handled with the

    administrative interface – Use and creation of modules – Frontend – Drupal theme built from scratch or from a base – Components provided by core:
 Twig templates, jQuery etc. 6
  6. See Drupal group: https://groups.drupal.org/headless-drupal “Headless” Drupal initiative «We want Drupal

    to be the CMS of choice for client-side MVC frameworks.» «We want an API for renderable structure and context-aware template-driven JSON representations of pages.» 7
  7. “Headless” Drupal website – “Decoupled” CMS – Backend – Contents

    handled with the administrative interface – Use and creation of modules – Frontend – Not Drupal ! – Providing contents through an API 8
  8. Use case “views” – Client: Swiss insurance company – Need:

    display some articles on a client portal built with AngularJS – Why Drupal 8 ? – A section of the portal fed by Drupal – Nodes (Articles) – Taxonomies – Search – Project status: on production 10
  9. Drupal modules – Goal: exposing a list of nodes formatted

    as JSON – In core modules (new in Drupal 8): – RESTful Web Services – Serialization – Based on Symfony components (Serializer, HttpFoundation, Routing etc.) – How? Building queries with Views interface 11
  10. REST Export view – Module: Views – In core –

    Building queries through the administration interface – REST Export display – Endpoint: /api/v1/articles – Method: GET 12
  11. Issues – Boolean as a String – Integer as a

    String – Multiple fields as a String – Entity references as a String 17
  12. Custom Serializer – Solution: alter output of a specific row

    – Extend Serializer class – Style plugin for serialized output formats – Provided by Rest module – View format: select your own Serializer 18
  13. Caching – In-core caching system – In-core module: Dynamic Page

    Cache – Cache settings available in the view – None: no cache – Tag: cache invalidated depending on data update – Time-based: cache invalidated depending on a time 21
  14. Alternative solution: Rest Views – Contrib module: https://www.drupal.org/project/rest_views – Solution

    to output – Multiple fields – References nested – Correct type output (bool, number etc.) – No custom code needed – Alpha version 22
  15. Feedback PROS CONS – Easy and fast to set up

    – Features “out of the box” – Views in core – Site building approach – Queries not performant for large and complex data – Limited functionalities – Extended implementation in code VS. views interface setup – Contrib modules not yet stable 23
  16. Use case “code” – Client: Fashion sector – Need: Display

    same contents on a website and on a mobile application – Why Drupal 8? – Handle contents on a single platform (Nodes, Taxonomies etc.) – Traditional website – API provided to feed mobile application contents – Project status: in progress 25
  17. Drupal modules – Goal: exposing a list of nodes formatted

    as JSON – In core modules: – RESTful Web Services – Serialization – Contrib modules: – Drupal console – REST UI (optional) – How? Creating resources in code 26
  18. Creating a Resource – Class ArticleRestResource generated extended from RestResource

    class – Enable Resource command:
 drupal rest:enable – Enable new permission 
 "Access GET on Article REST Resource resource" 
 28
  19. Caching – In-core caching system – In-core module: Dynamic Page

    Cache – Add a cacheable dependency to the response
 – Based on – Tags: setCacheTags() – Context: setCacheContexts() – Time: setCacheMaxAge() 33 // Invalidate cache when content is changed
 $cache_metadata = new CacheableMetadata();
 $cache_metadata->setCacheTags([‘node_list’]);
 $response->addCacheableDependency($cache_metadata);
  20. Feedback PROS CONS – Large amount of data – Control

    of the output – Drupal console integration – Rest API in core – Other methods POST, PATCH etc. – Developer approach – Understanding of Symfony components 35
  21. Authentication – Goal: protecting REST endpoints with an authentication –

    Authentication providers – Cookies (in core) – HTTP Basic Authentication (in core) – OAuth 1.0 (contrib) – etc. – To be specified in – Views: adapt “Path settings authentication” and adjust “access” – Code: adapt resource configuration yaml file and assign permission 
 “Access *** on *** REST Resource resource” to a role 37
  22. Methods with Drupal REST API – Safe methods (read-only) –

    GET – HEAD – OPTIONS – TRACE – Unsafe methods (manipulate stored data), X-CSRF-Token request header required – POST – PATCH – DELETE 38
  23. Entities exposed as RESTful API – See complete list in

    /admin/config/services/rest (restui enabled) – Examples: https://www.drupal.org/docs/8/core/modules/rest/overview 39
  24. GraphQL: an alternative to REST – New API standard –

    A query language for APIs – Invented and open-sourced 
 by Facebook – Enables declarative 
 data fetching 40 Source: https://www.howtographql.com
  25. GraphQL advantages – Single API call / endpoint – Client

    can specify which data it actually needs – Better experience for query building – No versions to maintain 41
  26. GraphQL in Drupal 8 – In-core – Serialization – Typed

    data API – Contrib module – GraphQL (beta version, GraphiQL included) – Github repositories – GraphQL Views – GraphQL Twig To learn more:
 https://www.amazeelabs.com/en/blog/graphql-for-drupal-basics 42
  27. Why using Drupal 8 to build APIs? – Built-in eco-system

    – Content management platform – System of caching – Symfony-based components – API-first – REST API in core – GraphQL integration – Services module 44
  28. Resources – REST – https://events.drupal.org/baltimore2017/sessions/masters-universe-live-coding-react-application-using- drupal-services – http://www.mediacurrent.com/blog/building-rest-endpoints-drupal-8 – https://makina-corpus.com/blog/metier/2017/comment-mettre-en-place-un-site-drupal-headless

    (FR) – https://www.drupal.org/doc s/8/api/restful-web-services-api/restful-web-services-api-overview – https://www.drupal.org/project/drupal/issues/2936209 – http://enzolutions.com/articles/2014/12/16/how-to-create-a-rest-resource-in-drupal-8/ – http://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/ – GraphQL – https://www.howtographql.com/basics/0-introduction/ – https://www.howtographql.com/basics/1-graphql-is-the-better-rest/ – https://philsturgeon.uk/api/2017/01/24/graphql-vs-rest-overview/ – https://www.amazeelabs.com/en/blog/graphql-for-drupal-basics 47