Play Framework 2.0: Generate TinyUrl With goo.gl API
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