Online APIs

Consuming the YouTube API

As usual, we can use Groovy (or just translate this quite easily, excusing the try/catch/finally/close stuff, to Java) to do it!

import groovy.json.JsonSlurper

def apiKey = "GET_ONE_API_KEY_FROM_GOOGLE"

def videoId = "e6Q1gLFWhhY"

def url  = "https://www.googleapis.com/youtube/v3/videos?" +

           "id=${videoId}&key=${apiKey}&part=snippet,contentDetails,statistics,status"

def connection = new URL( url ).openConnection()

if ( connection.responseCode == connection.HTTP_OK ) {

  def json = new JsonSlurper().parseText( connection.inputStream.text )

  

  // print some basic information about the video

  println "Video '${json.items[0].snippet.title}' was published by " +

          "'${json.items[0].snippet.channelTitle}' at '${json.items[0].snippet.publishedAt}"

} else {

  println "ERROR ${connection.responseCode}"

}

The Maven API

Details of the Maven API can be found here.

import static java.net.URLEncoder.encode

def parse = new groovy.json.JsonSlurper().&parseText

final MAVEN_URL = "http://search.maven.org/solrsearch/select?q="

final searchBy = [ 'general': '', 'className': 'c', 'groupId': 'g' ]

def search = { type, query ->

  parse(

    ( MAVEN_URL + searchBy[ type ] +

    ":${encode( query )}&rows=5&wt=json" ).toURL().text )

}

def printJson = { json ->

  json.response.docs.each { println "$it.id:$it.latestVersion" }

}

// Example queries

printJson search( 'className', 'HttpClient' )

printJson search( 'general', 'google guava' )

printJson search( 'groupId', 'org.codehaus.groovy' )

Accessing the Official.fm API with JavaScript

The code below is a simplified version of this Pen.

Documentation about the Official.fm API can be found here.

// create a XMLHttpRequest Object in any browser

var xmlhttp;

if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari

    xmlhttp=new XMLHttpRequest();

}

else { // code for IE6, IE5

    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

// response callback

xmlhttp.onreadystatechange = function() {

    if (xmlhttp.readyState == 4 &&

      xmlhttp.status == 200) {

        var json = JSON.parse( xmlhttp.responseText );

        // put the results in the #results html node

        document.getElementById("results").innerHTML=

          htmlFromJson(json);

    }

}

// retrieve the search text from the #searchBox node and query for tracks

var searchText = document.getElementById("searchBox").value;

var query = encodeURIComponent(searchText);

xmlhttp.open("GET",

   "http://api.official.fm/tracks/search?q=" + query +

"&types=original,remix,cover,embed&api_version=2", true);

xmlhttp.send();

// helper function that converts Json to HTML

function htmlFromJson(json) {

    var res = "";

    if (json.tracks.length == 0) {

      return "<div>Nothing found</div>"

    }

    for (i in json.tracks) {

      res += "<div>" + json.tracks[i].track.title + "</div>"

    }

    return res;

}