Design return values for RESTful API

后端 未结 2 1241
Happy的楠姐
Happy的楠姐 2021-01-23 03:18

There is a lot of documentation for RESTful services. I need more Information about the returning representations.

What is the best way for design the return value for R

2条回答
  •  猫巷女王i
    2021-01-23 03:47

    Use HTTP Content negotiation with vendor types. Don't use URL query parameters if you request different representations of the same resource.

    Request short representation application/vnd.com.example.cars.short+json of list

    GET http://example.com/rest/cars
    Accept: application/vnd.com.example.cars.short+json
    

    Response:

    200 OK
    Content-Type: application/vnd.com.example.cars.short+json
    
    [
      {
        "id": 12,
        "brand": "Ford"
      },
      {
        "id": 34,
        "brand": "Volkswagen"
      },
      {
        "id": 1234,
        "brand": "Tesla"
      }
    ]
    

    Request long represenation application/vnd.com.example.cars.long+json of single car

    GET http://example.com/rest/cars/1234
    Accept: application/vnd.com.example.cars.short+json
    

    Response

    200 OK
    Content-Type: application/vnd.com.example.cars.long+json
    
    {
      "id": 1234,
      "brand": "Tesla",
      "manufactured": "2016-03-15",
      "color": "black"
    }
    

    The vendor types can be used for both resources.

提交回复
热议问题