Tuesday, December 6, 2016

RESTful principles provide strategies to handle CRUD actions using HTTP methods

RESTful principles provide strategies to handle CRUD actions using HTTP methods mapped as follows:

    GET /objects - Retrieves a list of objects
    GET /objects/12 - Retrieves a specific object
    POST /objects - Creates a new object
    PUT /objects/12 - Updates object #12
    PATCH /objects/12 - Partially updates object #12
    DELETE /objects/12 - Deletes object #12



The great thing about REST is that you're leveraging existing HTTP methods to implement significant functionality on just a single /objects endpoint. There are no method naming conventions to follow and the URL structure is clean & clear.


But how do you deal with relations?
If a relation can only exist within another resource, RESTful principles provide useful guidance.
Let's look at this with an example. A Object in Enchant consists of a number of messages.
These messages can be logically mapped to the /objects endpoint as follows:

    GET /objects/12/messages - Retrieves list of messages for object #12
    GET /objects/12/messages/5 - Retrieves message #5 for object #12
    POST /objects/12/messages - Creates a new message in object #12
    PUT /objects/12/messages/5 - Updates message #5 for object #12
    PATCH /objects/12/messages/5 - Partially updates message #5 for object #12
    DELETE /objects/12/messages/5 - Deletes message #5 for object #12

Alternatively, if a relation can exist independently of the resource, it makes sense to just include an identifier for it within the output representation of the resource. The API consumer would then have to hit the relation's endpoint. However, if the relation is commonly requested alongside the resource, the API could offer functionality to automatically embed the relation's representation and avoid the second hit to the API.

No comments:

Post a Comment