JSON view example from docs gives "Missing Template error"

@Jubbs You should know that the way how content type negotiation works is not only decided by the server but also by the client.

So in the example of the docs you are only adding the possibility of a JSON content type to your controller actions via

public function viewClasses(): array
{
    return [JsonView::class];
}

and

$this->viewBuilder()->setOption('serialize', 'articles');

inside your action.

But this doesn’t mean it is forced to only be JSON, it can still be a simple HTTP request with the default template which returns HTML.

If you want JSON as a response your client should specify it wants JSON via the Accept Header which should be set to application/json

It of course depends on what client you are using, in e.g. jQuery it is the option dataType: 'json',
In Postman you can set additional headers easily like so


and many many more possibilites of course.

You can alternativly add

$routes->setExtensions(['json']);

to your config/routes.php (or plugin routes) to allow JSON routes.
This means, that you can e.g. call your action via

http://localhost/mycontroller/myaction/3.json

instead of

http://localhost/mycontroller/myaction/3

and get a direct JSON response without having the need to manually set the JSON View Class via

$this->viewBuilder()->setClassName("Json");
1 Like