Sunday, March 15

Give It a Rest: REST apis part 1

So, first off I'm going to talk about one of the simplest ways to get a web service to send you data - it's called REST.

REST stands for representational state transfer and is an architecture, a way of laying out resources on a server. The idea is that the information you want to get at (the "resource") can be asked for by describing a "representation" of that data using HTTP calls. Services which do this are "RESTful".

For example, say you have a service which provides you with details of the weather in a specific location. One way to query this service might be:

[serverlocation]?country=uk&city=london

Which is to say, what's it like in London, UK right now?
Another equally valid way to ask for this information might be:

[serverlocation]?lat=5132N&long=0005W

Which refers to exactly the same place (resource), but in a different way. As long as the server accepts all of these query parameters, they're both fine to use.

The key here is that you don't have to send a HTTP header, you don't need any funny protocols, you just ask for a page with well defined query parameters saying what you need, and bing! that page contains the appropriate data.

The response itself can be in pretty much any format, indeed - you'd often use one query parameter for the response format, if you have a choice. Suppose it was XML, it might look like this:

<response>
<temp>12.7</temp>
<windspd>34.6</windspd>
<winddir>170</windir>
<humid>54</humid>
</response>

Which I've just made up, but you get the idea. If you ask for the weather info for the city of "Gropiertegbun", you might instead get this:

<response>
<error>city not recognised</error>
</response>

With the possible exception that "recognised" would probably end up getting spelt the American way. That's because I made that city up, and even if I didn't, perhaps asking for a city without a country ID returns an error too. REST apis generally have fairly simple rules about which parameters you can use with which, and generally have defaults for when specific parameters are missing.

Part 2 will deal with how to use a server scripting language, in this case PHP, to make these calls and parse (read out) the results. I'll then probably follow on with details of how to build a user inteface to modify the queries, and how you can feed the results into other apis to display and use your data.

No comments:

Post a Comment