he4d he4d - 4 months ago 43
reST (reStructuredText) Question

WebAPI only for data-exchange?

My intent is to create a WebAPI for an IoT Device. It should give me informations about Hardware Ports, Device Status etc. My question now is, would it be okay to use it for controlling some of the ports. For example a LED which is connected to an output of the IoT Device is would be controlled like [GET] /api/led/{id}/on
[GET] /api/led/{id}/off

Would that contradict the actual meaning of a WebAPI?


Yes - this is not a great structure, as the GET method is supposed to be idempotent AND safe - see http://restcookbook.com/HTTP%20Methods/idempotency/ for a more detailed definition, but practically speaking what it means to say it's safe is that a GET request should not modify state or data.


GET /api/led/{id}/on

should return a representation to indicate if it is on or off, but should not actually modify the state of the led. It could return true or {"on" : true } if it were on and false if it were off - whatever makes sense for your application.

To turn it on or off you should use a non-safe method, so what you could do is:

PUT /api/led/{id}/on

and make the body true or false, or possibly {"on":true} or {"on":false}

or possibly

POST /api/led/{id}/on

to turn it on and

POST /api/led/{id}/off

to turn it off.

All of the above are valid WebApi/REST techniques, but some may be more or less clear to the consumer depending on standard terminology/semantics in your context.