Simplyfing Restful API

There are a couple of key things I consider when building a project that will include a robust API is the entities I will need to interact with and play a key role in my application.  Often times this is Nodes, Users, Products, and a couple of custom entities as needed.

Once I have my list I thing decide the fields that are needed and set about simplifying how I will interact with them.  For this, I leverage Drupal 8 and Symfony2's Serialization API.

Talking to the Wind - Creating a custom Normalization Class

For the first step, I create a Normalization class that allows me to take a Drupal 8 Entity and create a JSON object that can be easily consumed.  For this example, I will use a simple Node, but the great thing is you can create multiple Normalizers and use different criteria to decide if they will be used or not.

View on Gist

The great thing about this is you get total control over how your RestFUL API so you can continue to use the built-in endpoints for nodes or create new ones and this normalizer will be used when it returns TRUE for the supportsNormalization() method.

Listening to the WInd - Creating a custom Denormalizer Class

I know what you're thinking now, that its all well and good to be able to clean up that RestFUL API Endpoint's output, but how about reacting to updates from your headless application.  Nobody wants there js to have sections of code just trying to update individual values or properties.  This is where Denormalizers come in.  It is the same principle but in reverse.  So with Normalizers you are taking an entity and turning it into an array that is then rendered as JSON, CSV, XML, etc.  Denormalizers will take the JSON, CSV, or XML datasets and convert them into Drupal friendly entities.

View on Gist

Now that we have the Normalizer and Denormalizer scripts setup we can decide how we want to build out endpoints.  We can use the built-in ones or create custom endpoints.  In these custom endpoints, you can decide the url path that will be called in order to access the data. These will be created as Plugins and then can be accessed from clients.  

I will go over when to use the Restful API versus creating Controllers to help with managing content.  Another great thing about using Normalizers is they can also be accessed from your custom controllers.  So stay tuned for more details on simplifying your Decoupled Drupal workflow.

Useful References:

Have You any questions?