mscharhag, Programming and Stuff;

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

Thursday, 27 August, 2020

REST: Retrieving resources

Retrieving resources is probably the simplest REST API operation. It is implemented by sending a GET request to an appropriate resource URI. Note that GET is a safe HTTP method, so a GET request is not allowed to change resource state. The response format is determined by Content-Negotiation.

Retrieving collection resources

Collections are retrieved by sending a GET request to a resource collection.

For example, a GET request to /paintings might return a collection of painting resources:

Request:

GET /paintings
Accept: application/json

Response:

HTTP/1.1 200 (Ok)
Content-Type: application/json

[
    {
        "id": 1,
        "name": "Mona Lisa"
    }, {
        "id": 2
        "name": "The Starry Night"
    }
]

The server indicates a successful response using the HTTP 200 status code (see: Common HTTP status codes).

Note that it can be a good idea to use a JSON object instead of an array as root element. This allows additional collection information and Hypermedia links besides actual collection items.

Example response:

HTTP/1.1 200 (Ok)
Content-Type: application/json

{
    "total": 2,
    "lastUpdated": "2020-01-15T10:30:00",
    "items": [
        {
            "id": 1,
            "name": "Mona Lisa"
        }, {
            "id": 2
            "name": "The Starry Night"
        }
    ],
    "_links": [
        { "rel": "self", "href": "/paintings" }
    ]
}

If the collection is empty the server should respond with HTTP 200 and an empty collection (instead of returning an error).

For example:

HTTP/1.1 200 (Ok)
Content-Type: application/json

{
    "total": 0,
    "lastUpdated": "2020-01-15T10:30:00",
    "items": [],
    "_links": [
        { "rel": "self", "href": "/paintings" }
    ]
}

Resource collections are often top level resources without an id (like /products or /paintings) but can also be sub-resources. For example, /artists/42/paintings might represent the collection of painting resources for the artist with id 42.

Retrieving single resources

Single resources retrieved in the same way as collections. If the resource is part of a collection it is typically identified by the collection URI plus the resource id.

For example, a GET request to /paintings/1 might return the painting with id 1:

Request:

GET /paintings/1
Accept: application/json

Response:

HTTP/1.1 200 (Ok)
Content-Type: application/json

{
    "id": 1,
    "name": "Mona Lisa",
    "artist": "Leonardo da Vinci"
}

If no resource for the given id is available, HTTP 404 (Not found) should be returned.

 

Leave a reply