Rest – Sending multiple resources under REST endpoints

api-designrest

I am designing an API where-

1. There can be multiple devices under a gateway.
2. There are multiple sensors on every device.

GET /devices/d1/sensors/s1 returns the status of sensor s1 on device d1.
Moving forward, I need to allow querying sensors across multiple devices.

Something like- GET /devices/d1,d2,d7,d30,d45,d500/sensors/s1,s5 would not scale as I'd be dealing with a lot of devices+sensors and increasing the URL length linearly would be bad design.

How can I approach this more elegantly?

Best Answer

One of the core ideas behind REST is that each URL provides a representation for a single resource (although that resource can be a collection that gives information about other resources).

If you want to get information about multiple sensors, where you don't know/care which device each sensor is connected to, the canonical way is to provide a top-level sensors resource: GET /sensors. This would give you all sensors in the system. If you wan't to restrict the list in some way, you use query parameters:

GET /sensors?device=d1,d2,d7,d30,d45,d500&type=temperature

would give you the temperature sensors connected to the listed devices.

If you do care which device each sensor is connected to, there is no way around performing multiple requests, one for each device.

Related Topic