# Translations management API

> For the complete documentation index, see [llms.txt](https://doc.ibexa.co/en/6.0/llms.txt).

Use the PHP API, REST API, and console commands to translate content, work with bulk translation jobs, read translation analytics, and maintain translation data.

Editions: LTS Update

Translations management offers the following ways to work with translations outside the back office:

- [PHP API](#php-api) - find content that misses a translation, work with bulk translation jobs and review statuses, and read translation analytics
- [REST API](#rest-api) - do everything that the **Translations** screen of Translations hub does, including starting bulk translation jobs
- [console commands](#console-commands) - translate single content items and maintain translation data

## PHP API

The PHP API services of Translations hub let you build your own reports or automate the review of bulk translation jobs:

- [`ContentDiscoveryServiceInterface`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-BulkTranslations-ContentDiscoveryServiceInterface.html) finds content items that miss a translation
- [`JobServiceInterface`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-BulkTranslations-JobServiceInterface.html) reads bulk translation jobs and their items, and reviews, retries, and removes them
- [`ReviewItemServiceInterface`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-ReviewQueue-ReviewItemServiceInterface.html) lists machine translations by review status, both from bulk translation jobs and from individual translations
- [`TranslationCoverageProviderInterface`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-Analytics-TranslationCoverageProviderInterface.html), [`TranslationBacklogProviderInterface`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-Analytics-TranslationBacklogProviderInterface.html), and [`TranslationStaleOwnersProviderInterface`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-Analytics-TranslationStaleOwnersProviderInterface.html) return translation analytics

All of them respect the permissions of the current user. For more information, see [Translations hub permissions](https://doc.ibexa.co/projects/userguide/en/6.0/translations/translations_hub/#permissions).

To start bulk translation jobs, use the [REST API](#rest-api).

### Find content that misses translation

[`ContentDiscoveryServiceInterface::findMissingTranslations()`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-BulkTranslations-ContentDiscoveryServiceInterface.html#method_findMissingTranslations) returns the content items that don't have a published version in the target language, and that the current user can translate into it. Like the **Missing** tab, it searches the content structure and leaves out products.

Pass a [`ContentDiscoveryQuery`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-BulkTranslations-ContentDiscoveryQuery.html) with the target language code. You can also filter the results by content type identifier and by a search phrase, and set sorting and pagination. The method returns a `SearchResult` with `Content` objects.

### Read translation analytics

The analytics providers return the data that the **Analytics** screen of Translations hub shows. Without a [`SubtreeCriterion`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-Analytics-Query-Criterion-SubtreeCriterion.html), they cover the whole content structure, and they count only the content items that the current user can read.

| Provider                                                         | Query                                                                                                                                                                                      | Returns                                                                                                                                                                                                      |
| ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `TranslationCoverageProviderInterface::getTranslationCoverage()` | [`TranslationCoverageQuery`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-Analytics-Query-TranslationCoverageQuery.html)       | For each language, the number of content items that are translated, missing, or outdated, the coverage ratio, and the average number of times the source was published again after the outdated translations |
| `TranslationBacklogProviderInterface::getTranslationBacklog()`   | [`TranslationBacklogQuery`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-Analytics-Query-TranslationBacklogQuery.html)         | Content items that need a new translation or an update of an outdated one                                                                                                                                    |
| `TranslationStaleOwnersProviderInterface::getStaleOwnerIds()`    | [`TranslationStaleOwnersQuery`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-Analytics-Query-TranslationStaleOwnersQuery.html) | IDs of the owners of content items with an outdated translation                                                                                                                                              |

You can narrow the results with criteria from the `Ibexa\Contracts\TranslationsManagement\Analytics\Query\Criterion` namespace, for example, by subtree, content type, or publication date. Not every provider supports every criterion: an unsupported criterion results in an `UnsupportedCriterionException`.

The following example prints the translation coverage of a language and the first content items that miss a translation into it:

```php
<?php

declare(strict_types=1);

namespace App\Command;

use Ibexa\Contracts\Core\Repository\PermissionResolver;
use Ibexa\Contracts\Core\Repository\UserService;
use Ibexa\Contracts\Core\Repository\Values\Content\Content;
use Ibexa\Contracts\TranslationsManagement\Analytics\Query\TranslationCoverageQuery;
use Ibexa\Contracts\TranslationsManagement\Analytics\TranslationCoverageProviderInterface;
use Ibexa\Contracts\TranslationsManagement\BulkTranslations\ContentDiscoveryQuery;
use Ibexa\Contracts\TranslationsManagement\BulkTranslations\ContentDiscoveryServiceInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(
    name: 'doc:translations_hub:overview'
)]
final class TranslationsHubOverviewCommand extends Command
{
    public function __construct(
        private readonly TranslationCoverageProviderInterface $coverageProvider,
        private readonly ContentDiscoveryServiceInterface $contentDiscoveryService,
        private readonly PermissionResolver $permissionResolver,
        private readonly UserService $userService
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('languageCode', InputArgument::REQUIRED, 'Target language code, for example ger-DE')
            ->addArgument('user', InputArgument::OPTIONAL, 'Login of the user to check the content as', 'admin');
    }

    #[\Override]
    protected function execute(
        InputInterface $input,
        OutputInterface $output
    ): int {
        $user = $this->userService->loadUserByLogin((string) $input->getArgument('user'));
        $this->permissionResolver->setCurrentUserReference($user);

        $languageCode = (string) $input->getArgument('languageCode');

        $coverageList = $this->coverageProvider->getTranslationCoverage(
            new TranslationCoverageQuery(languageCodes: [$languageCode])
        );
        $coverage = $coverageList->getForLanguage($languageCode);
        if ($coverage !== null) {
            $output->writeln(sprintf(
                '%s: %d of %d content items translated (%.1f%%), %d missing, %d outdated',
                $coverage->languageCode,
                $coverage->translatedItems,
                $coverage->targetItems,
                $coverage->coverageRatio * 100,
                $coverage->missingItems,
                $coverage->staleItems
            ));
        }

        $missingTranslations = $this->contentDiscoveryService->findMissingTranslations(
            new ContentDiscoveryQuery(targetLanguageCode: $languageCode, limit: 10)
        );
        $output->writeln(sprintf('Content items without a %s translation: %d', $languageCode, $missingTranslations->totalCount));
        foreach ($missingTranslations->searchHits as $searchHit) {
            $content = $searchHit->valueObject;
            if ($content instanceof Content) {
                $output->writeln(sprintf('- %s (ID %d)', $content->getName(), $content->getId()));
            }
        }

        return self::SUCCESS;
    }
}
```

### Work with bulk translation jobs

[`JobServiceInterface`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-BulkTranslations-JobServiceInterface.html) gives access to the jobs listed in the **History** tab of Translations hub:

- `findBulkTranslationJobs()` and `countBulkTranslationJobs()` find jobs by status, target language, creator, or title, by using a [`JobQuery`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-BulkTranslations-Values-JobQuery.html)
- `getBulkTranslationJob()` loads a job by its ID
- `findJobItems()` lists the items of a job, optionally filtered by item status, review status, target language, or content type, by using a [`JobItemQuery`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-BulkTranslations-Values-JobItemQuery.html)
- `reviewBulkTranslationJobItems()` approves or rejects the translations of many job items at once
- `retryBulkTranslationJob()` translates the failed items of a finished job again
- `retranslateJobItem()` translates a single item of a finished job again, and removes its previous draft
- `removeBulkTranslationJob()` removes a job together with the drafts that it created, or cancels it first if it's pending or in progress

Retrying, translating again, and removing happen in the [background](https://doc.ibexa.co/en/6.0/translations_management/configure_translations_management/#process-bulk-translation-jobs-in-background).

The following example lists the jobs that wait for review or failed, together with their failed items, and can retry the failed items or approve all translations of a job:

```php
<?php

declare(strict_types=1);

namespace App\Command;

use Ibexa\Contracts\Core\Repository\PermissionResolver;
use Ibexa\Contracts\Core\Repository\UserService;
use Ibexa\Contracts\TranslationsManagement\AutoTranslate\AutoTranslationReviewOperation;
use Ibexa\Contracts\TranslationsManagement\AutoTranslate\AutoTranslationReviewStatus;
use Ibexa\Contracts\TranslationsManagement\BulkTranslations\JobServiceInterface;
use Ibexa\Contracts\TranslationsManagement\BulkTranslations\Values\JobItem;
use Ibexa\Contracts\TranslationsManagement\BulkTranslations\Values\JobItemQuery;
use Ibexa\Contracts\TranslationsManagement\BulkTranslations\Values\JobItemStatus;
use Ibexa\Contracts\TranslationsManagement\BulkTranslations\Values\JobQuery;
use Ibexa\Contracts\TranslationsManagement\BulkTranslations\Values\JobStatus;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(
    name: 'doc:translations_hub:jobs'
)]
final class BulkTranslationJobsCommand extends Command
{
    public function __construct(
        private readonly JobServiceInterface $jobService,
        private readonly PermissionResolver $permissionResolver,
        private readonly UserService $userService
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('user', InputArgument::OPTIONAL, 'Login of the user to act as', 'admin')
            ->addOption('retry', null, InputOption::VALUE_NONE, 'Retry the failed items of finished jobs')
            ->addOption('approve', null, InputOption::VALUE_REQUIRED, 'ID of a job whose translations to approve');
    }

    #[\Override]
    protected function execute(
        InputInterface $input,
        OutputInterface $output
    ): int {
        $user = $this->userService->loadUserByLogin((string) $input->getArgument('user'));
        $this->permissionResolver->setCurrentUserReference($user);

        $jobs = $this->jobService->findBulkTranslationJobs(new JobQuery(
            limit: 10,
            statuses: [JobStatus::STATUS_FOR_REVIEW, JobStatus::STATUS_FAILED]
        ));
        $output->writeln(sprintf('Jobs waiting for review or failed: %d', $jobs->totalCount));

        foreach ($jobs as $job) {
            $output->writeln(sprintf(
                '#%d %s (%s): %d of %d items translated, %d failed',
                $job->id,
                $job->title ?? 'Untitled',
                implode(', ', $job->targetLanguageCodes),
                $job->successfulItems,
                $job->totalItems,
                $job->failedItems
            ));

            $failedItems = $this->jobService->findJobItems(
                new JobItemQuery(jobId: $job->id, status: JobItemStatus::STATUS_FAILED)
            );
            foreach ($failedItems as $failedItem) {
                $output->writeln(sprintf('  Failed: %s (content ID %d)', $failedItem->contentName, $failedItem->contentId));
            }

            if ($input->getOption('retry') && $job->isRetryable()) {
                $this->jobService->retryBulkTranslationJob($job->id);
                $output->writeln('  Failed items queued for another translation attempt.');
            }
        }

        $jobToApprove = $input->getOption('approve');
        if ($jobToApprove !== null) {
            $itemsForReview = $this->jobService->findJobItems(new JobItemQuery(
                jobId: (int) $jobToApprove,
                limit: 100,
                reviewStatus: AutoTranslationReviewStatus::STATUS_FOR_REVIEW
            ));
            $jobItemIds = array_map(
                static fn (JobItem $jobItem): int => $jobItem->id,
                $itemsForReview->items
            );

            if ($jobItemIds !== []) {
                $this->jobService->reviewBulkTranslationJobItems(
                    $jobItemIds,
                    AutoTranslationReviewOperation::OPERATION_APPROVED
                );
            }
            $output->writeln(sprintf('Approved translations: %d', count($jobItemIds)));
        }

        return self::SUCCESS;
    }
}
```

### Find translations by review status

[`ReviewItemServiceInterface::findReviewItems()`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-ReviewQueue-ReviewItemServiceInterface.html#method_findReviewItems) returns machine translations, like the **For review** and **Translated** tabs do. Unlike `JobServiceInterface::findJobItems()`, it includes translations that editors created one by one, outside of bulk translation jobs.

Pass a [`ReviewItemQuery`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-ReviewQueue-Values-ReviewItemQuery.html) with criteria from the `Ibexa\Contracts\TranslationsManagement\ReviewQueue\Values\Criterion` namespace, for example `ReviewStatusCriterion`, `TargetLanguageCriterion`, `JobIdCriterion`, or `ProviderCriterion`, and combine them with `LogicalAnd` and `LogicalOr`. Each returned [`ReviewItem`](https://doc.ibexa.co/en/6.0/api/php_api/php_api_reference/classes/Ibexa-Contracts-TranslationsManagement-ReviewQueue-Values-ReviewItem.html) contains the content ID, version number, languages, provider, review status, and, for translations from a bulk translation job, the job context.

## REST API

The REST API of Translations hub covers everything that the **Translations** screen does, including starting bulk translation jobs. Its endpoints are available under `/api/ibexa/translations-hub/bulk-translation/`:

| Method   | Endpoint                      | Description                                                                        |
| -------- | ----------------------------- | ---------------------------------------------------------------------------------- |
| `GET`    | `/missing`                    | List content items that miss a translation                                         |
| `GET`    | `/missing/ids`                | List the IDs of content items that miss a translation, for selecting them in a job |
| `GET`    | `/missing/filters`            | List the filter choices of the missing translations list                           |
| `GET`    | `/outdated`                   | List outdated translations                                                         |
| `GET`    | `/outdated/filters`           | List the filter choices of the outdated translations list                          |
| `POST`   | `/setup`                      | Preview a bulk translation job for the selected content items, without creating it |
| `POST`   | `/start`                      | Start a bulk translation job                                                       |
| `GET`    | `/history`                    | List bulk translation jobs                                                         |
| `GET`    | `/history/filters`            | List the filter choices of the job list                                            |
| `GET`    | `/job/{id}`                   | Get the summary of a job                                                           |
| `GET`    | `/job/{id}/items`             | List the items of a job                                                            |
| `POST`   | `/job/{id}/retry`             | Retry the failed items of a job                                                    |
| `DELETE` | `/job/{id}`                   | Remove a job                                                                       |
| `POST`   | `/job-items/{id}/retranslate` | Translate a single job item again                                                  |
| `POST`   | `/job-items/bulk-review`      | Approve or reject the translations of many job items                               |
| `GET`    | `/for-review`                 | List translations that wait for review                                             |
| `GET`    | `/for-review/filters`         | List the filter choices of the review list                                         |
| `GET`    | `/translated`                 | List accepted translations that aren't published yet                               |
| `GET`    | `/translated/filters`         | List the filter choices of the accepted translations list                          |
| `POST`   | `/translated/bulk-delete`     | Delete the drafts of many accepted translations                                    |

To start a job, send the IDs of the content items, the source language, the target languages, and the provider identifier, for example:

```bash
curl -X POST https://example.com/api/ibexa/translations-hub/bulk-translation/start \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json' \
    -d '{"contentIds": [57, 58, 59], "sourceLanguage": "eng-GB", "targetLanguages": ["ger-DE"], "provider": "deepl", "title": "German launch", "includeExistingTranslations": false}'
```

If no enabled translation provider supports the language pair, omit `provider` or set it to `null`. The job then creates empty drafts in the target languages, with the "For review" status, for editors to translate.

The response says whether a job was started, its ID, and how many content items were accepted or skipped. The job leaves out content items that don't exist, products, and content items that the user can't translate, and, unless `includeExistingTranslations` is `true`, content items that already have all the target translations. One job can contain at most 500 translations, counted as content items multiplied by target languages. If a job for one of the target languages is already pending or in progress, the request fails with the `409 Conflict` status.

These endpoints use the same [authentication](https://doc.ibexa.co/en/6.0/api/rest_api/rest_api_authentication/index.md) as the rest of the REST API. With session authentication, requests that change data must contain the `X-CSRF-Token` header.

The [REST API reference](https://doc.ibexa.co/en/6.0/api/rest_api/rest_api_reference/rest_api_reference.html) doesn't list these endpoints. To get their full OpenAPI description, with request and response schemas, export it from your project:

```bash
php bin/console api:openapi:export --output=openapi.json
```

## Console commands

### Translate content items

For the purposes of batch processing, automation, and other scripted actions, the [Translations management](https://doc.ibexa.co/en/6.0/translations_management/translations_management_guide/index.md) package exposes a command that automatically translates content items or products by using any of the configured providers:

```bash
php bin/console ibexa:translations:auto-translate-content \
    --content-id=42 \
    --provider=deepl \
    --from=eng-GB \
    --to=fre-FR
```

> **Tip: Command alias**
>
> You can use `ibexa:translations:translate-content` as an alias.

The command uses the same provider configuration and field value transformers as the UI. Therefore, depending on the specific command options used, the result can be the same as if an editor [triggered the automated translation manually](https://doc.ibexa.co/projects/userguide/en/6.0/translations/translate_content/#add-translations).

Without the `--draft-only` option, the translation generated with a CLI command is instantly published, while a manual one requires that a human publishes it.

#### Command options

| Option         | Required | Description                                                                                |
| -------------- | -------- | ------------------------------------------------------------------------------------------ |
| `--content-id` | Yes      | ID of the content item or product to translate                                             |
| `--provider`   | Yes      | Identifier of the translation provider to use                                              |
| `--from`       | Yes      | Source language code                                                                       |
| `--to`         | Yes      | Target language code                                                                       |
| `--user-id`    | No       | Repository user ID to run the translation (default: `14`, which is the Administrator user) |
| `--draft-only` | No       | Create a translated draft without publishing it                                            |

### Purge translation attempts

Cohesivo records every attempt to translate a content item with a translation provider, including attempts that failed. Provider statistics in analytics use these records to calculate how often requests to each provider fail.

To remove attempts older than a specific number of days, run the `ibexa:translations:purge-translation-attempts` command. By default, it removes attempts older than 365 days. First, list the attempts that the command would remove:

```bash
php bin/console ibexa:translations:purge-translation-attempts --older-than=180 --dry-run
```

Then, remove them:

```bash
php bin/console ibexa:translations:purge-translation-attempts --older-than=180 --force
```

Without `--dry-run` or `--force`, the command doesn't remove anything. After a purge, provider statistics no longer include the removed attempts.

### Reset stuck removals

When a user deletes a bulk translation job, or deletes drafts in the **Translated** tab, the job or the drafts disappear from the list while the worker removes them in the background. If the removal doesn't finish, for example because the message was lost, you can list them again so that users can repeat the action:

- To list bulk translation jobs in the **History** tab again, run `ibexa:translations:reset-pending-job-removals` with job IDs, or with the `--all` option:

  ```bash
  php bin/console ibexa:translations:reset-pending-job-removals 12 15
  ```

- To list translations in the **Translated** tab again, run `ibexa:translations:reset-pending-draft-removals` with the IDs of auto-translation records, or with the `--all` option:

  ```bash
  php bin/console ibexa:translations:reset-pending-draft-removals --all
  ```
