When in my REST API should I use an envelope? If I use it in one place, should I always use it?

I’d say “hell yes!” (contrary to someone here who said “hell no”) to an envelope! There’s always some extra information that needs to be sent from some endpoints. Pagination, errorMessages, debugMessages for example. An example how facebook does it:

Response from get friends request

{
  "data": [
    {
      "id": "68370", 
      "name": "Magnus"
    }, 
    {
      "id": "726497", 
      "name": "Leon"
    }, 
    {
      "id": "57034", 
      "name": "Gonçalo"
    }
  ], 
  "paging": {
    "next": "https://graph.facebook.com/v2.1/723783051/friends?fields=id,name&limit=5000&offset=5000&__after_id=enc_AeyGEGXHV9pJmWq2OQeWtQ2ImrJmkezZrs6z1WXXdz14Rhr2nstGCSLs0e5ErhDbJyQ"
  }, 
  "summary": {
    "total_count": 200
  }
}

Here we have pagination with the next link to request to get the next chunk of users and a summary with the total number of friends that can be fetched. However they don’t always send this envelope, sometimes the data can go straight in the root of the body. Always sending the data the same way makes it much easier for clients to parse the data since they can do it the same for all endpoints. A small example of how clients can handle envelope responses:

public class Response<T> {
  public T data;
  public Paging paging;
  public Summary summary;
}

public class Paging {
  public String next;
}

public class Summary {
  public int totalCount;
}

public class WebRequest {
  public Response<List<User>> getFriends() {
    String json = FacebookApi.getFriends();
    Response<List<User>> response = Parser.parse(json);
    return response;
  }
}

This Response object could then be used for all endpoints by just changing List to the data that the endpoints returns.

Leave a Comment