1

Hello i am trying to fetch devices present/registered at IOTHUB via RESTAPI. But i am confused how to fetch all devices. I have read the documentation here : IoT Hub Service - Get Devices

But When i send a request i am getting an error

"Message": "ErrorCode:IotHubUnauthorizedAccess;Unauthorized", "ExceptionMessage": "Tracking ID:a795ee1f7ae04adfa600333e45e9aa09-G:5-TimeStamp:06/29/2020 14:32:56"

Is there any auth token to provide in order to get devices?

SatishBoddu
  • 752
  • 6
  • 13
omer salam
  • 27
  • 4

2 Answers2

2

You can call the rest API using the Shared Access Signature. To get a valid token, you can use the Azure CLI like so:

az iot hub generate-sas-token -n <IoT hub name> --policy registryRead

This will produce an output like:

{
  "sas": "SharedAccessSignature sr=iothubname.azure-devices.net&sig=kPszxZZZZZZZZZZZZZZZZZAhLTILsVpT0tp5sRSWiDZ0%3D&se=1593446477&skn=registryRead"
}

Then you need to use the value of "sas" as your Authorization header when you do your GET request. Curl example:

curl --location --request GET 'https://iothubname.azure-devices.net/devices?api-version=2019-07-01-preview' \
--header 'Authorization: SharedAccessSignature sr=iothubname.azure-devices.net&sig=kPszxZZZZZZZZZZZZZZZZZAhLTILsVpT0tp5sRSWiDZ0%3D&se=1593446477&skn=registryRead'
Matthijs van der Veer
  • 3,865
  • 2
  • 12
  • 22
2

So for a quick start on this we can use Postman with Azure IoT Hub Query language..+ SAS token for authorization.

Step 1: Generate the SAS token as said by Matthijs, Also we can quickly make use of Device Explorer tool Or Use this link to find the SetupDeviceExplorer.msi. Copy the generated SAS token fully.

enter image description here

Step 2: Construct the Query body.

the POST query looks like this sample. See Registry Manager - Query Iot Hub

POST https://IOTHUB.azure-devices.net/devices/query?api-version=2020-03-13

{
  "query": "SELECT deviceId FROM devices"
}

enter image description here

Step 3: Authorization use SAS token, and send the request to test it out.

enter image description here

A similar thread answered by RomanKiss can be read from Get all devices from IoT Azure Hub. Please let us know if you know further help!

SatishBoddu
  • 752
  • 6
  • 13