Extending Craft's Element API with Custom Serializers

The Element API plugin is a very powerful tool that you can use for quickly exposing your data structures to an external source.

Let us make things easier!

What is the Element API?

CraftCMS Element API is a very powerful tool that you can use for quickly exposing your data structures to an external source. This could be the front end of your system, a mobile application or a feed for other applications to consume. Out of the box you are pretty limited in the types of data you can return, but we’re going to explore a use case for a custom serializer and why it’s such a powerful concept.

This article assumes you have a base knowledge of using craft’s element api, and are comfortable writing your own craft plugin.

Element API is built using Fractal (https://fractal.thephpleague.com/) an elegant open source component library for rendering elegant JSON structures, Craft comes with a few different options out of the box: 'array', 'dataArray', 'jsonApi', 'jsonFeed', or a custom serializer. If you are reading this article – I’m assuming you have decided that the only option available for your needs is a custom serializer instance so let’s get into it!

Let’s assume that we have a list of items available, but you have a custom field built, let’s call it a “likesField” which gets queried during runtime, and isn’t stored in a database table. Here’s what that likesField query might look like:


/**
 * likesField.php in your custom plugin
 *
 */
public function normalizeValue($value, ElementInterface $element = null)
  {
    return (int) Entry::find()->section(‘likes’)->relatedTo($element)->count();
  }

What the function presented above is saying is “Give me all of the likes associated with this specific element”. There are numerous reasons for not wanting to store this number in the database, but have it be easily accessible as part of the object instead of doing that query with twig.

OK so now that we have our fictional likesField, suppose we want to order our elementAPI query based on the number of likes? Well, because this number isn’t stored in the database – it’s basically impossible out of the box to make that adjustment. Enter our custom serializer!


/**
 * Serializer for JSON Feed: Version 1
 *
 */
class LikesSerializer extends ArraySerializer
{
  /**
   * @inheritdoc
   */
  public function collection($resourceKey, array $data)
  {
    $likes = [];
    foreach($data as $entry)
    {
      $likes[] = $entry['likes'];
    }
    array_multisort($likes, SORT_DESC, $data);
   return ['data' => $data];
  }
}

So above, we can actually push the values into an array, sort that array and then display our query by the likes field! How cool is that? You can easily see that while this example is simple in premise - by being able to manipulate and control our response with a serializer how powerful of a tool this can be for any project.

If you’d like to know more, don’t hesitate to reach out to us at here: [email protected]

Continue reading.

Why We Love Craft CMS

Here at Brilliance, we LOVE CraftCMS. Our clients love it as well.

Find out more
Ethereum Development Community Nears Merge Date for Proof of Stake

A brief introduction to consensus mechanisms and why proof of stake is the right move for Ethereum.

Find out more
The Best Alternative to WordPress

WordPress has its place, but for larger, more complex projects it should be avoided. We will show how Craft CMS is an overall better solution for your website needs.

Find out more
See all posts

Let's chat about your project

6118 SE Belmont St Ste 404
Portland, OR 97215

This site is protected by reCaptcha and its Privacy Policy and Terms of Service apply.

Contact image