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

前端 未结 5 1552
面向向阳花
面向向阳花 2020-12-03 02:33

I\'m working on building a RESTful web service. I have read up on the principles of using HTTP for every mechanism as far as it will take you, and most of the time, like whe

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 03:08

    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 {
      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> getFriends() {
        String json = FacebookApi.getFriends();
        Response> 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.

提交回复
热议问题