Play Framework 2.0: Generate TinyUrl With API

The Google URL Shortener at 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 :

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

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

def generateTinyUrl(longUrl: String): String = {

val apiKey = "GOOGLE_API_KEY"

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

val shortUrlJson = jpromise.get().asJson


OutPut: eg LongUrl=

TinyUrl would be :

Entire code can be found here:

About ruchijindal

Software Engineer in Knoldus
This entry was posted in Scala and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s