Google Short URL API: Forbidden

1.3k views Asked by At

I have what I think is correctly written code yet whenever I try and call it I'm getting permission denied from Google.

file_get_contents(https://www.googleapis.com/urlshortener/v1/url): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden

This isn't a rate limit or anything as I currently have zero ever used...

I would have thought this is due to an incorrect API key but I've tried resetting it a number of times. There isn't some downtime while the API is first applied is there?

Or am I missing a header setting or something else just as small?

public function getShortUrl()
{
    $longUrl = "http://example.com/";
    $apiKey = "MY REAL KEY IS HERE";

    $opts = array(
        'http' =>
            array(
                'method'  => 'POST',
                'header'  => "Content-type: application/json",
                'content' => json_encode(array(
                    'longUrl' => $longUrl,
                    'key'     => $apiKey
                ))
            )
    );

    $context = stream_context_create($opts);

    $result = file_get_contents("https://www.googleapis.com/urlshortener/v1/url", false, $context);

    //decode the returned JSON object
    return json_decode($result, true);
}
1

There are 1 answers

0
Chris On BEST ANSWER

It seems I need to manually specify the key in the URL

$result = file_get_contents("https://www.googleapis.com/urlshortener/v1/url?key=" . $apiKey, false, $context);

This now works. There must be something funny with how the API inspects POST for the key (or lack of doing so).

Edit: For anyone in the future this is my complete function

public static function getShortUrl($link = "http://example.com")
{
    define("API_BASE_URL", "https://www.googleapis.com/urlshortener/v1/url?");
    define("API_KEY", "PUT YOUR KEY HERE");

    // Used for file_get_contents
    $fileOpts = array(
        'key'    => API_KEY,
        'fields' => 'id' // We want ONLY the short URL
    );

    // Used for stream_context_create
    $streamOpts = array(
        'http' =>
            array(
                'method'  => 'POST',
                'header'  => [
                    "Content-type: application/json",
                ],
                'content' => json_encode(array(
                    'longUrl' => $link,
                ))
            )
    );

    $context = stream_context_create($streamOpts);
    $result = file_get_contents(API_BASE_URL . http_build_query($fileOpts), false, $context);

    return json_decode($result, false)->id;
}