phparraysrestgoogle-translategoogle-translation-api

Multiple lines for Google translate API (v2) and PHP (Symfony) requests problem


In my application, which uses Symfony and Google Translate API (v2), I have the following simple code:

$textArray = ["this is my text", "my text is amazing"];

$options = [
    'body' => [
        'q' => $textArray,
        'target' => $targetLocale,
        'format' => $format,
        'source' => $locale,
        'model' => 'base',
        'key' => $this->parameterBag->get('google_api_key')
    ],
    'headers' => [
        'ContentType' => 'application/json'
    ]
];
$response = $this->client->request(
    'POST',
    $this->parameterBag->get('google_translate_api.v2.translate_path'),
    $options
);

I use Symfony\Contracts\HttpClient\HttpClientInterface for the requests. So, the my $options are the following: $options variable

In response I get a 400 error. So, during debugging I found out that the problem is in the "q" - it expects a string, not array. The official documentation says that I should send the array of strings there if I have multiple sentences, at least I have such option. When I send them through Postman using the same "q" keys, everything works fine. in Postman works well

So, the question is: how should I modify my array of Qs in order to make it work?


Solution

  • So, the solution was actually is in using 'json instead of 'body' and the thing that we need to pass the key in 'query', not in 'json', separately.

    $options = [
        'json' => [
            'q' => $textArray,
            'target' => $targetLocale,
            'format' => $format,
            'source' => $locale,
            'model' => 'base',
        ],
        'query' => [
            'key' => $this->parameterBag->get('google_api_key'),
        ]
    ];
    

    this way we will have a possibility to send a proper array as array of Q strings.