Deliver only application/json in V3

#1

in the past I have used Kirby very much as a pure API. This means that there were no normal PHP pages. Just a function that JSON publishes. But because I didn’t like the .json in the URL, I didn’t use this function either. That means a home.php just delivered json.

Now I ported to version3, added by reinstalling everything. And my old approach doesn’t really work anymore.

I always get an answer with the type document. Setting the headers doesn’t help either.

0 Likes

Generate RSS feed from my website content
#2

If all else fails, you could return the home page/whatever your have there from a route, e.g.

'routes' => [
        [
            'pattern' => '/',
            'action' => function() {
                return Response::json(json_encode(page('home')->toArray()));
            }
        ]
    ]
0 Likes

#3

In Kirby 3, you can set the response type like this in your templates:

<?php

$kirby->response()->json();
echo json_encode(['your' => 'data']);

You can also set other types like this by extension or MIME type:

<?php

$kirby->response()->type('txt');
$kirby->response()->type('text/plain');

It looks like we haven’t documented this anywhere yet. Or have I overlooked it, @texnixe?

0 Likes

#4

No, I don’t think so, I was missing it yesterday as well, but would have expected that if I return a Response::json() or a new Response() with application/json from a template, that I’d get the correct headers as well.

0 Likes

#5

There’s an idea issue about that here.

0 Likes

#6

Ah, thanks, @lukasbestle.

0 Likes