phpjsonpostguzzlegoogle-url-shortener

Guzzle POST request not working


I would like to use Google URL Shortener API. Now, I need to send a JSON POST request to the Google API.

I'm using Guzzle 6.2 in PHP.

Here is what I have tried so far:

$client = new GuzzleHttp\Client();
$google_api_key =  'AIzaSyBKOBhDQ8XBxxxxxxxxxxxxxx';
$body = '{"longUrl" : "http://www.google.com"}';
$res = $client->request('POST', 'https://www.googleapis.com/urlshortener/v1/url', [
      'headers' => ['Content-Type' => 'application/json'],
      'form_params' => [
            'key'=>$google_api_key
       ],
       'body' => $body
]);
return $res;

But it returns following error :

Client error: `POST https://www.googleapis.com/urlshortener/v1/url` resulted in a `400 Bad Request` response:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
(truncated...)

Any helps would be appreciated. I've read Guzzle document and many other resources but didn't help!


Solution

  • You don't need form_params, because Google requires simple GET parameter, not POST (and you can not even do that, because you have to choose between body types: form_params creates application/x-www-form-urlencoded body, and body parameter creates raw body).

    So simply replace form_params with query:

    $res = $client->request('POST', 'https://www.googleapis.com/urlshortener/v1/url', [
        'headers' => ['Content-Type' => 'application/json'],
        'query' => [
            'key' => $google_api_key
        ],
        'body' => $body
    ]);
    
    // Response body content (JSON string).
    $responseJson = $res->getBody()->getContents();
    // Response body content as PHP array.
    $responseData = json_decode($responseJson, true);