5

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!

Hamed Kamrava
  • 12,359
  • 34
  • 87
  • 125

3 Answers3

4

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);
Alexey Shokov
  • 4,775
  • 1
  • 21
  • 22
0

I wasnt able to make a post request, is not exactly the same case but I write here my solution in case helps someone:

I needed to send a post request with a key like this 'request_data', I was trying to do it as Guzzle docs say:

 $r = $client->request('PUT', 'http://test.com', [
'form_data' => ['request_data' => 'xxxxxxx']
 ]);

the result was something like this:

{'request_data':....}

but what I wanted was something like this:

 'request_data': {}

so what I finally figure it out was doing it like this:

    $client = new Client();

    $response = $client->request('POST', $url, [
        'body' => "request_data=" . json_encode([$yourData]),
        'headers' => [
            'Content-Type' => 'application/x-www-form-urlencoded'
        ]
    ]);

doing it like this the result is what I expected.

Evan
  • 1,004
  • 11
  • 12
-1

The manual says the following:

After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs.

Try to append `"key=$google_api_key" to your URL.

BVengerov
  • 2,947
  • 1
  • 18
  • 32