Routing JSON representation?

Hi folks

Following the cookbook instructions, I created a JSON representation for my /home site. Consuming the JSON data works perfectly by fetching from the /home.json endpoint.

However, I would rather prefer to communicate an endpoint such as https://myserver.com/api/to others instead of https://myserver.com/home.json. Is there any way to route /api/ to /home.json? I tried with routes in config.php but without success.

Thanks for any hints.

Stefan

The api endpoint is reserved by the system. You should be able to use a route named differently that returns home.json.

Thanks @pixelijn I just tried it, but without success. The following route returns the html representation of /home instead of its counterpart /home.json. Any ideas? Or maybe a bug?

return [
'routes' => [
    [
    'pattern' => 'apitest',
    'action'  => function () {
        return page('home.json');
    }
    ]
]

home.json is not a page. Not quite sure how to go about this, let me think. But you might as well return your json directly from the route instead of returning it from a route via a content representation.

Yes, directly within routes works. I thought there is an easier way though :smiley:

There is actually another way:

[
    'pattern' => 'apitest',
    'action'  => function () {
        return page('home')->render([], 'json');
    }
],
2 Likes

Wow, this works perfect. Thanks @texnixe :slight_smile: