How do I goo.gl-shorten the url in js?

Prereq: create yourself an API key for urlshortener https://code.google.com/apis/console/

There are many documents for various ways of turning the goo.gl URL into the original URL via js get api, for example: here , here and here - and at least the first one even works.

If I set up a bit to use insert api to convert the URL to a tiny URL, passing { "longUrl": "https://codepen.io/" } instead breaks it. Try it at http://codepen.io/johan/full/EHbGy#YOUR-API-KEY-HERE if you want, or run this somewhere:

 <script> var api_key = 'YOUR-API-KEY-HERE'; function makeRequest() { var request = gapi.client.urlshortener.url.insert({ 'longUrl': 'https://codepen.io/' }); request.execute(function(response) { alert(JSON.stringify(window.got = response)); }); } function load() { gapi.client.setApiKey(api_key); gapi.client.load('urlshortener', 'v1', makeRequest); } </script> <script src="https://apis.google.com/js/client.js?onload=load"></script> 

... it just answers with an error:

 { "code": 400 , "message": "Required" , "data": [ { "domain": "global" , "reason": "required" , "message": "Required" , "locationType": "parameter" , "location": "resource.longUrl" } ] , "error": { "code": 400 , "message": "Required" , "data": [ { "domain": "global" , "reason": "required" , "message": "Required" , "locationType": "parameter" , "location": "resource.longUrl" } ] } } 

Suggestions? (No, this will not work if you change the url.insert parameter to an object using the resource.longUrl key - or just pass the URL without a wrapper object.)

+6
source share
2 answers

In the document or error message this is not very clear, but your request should look like this: everything will be fine:

 var request = gapi.client.urlshortener.url.insert({ 'resource': {'longUrl': 'https://codepen.io/'} }); 
+6
source

I think I will drop the messy client library for this when it turns out that I can do this five lines of coffescript instead of loading all of these cracks since I already have jQuery: http://codepen.io/johan/ pen / puJyH

 api = 'https://www.googleapis.com/urlshortener/v1/url' api += "?key=#{key}" if key = location.search.slice 1 $.ajax url: api type: 'POST' data: JSON.stringify(longUrl: url) contentType: 'application/json' success: (got) -> alert "shortened url: #{got.id}" 
+1
source

All Articles