craftcms / element-api

Create a JSON API/Feed for your elements in Craft.
MIT License
499 stars 57 forks source link

Multilanguage support? #33

Closed davorpeic closed 7 years ago

davorpeic commented 7 years ago

Hi,

is it possible to send language in the request? Example I have mobile app that talks with element-api and user (not logged in) would be able to choose the language that he wants to see.

thanks

davorpeic commented 7 years ago

Ok, so I've been playing a little bit with awesome new feature Sites and languages. My idea is to be able to get content from mobile app by sending language handle and be able to also get content from different sites.

This is how I did it, not sure if it is the correct way, but it works

I have one site with two languages

sites_-_craft3_test

<?php

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

return [
    'endpoints' => [
        'api/news.json' => function() {

            $langHandle = Craft::$app->request->getQueryParam('lang', 'site1_en');

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

and requests looks like this /api/news.json?lang=site1_es

brandonkelly commented 7 years ago

Yep, that's how to do it!