More data from single api endpoint

this is my firs time working with cockpit.

im making a word meaning app with option to see its translation is other languages

ok so what im trying to do is, in my collection i have collection called words with these fields

word: hello
meaning: greeting
source: en
target: de
translation: hallo

what i also have is a collection called languages:
langname: english
langcode: en

so what i want to do is when i call the word hello from words collection, i want to include the full language name: english along the single call.

is this possible or i must make 2 separate calls each time and connect them up on my front end.

thanks.

I’m new and curious about this as well. :thinking:

I’d suggest to adjust your collection words and make the source field of type “Collection-Link” and then “link” the related language entry from your language collection.

This automatically returns later the full entry for your word with the sub-entry of your language.

you can create custom api endpoints in which you can use the cockpit api in order to generate your own data to be returned by the api. This way you are able to combine different collections into one single api call result.

I will give you an concrete example:

To make this example work you need three collections (‘job_locations’, ‘jobs’, ‘job_categories’).

Create a file named “jobs.php" withunder /<cockpit-install-dir>/config/api (so /<cockpit-install-dir>/config/api/jobs.php) with this content:

<?php
 
$data = [];
 
foreach (['job_locations', 'jobs', 'job_categories'] as $collection_name) {
    $data[$collection_name] = cockpit('collections')->find($collection_name, [
        'filter' => function($doc) { // make only published entries being used
            return $doc['published'];
        },
        'sort' => [
            '_o' => 1
        ]
    ]);
}
 
return $data;

Now you can fetch your data using this URL: https://your-cp-installati.on/api/jobs?token=<CUSTOM_API_ENDPOINT_TOKEN_HERE/ADMIN_API_TOKEN/>

The result will contain all entries of all three collections keyed by the collection they are contained in.

1 Like