Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-CRUD operations in a RESTful service

What is the "RESTful" way of adding non-CRUD operations to a RESTful service? Say I have a service that allows CRUD access to records like this:

GET /api/car/123           <- Returns information for the Car object with ID 123 POST /api/car              <- Creates a new car (with properties in the request) PUT /api/car/123           <- Updates car 123 (with properties in the request) DELETE /api/car/123        <- Deletes car 123     POST /api/car/123/wheel/   <- Creates a wheel and associates it to car 123 

If I want to change the car's color, I would simply POST /api/car/123 and include a POST variable for the new color.

But let's say I want to purchase a car, and that operation is more complicated than simply updating a "user" record's "owned car" property. Is it RESTful to simply do something like POST /api/car/123/purchase, where "purchase" is essentially a method name? Or should I use a custom HTTP verb, like PURCHASE instead of POST?

Or are non-CRUD operations completely outside the scope of REST?

like image 886
MikeWyatt Avatar asked Jul 27 '11 19:07

MikeWyatt


People also ask

Is REST API only CRUD?

No, REST is about how your API represents data and interactions with that data as objects... CRUD is well suited to a REST api, but you can think about just about anything as an entity.

What is CRUD in REST Web services?

In the context of the RESTful web services, this method is used to retrieve resources. This is the method used for read operations (the R in CRUD). HEAD: The HEAD requests are semantically identical to the GET requests except the body of the response is not transmitted.

What is an example of a non RESTful API?

The classic example of a non-RESTful system using HTTP is something which treats HTTP as if it was a transport protocol, and with every request sends a POST of data to the same URI which is then acted upon in an RPC-like manner, possibly with the connection itself having shared state.


1 Answers

Think about purchase as a business entity or a resource in RESTful dictionary. That being said, making a purchase is actually creating a new resource. So:

POST /api/purchase 

will place a new order. The details (user, car, etc.) should be referenced by id (or URI) inside the contents sent to this address.

It doesn't matter that ordering a car is not just a simple INSERT in the database. Actually, REST is not about exposing your database tables as CRUD operations. From logical point of view you are creating an order (purchase), but the server side is free to do as many processing steps as it wants.

You can even abuse HTTP protocol even further. Use Location header to return a link to newly created order, carefully choose HTTP response codes to inform users about problems (server- or client-side), etc.

like image 83
Tomasz Nurkiewicz Avatar answered Sep 24 '22 01:09

Tomasz Nurkiewicz