I need to return two types of entry to an external service, and am trying to do so in one endpoint.

I am able to return all of the instances of each type, but it returns an array of mixed types.

"api/myEndpoint" => function() {
        return [
            "criteria" => [
                "type" => ["typeOne", "typeTwo"],
            "transformer" => new MyTransformer()

I'm trying to achieve: { "data": { "typeOne": [{...}, {...}], "typeTwo": [{...}, {...}]}}

I can think of various workarounds for this specific case. It would be easy enough to add a type field within the Transformer, and sort them on the other side. Or, simply make two calls. However, our team was planning on using Craft as a headless CMS for future projects, and it's important to me be able to control the structure of Element API's JSON response.

  • 1
    dont suppose you ever got to the bottom of this one did you? having the same problem.
    – BillyMedia
    Commented Jan 9, 2018 at 17:24

1 Answer 1


I'm using Craft as a headless CMS, so I wanted full control over the JSON it was returning. I didn't figure out how to do this with Element API, but it's very simple to write your own plugin that turns entries into JSON. Craft already includes the code to look up entries, so it's easy.

A basic controller might look something like:

class MyCustomPlugin_SomeResourceController {

    public function actionWidgets() {
        $criteria = craft()->elements->getCriteria(ElementType::Entry);
        $widgetEntries = $criteria->section("resources")->type("widget")->find();

        // map entries to PHP objects
        $widgetObjects = array_map(function($entry) {
            return [
                "name" => $entry->title
        }, $widgetEntries);

            "widgets" => $widgetObjects,
            "anotherThing" => "somethingElse"


In the actual app, I'm combining several different types of entries into one endpoint, so I extracted the reading and formatting into services, which I combine in various controller actions.

Presumably, Element API has some other features that I'm missing out on, but I haven't noticed.

  • yeah, i gave up trying to find a solution and ended up creating my own plugin.
    – BillyMedia
    Commented Jan 11, 2018 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.