2013-06-02

Accessing Spotify Metadata API from TypeScript

I decided to try out the latest TypeScript with a web API. Because I'm running in a browser, I needed the web API to support CORS. There are several popular web APIs that support CORS. I use Spotify all the time and decided to try accessing the Spotify Metadata API from TypeScript. Their API isn't very big, but for this research, I simply wrapped their album lookup. Here is a unit test that demonstrates use of the TypeScript client I created:

In Spotify's desktop client, you can right click on any album and get a Spotify URI. The Spotify URI for the Confess album by Twin Shadow is "spotify:album:3rhlzjGgPa8H48HYsibOeh". The Metadata API allows you to lookup info about that album by doing a HTTP GET to http://ws.spotify.com/lookup/1/.json?uri=spotify:album:3rhlzjGgPa8H48HYsibOeh.

All the code for the solution is on GitHub here. I'm using the latest TypeScript 0.9 alpha that supports generics and the Web Essentials extension to create the .js each time a .ts is saved. There were a few challenges I had to overcome. I was expecting to be able to create an interfaces for the JSON returned, but they used names with hyphens in it. If you are authoring a new web API, I would not recommend putting hyphens in your JSON names since it requires you to access them in JavaScript via quoted property names. The next release of TypeScript should have support for quoted property names in interface declarations. To work around the limitation, I created classes that wrapped each JSON interface. While doing that, I discovered that the type inference for Array.map still has some bugs to be worked out, but that is completely understandable for an alpha. The progress they are making with TypeScript is terrific and I'm really looking forward to the generics support they are working on. May be next time, I can try out a Generic Promise.