api-platform / core

The server component of API Platform: hypermedia and GraphQL APIs in minutes
https://api-platform.com
MIT License
2.39k stars 848 forks source link

Add multi-language OpenAPI specification #5785

Open alebedev80 opened 10 months ago

alebedev80 commented 10 months ago

I need multi-language API documentation. For now possible to generate single language only (which use in resource files). How better to implement it? Build instance of ApiPlatform\OpenApi\OpenApi with already translated field or do translation during normalization in ApiPlatform\OpenApi\Serializer\ApiGatewayNormalizer?

I think better to translate OpenApi instance and propose to implement OpenApiFactoryInterface decorator in follow way:

// OpenApiTranslator.php

<?php

namespace App\Docs\OpenAPI;

use ApiPlatform\OpenApi\OpenApi;

interface OpenApiTranslator
{
    public function translate(OpenApi $openApi, string $lang = 'en'): OpenApi;
}

// OpenApiTranslatorFactory.php
<?php

declare(strict_types=1);

namespace App\Docs\OpenAPI;

use ApiPlatform\OpenApi\Factory\OpenApiFactoryInterface;
use ApiPlatform\OpenApi\OpenApi;

readonly class OpenApiTranslatorFactory implements OpenApiFactoryInterface
{
    private const DEFAULT_LANG = 'en';
    public function __construct(
        private OpenApiFactoryInterface $decorated,
        private OpenApiTranslator $translator
    )
    {
    }

    /**
     * @inheritDoc
     */
    public function __invoke(array $context = []): OpenApi
    {
        $lang = $context['lang'] ?? self::DEFAULT_LANG;
        $openApi =($this->decorated)($context);
        return $this->translator->translate($openApi, $lang);
    }
}

and fix commad api:openapi:export command to check which translation available (or add some argument) and generate translated OpenAPI specifications with some suffix in the filename, e.g. 'openapi_en.json', 'openapi_de.json' and etc.

stale[bot] commented 8 months ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.