3

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 RESTful ervices?

Example:

  • GET /rest/cars: list with cars
  • GET /rest/cars/1234: the car with the ID 1234

For RESTful services:

  • Should the return values (car-objects) have the same attributes?
  • Can the detail object have more attributes then the list objects?
  • in which case must the objects be the same?
Carsten E
  • 31
  • 1
  • 2

2 Answers2

2

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.

1

Using query parameters to request a subset of fields

You can return the same representation in both cases and support filtering the fields to be returned with a query parameter:

GET /api/cars?fields=color,year HTTP/1.1
Host: example.com
Accept: application/json

Using custom media types to return a predefined set of fields

Another approach is to define a custom media type for a partial representation of your resource.

For example, you could use one of the following (or both) media types to retrieve a full representation of a collection of resources:

GET /api/cars HTTP/1.1
Host: example.com
Accept: application/json
GET /api/cars HTTP/1.1
Host: example.com
Accept: application/vnd.company.full+json

And the following to return a partial representation for your resource (the fields you will include in the partial representation are up to you):

GET /api/cars HTTP/1.1
Host: example.com
Accept: application/vnd.company.partial+json
cassiomolin
  • 124,154
  • 35
  • 280
  • 359