REST-approach. Part 2

When using the REST approach to build custom applications there may appear cases when you want to sort the entries or add paginated list. Also, when using REST there are situations when there are subsidiary resources, such as a list of colors of cars.

In order to manage the subsidiary resources we need to create a new resource, and then tie it to the old one. For example, you need to show the color of cars in a separate resource in the application. It is almost directly related to the database schema in where the data is stored. But in fact, you can make your objects’ schema not the same as a database schema. To allocate the colors to separate looks quite natural and justified.

Let's create a resource "color" with the address "auto.com/color". Work with it it will be built in the same way as the work with the resource "cars". You also need to adjust a little bit the resource "cars" so it looks like this and add another resource for color.

Resource for colors:

{

 "Id": "1",

 "Name": "blue"

}

To associate the color with the car, you need to link an object to the vehicle color.

Modified car object:

{

    "id": 2,

    "model": "Lada",

    "color": {

         "id": "1",

         "name": "blue"

    }

 }

 

In the user interface, color is likely to be selected from color drop-down list.

The following approach can be used to implement the search of cars: add a separate address and controller for the search "auto.com/mobile/search/lada+kalina", but it is very similar to a separate resource. But, as has been described in a previous article, all resources should be uniquely identified. But with this approach, we can see a different set of data, which will change be from one request to other, so even though this option and obvious, but it is not correct to use it.

In order to make searching for car title to add to the GET request to another parameter "search". For example like this - "auto.com/mobile?search=lada+kalina", and the server respectively to handle such a request. Thus, the query string is not like a particular resource, but can solve the problem of searching.

Sorting and pagination works similarly.

To sort -  you must add two more parameters in the query "order" and "direction" in following way "auto.com/mobile?order=desc&direction=name". According to your request we will get all the cars, sorted in descending order.

For the pagination - you must add parameters "page" and "limit". "Page" shows the current page, and the "limit" indicates the number of records per page. If you send to the server the next request "auto.com/mobile?page=2&limit=25", you will get the cars with numbers 26 to 50.

The similar parameters can be added in any order and in any amount, it is important that server application knew about them and could process them.

Best regards,

Mind Team

Published at:28.05.2015