Play Framework 2.0: Generate TinyUrl With goo.gl API

Table of contents
Reading Time: 2 minutes

The Google URL Shortener at goo.gl is a service that takes long URLs and squeezes them into fewer characters to make a link that is easier to share, tweet, or email.

Steps to integrate with goo.gl :

Step #1 : Register App with Google

Register your App with Google through the API Console.  When you create your application, you register it with Google. Google then provides information you’ll need later, such as a client ID and a client secret , Api key etc .

Step #2: Authorizing requests and identifying your application

Requests to the Google URL Shortener API for non-public user data must be authorized by an authenticated user.Every request your application sends to the Google URL Shortener API needs to identify your application to Google. Your App would be recognized by Google through API Key in the API Access pane.

Step #3: Activate the Google URL Shortener API

Activate the Google URL Shortener API in the Services pane of the Google APIs Console.

Step #4: Acquiring and using an API key

Requests to the Google URL Shortener API for public data must be accompanied by an identifier, which can be an API key or an auth token. Go to the API Access  pane. The API key is near the bottom of that pane, in the section titled “Simple API Access.”

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

The API key is safe for embedding in URLs; it doesn’t need any encoding.

Step #5: Code in Play2.0 to Shorten a long URL

[sourcecode language=”scala” wraplines=”false” collapse=”false”]

import play.libs.WS
import play.api.Play

def generateTinyUrl(longUrl: String): String = {

val apiKey = "GOOGLE_API_KEY"

val jpromise = WS.url("https://www.googleapis.com/urlshortener/v1/url")
.setHeader("Content-Type", "application/json")
.setQueryParameter("key", apiKey)
.post("""{"longUrl": """" + longUrl + """"}""")

val shortUrlJson = jpromise.get().asJson

shortUrlJson.get("id").toString
} [/sourcecode]

OutPut: eg LongUrl= http://blog.knoldus.com/2013/02/02/how-to-use-goo-gl-api-to-generate-tiny-url-in-play-framework/

TinyUrl would be : http://goo.gl/gmynm

Entire code can be found here:  https://github.com/knoldus/scalajobz/blob/master/app/utils/GoogleApisUtil.scala

1 thought on “Play Framework 2.0: Generate TinyUrl With goo.gl API2 min read

  1. This is the perfect blog for anyone who would like to find out about this topic.
    You know so much its almost hard to argue with you (not that I personally would want to…HaHa).
    You definitely put a brand new spin on a topic which has been written about for
    decades. Wonderful stuff, just excellent!

Comments are closed.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading