Why REST

September 16, 2014

Blog | Development | Why REST
Why REST
Most REST APIs “speak” JavaScript, or more specifically JSON (JavaScript Object Notation), so let’s get something out of the way: even if you don’t particularly likeJavaScript, it’s good to learn The Good Parts.  Back-end programmers, I’m talking to you.  Writing good front end logic is hard because users are unpredictable.  Don’t make writing the front end harder by imposing a complicated API pattern.  REST APIs are supposed to make it slightly less complicated by providing a uniform and pattern-driven way to read and write data from the front end.  That makes a front-end engineer’s life a bit easier.  On the other hand, a poorly designed or implemented REST API can make for more work.
Even if you never ever do front-end work, and never touch the browser, remember that somebody else does.  A little bit of time and consideration on your part can make someone else’s life much easier.


 


Lifting Sails


There’s a really elegant little framework for Node.js which makes REST patterns painfully obvious. It’s called Sails.js.  If you’re not familiar with Node, I recommend taking 15 minutes to download and install it.  There’s a lot of cool stuff going on there, and even if you’re not “one of those JavaScript people” there are a lot of good ideas to be had.



I put all of the working code for this post on BitBucket, but you’ll need Node and Sails to run it. The implementation is just to give our front-end JavaScript an API to talk to, so the implementation isn’t critical. We’ll get to that in a few posts.

 

And We’re Underway

jQuery contains a few “helper” methods to wrap the .ajax() methods.  The two I want to point to right away are .get() and .post() because they align perfectly with their respective http verbs.

$.get("/foo")
    .done(function (data, status) { // .done promise instead of callback
        var fooList = $("#foolist");
        fooList.empty();
        for (var i = 0; i < data.length; i++) {
            var item = '
  • Name:' + "" + "" + "" + "
  • "; fooList.append(item); } attachClickHandlers(); }) .fail(function () { alert("error"); }) .always(function () { console.log("finished GET"); });

    var data = {
        name: $("#fooname").val()
    };
    $.post("/foo", data)
        .done(getData) // .done promise instead of callback
        .fail(function () {
            alert("error");
        })
        .always(function () {
            $("#fooname").val("");
            console.log("finished POST");
        });

    In this case, I call jQuery’s (I use the shortcut, $) .get() method with the path to the REST API with the assumption that /foo will list all the “foo” objects. If I wanted a specific one, I’d .get() another path, such as /foo/2.

    jQuery does not offer shortcut helpers for DELETE and PUT (yet), so those methods I chose to implement in the older “ajax” style of request.

    $.ajax({
        url: '/foo/' + $this.data("foo-id"),
        type: 'PUT',
        data: data,
        success: function () { // callback since promises aren't standard yet
            getData();
        }
    });

    For consistency, using the older style of .ajax() call for every verb is probably a better choice, but I want to bring up the newer “promise” based style of programming because it’s something that we will see a lot more of in coming years.  In an upcoming post on Angular with REST I’ll use promises extensively.

    But what we’re focusing on here is a set of expectations for the API.

    GET http://localhost:1337/foo       -- lists all foo objects
    GET http://localhost:1337/foo/{id}  -- gets one specific foo object
    POST http://localhost:1337/foo  {some json form data} -- creates a foo object
    PUT http://localhost:1337/foo/{id}  {some json form data} -- updates one specific foo object
    DELETE http://localhost:1337/foo/{id}  -- deletes one specific foo object

     

    By following that pattern in most or all of the API design, the consumer gets consistency and portability.  He or she doesn’t have to write a lot of code, or know a lot about the underlying data.  They only need to know the route to that information and can go from there.  And that makes the front-end engineer’s job much easier.

    If you have questions, join the conversation on Twitter.  Or if you’d to check out the functioning app, hit up BitBucket.  In my next post I will be talking about how I built the backend, so join us again then.

    Dan Clouse

    Senior Developer
    Tags
    • Development
    • JavaScript
    • Patterns & Practices

    Recent Work

    Check out what else we've been working on