1

I'm trying the Element API for the first time and getting this error message {"error":{"code":404,"message":"Endpoint has an invalid elementType"}}

I cannot for the life of me figure out what I'm missing... I've read the docs, followed the Mijingo "Creating an Element API video", read Andrew Welch's post (https://nystudio107.com/blog/lazy-loading-with-the-element-api-vuejs) and hunted through Stack Exchange but haven't came across any fixes.

This is from my current element-api.php file:

<?php
namespace Craft;

return [
    'endpoints' => [
        'api/news.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'news'],
            'transformer' => function(EntryModel $entry) {
                return [
                    'title' => $entry->title,
                    'body' => (string) $entry->newsText
                ];
            }
        ],
    ]
];

Previously, I tried changing the code slightly to:

<?php

use craft\elements\Entry;
use craft\helpers\UrlHelper;

return [
    'endpoints' => [
        'news.json' => function() {
            return [
                'elementType' => Entry::class,
                'criteria' => ['section' => 'news'],
                'transformer' => function(Entry $entry) {
                    return [
                        'title' => $entry->title,
                        'url' => $entry->url,
                        'jsonUrl' => UrlHelper::url("news/{$entry->id}.json"),
                        'newsTitle' => $entry->newsTitle,
                    ];
                },
            ];
        },
    ]
];

but still no luck. With the second block of code the error message I get is Template not found: api/news.json

Apologies if I'm missing something completely obvious, this is the first time using the plugin, and I don't know PHP, but following along with the Mijingo video helped me understand what was going on.

If anyone has any suggestions to fix this that would be greatly appreciated!

Cheers

1 Answer 1

2

Your second example has the correct elementType value (Entry::class with a corresponding Entry import at the top of the file). Alternatively you could do

'elementType' => 'craft\elements\Entry',

The error you’re getting in that example is because you changed the endpoint to just news.json rather than api/news.json. So the request isn’t getting routed to this endpoint in the first place.

1
  • Spot on. Thanks for much for this Brandon — got it working now (seems like it was because of the api/news.json + news.json error)! Really looking forward to using the plugin more and more.
    – fbnntt
    Commented Jun 16, 2019 at 16:40

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.