Google URL shortener

Here’s a library I use frequently for URL shortening:

GoogleLib.scpt:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

property googleAPIKey : "your Google API key goes here"

on shortenURL(theURL)
	--	Parameters:
	--		theURL (string) => the full URL to be shortened
	--	Result:
	--		string <= the shortened URL
	
	local jsonResult
	
	set jsonResult to do shell script "curl https://www.googleapis.com/urlshortener/v1/url?key=" & googleAPIKey & " -s -H 'Content-Type: application/json' -d '{\"longUrl\": \"" & theURL & "\"}'"
	tell application "JSON Helper"
		return |id| of (read JSON from jsonResult)
	end tell
end shortenURL

The library relies in the free JSON Helper application available from the Mac App Store.

Usage:

use GoogleLib : script "GoogleLib" version "1.0"

set theURL to "http://forum.latenightsw.com"
set theShortenedURL to GoogleLib's shortenURL(theURL)

theShortenedURL --> "http://goo.gl/NPaXIB"

…and here is the same library re-written using AppleScriptObjC to replace the JSON Helper application:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

-- classes, constants, and enums used
property NSJSONSerialization : a reference to current application's NSJSONSerialization
property NSUTF8StringEncoding : a reference to 4
property NSString : a reference to current application's NSString

property googleAPIKey : "your Google API key goes here"


on shortenURL(theURL)
	--	Parameters:
	--		theURL (string) => the full URL to be shortened
	--	Result:
	--		string <= the shortened URL
	
	local jsonResult, jsonData, jsonObject
	
	local jsonResult, jsonData, jsonObject, shortenedURL
	
	set jsonResult to do shell script "curl https://www.googleapis.com/urlshortener/v1/url?key=" & googleAPIKey & " -s -H 'Content-Type: application/json' -d '{\"longUrl\": \"" & theURL & "\"}'"
	set jsonData to (NSString's stringWithString:jsonResult)'s dataUsingEncoding:NSUTF8StringEncoding
	set jsonObject to NSJSONSerialization's JSONObjectWithData:jsonData options:0 |error|:(missing value)
	set shortenedURL to jsonObject's objectForKey:"id"
	
	return shortenedURL as text
end shortenURL

UPDATE: Code revised as Shane suggested.

Having Shane around has made my try AppleScriptObjC more than I otherwise would have, and I’m beginning to quite like it. It does not hurt that with SD6, its actually usable.

You might want to add an as text to that return statement, to get an AS string.

I think you’re hooked :wink:

1 Like