How to use Rest APIs of Azure IoT Hub

IoT hub is a kind of managed service where billions of IoT devices can be provisioned and managed. I faced one challenge when I had to send device data to cloud IoT hub by using azure functions. I couldn’t use the IoT hub’s built-in SDK and then the other way around was to use Rest APIs of azure IoT hub. In this scenario, let’s see how what should be the request message with header info and endpoint url would look like.

  1. To Get all Devices

 

static
async
Task<string> GetDevicesAsync()

{

 


var token = “SharedAccessSignature sr=myiothub.azure-devices.net&sig=WzrFLgkGnhvkJeR%2fF7sh5p%2bobE9ZVHMObNlf%2bKBF2HA%3d&se=1496930912&skn=iothubowner”;


using (var client = new
HttpClient())

{

 

client.BaseAddress = new
Uri(https://myiothub.azure-devices.net/&#8221;);

client.DefaultRequestHeaders.Accept.Clear();

client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue(“application/json”));

client.DefaultRequestHeaders.TryAddWithoutValidation(“Authorization”, token);


HttpResponseMessage response = await client.GetAsync(string.Format(“devices?top=100&api-version=2016-02-03”));


if (response.IsSuccessStatusCode)

{


var res = await response.Content.ReadAsStringAsync();


return res;

 

}


return
null; //result;

 

}

 

}

Header

URL

Request Message

Accept: application/json

Authorization: SharedAccessSignature sr= myiothub.azure-devices.net&sig=WzrFLgkGnhvkJeR%2fF7sh5p%2bobE9ZVHMObNlf%2bKBF2HA%3d&se=1496930912&skn=iothubowner

https://<yourIoThub&gt;.azure-devices.net/devices? top=100&api-version=2016-02-03

e.g.:

https://myiothub.azure-devices.net/devices?top=100&api-version=2016-02-03

{Method: GET, RequestUri: ‘https://myiothub.azure-devices.net/devices?top=100&api-version=2016-02-03&#8217;, Version: 1.1, Content: <null>, Headers:

{

Accept: application/json

Authorization: SharedAccessSignature sr= myiothub.azure-devices.net&sig=WzrFLgkGnhvkJeR%2fF7sh5p%2bobE9ZVHMOblf%2bKBF2HA%3d&se=1496930912&skn=iothubowner

}}

 

  1. To get a Particular Device

 

static
async
Task<string> GetDevice(string deviceId)

{

 


var token = “SharedAccessSignature sr=Myiothub.azure-devices.net&sig=WQrFLggGnhvkJeR%2fF7sh5p%2bobE9ZVHMObNlf%2bKBF2HA%3d&se=1496930912&skn=iothubowner”;


using (var client = new
HttpClient())

{

 

client.BaseAddress = new
Uri(https://Myiothub.azure-devices.net/&#8221;);

client.DefaultRequestHeaders.Accept.Clear();

client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue(“application/json”));

client.DefaultRequestHeaders.TryAddWithoutValidation(“Authorization”, token);


HttpResponseMessage response = await client.GetAsync(string.Format(“devices/{0}?api-version=2016-02-03”, deviceId));


if (response.IsSuccessStatusCode)

{


var res = await response.Content.ReadAsStringAsync();


return res;

 

}


return
null; //result;

 

}

 

}

Header

URL

Request Message

Accept: application/json

Authorization: SharedAccessSignature sr= myiothub.azure-devices.net&sig=WzrFLgkGnhvkJeR%2fF7sh5p%2bobE9ZVHMObNlf%2bKBF2HA%3d&se=1496930912&skn=iothubowner

https://<yourIoTHub&gt;.azure-devices.net/devices/<DeviceID>? api-version=2016-02-03

 

e.g.:

https://myiothub.azure-devices.net/devices/PressureSensor?api-version=2016-02-03

{Method: GET, RequestUri: ‘https://myiothub.azure-devices.net/devices/PressureSensor?api-version=2016-02-03&#8217;, Version: 1.1, Content: <null>, Headers:

{

Accept: application/json

Authorization: SharedAccessSignature sr=Myiothub.azure-devices.net&sig=WQrFLggGnhvkJeR%2fF7sh5p%2bobE9ZVHMbNlf%2bKBF2HA%3d&se=1496930912&skn=iothubowner

}}

 

  1. To add a new device

    static
    async
    Task<string> AddDeviceAsync(string newDeviceId)

    {


    string result = string.Empty;


    var token = “SharedAccessSignature sr=Myiothub.azure-devices.net&sig=WQrFLggGnhvkJeR%2fF7sh5p%2bobE9ZVHMObNlf%2bKBF2HA%3d&se=1496930912&skn=iothubowner”;


    using (var client = new
    HttpClient())

    {

     

    client.BaseAddress = new
    Uri(https://Myiothub.azure-devices.net/&#8221;);

    client.DefaultRequestHeaders.Accept.Clear();

    client.DefaultRequestHeaders.Accept.Add(new
    MediaTypeWithQualityHeaderValue(“application/json”));

    client.DefaultRequestHeaders.TryAddWithoutValidation(“Authorization”, token);


    var dataToPost = new

    {

    deviceId = newDeviceId,

    authentication = new

    {

    symmetricKey = new

    {

    primaryKey = “”,

    secondaryKey = “”

     

    }

    },

    status = “”,

    statusReason = “”

    };


    //var jsonData = JsonConvert.SerializeObject(dataToPost, Formatting.Indented);


    var content = new
    StringContent(JsonConvert.SerializeObject(dataToPost), Encoding.UTF8, “application/json”);

     


    HttpResponseMessage response = await client.PutAsync(string.Format(“devices/{0}?api-version=2016-02-03”, newDeviceId), content);


    if (response.IsSuccessStatusCode)

    {


    var res = await response.Content.ReadAsStringAsync();

     

     

    }


    return
    null; //result;

     

    }

     

    }

Header

URL

Request Message

Accept: application/json

Authorization: SharedAccessSignature sr= myiothub.azure-devices.net&sig=WzrFLgkGnhvkJeR%2fF7sh5p%2bobE9ZVHMObNlf%2bKBF2HA%3d&se=1496930912&skn=iothubowner

Content-Type: application/json; charset=utf-8

Content-Length: 126

https://<DeviceID&gt;.azure-devices.net/devices/<DeviceID>

 

e.g.:

https://myiothub.azure-devices.net/devices/PressureSensor

{Method: PUT, RequestUri: ‘https://myiothub.azure-devices.net/devices/PressureSensor?api-version=2016-02-03&#8217;, Version: 1.1, Content: System.Net.Http.StringContent, Headers:

{

Accept: application/json

Authorization: SharedAccessSignature sr=Myiothub.azure-devices.net&sig=WQrFLggGnhvkJeR%2fF7sh5p%2bobE9ZVMObNlf%2bKBF2HA%3d&se=1496930912&skn=iothubowner

Content-Type: application/json; charset=utf-8

Content-Length: 126

}}

  1. To send message to a device

 


static
async
Task<string> SendMessageAsync(string newDeviceId,JObject message)

{


string result = string.Empty;


var token = “SharedAccessSignature sr=Myiothub.azure-devices.net&sig=WQrFLggGnhvkJeR%2fF7sh5p%2bobE9ZVHMObNlf%2bKBF2HA%3d&se=1496930912&skn=iothubowner”;


var CorrelationId = newDeviceId + “_Sensor_” + message[“url”].ToString().Split(‘/’).Last();


var messageID = CorrelationId+“_”+DateTime.Parse(message[“current_value_time”].ToString()).ToString(“yyyyMMddhhmmss”);

 


var user = newDeviceId;


using (var client = new
HttpClient())

{

client.BaseAddress = new
Uri(https://Myiothub.azure-devices.net/&#8221;);

client.DefaultRequestHeaders.Accept.Clear();

client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue(“application/json”));

client.DefaultRequestHeaders.TryAddWithoutValidation(“Authorization”, token);

client.DefaultRequestHeaders.TryAddWithoutValidation(“IoTHub-MessageId”, messageID);

client.DefaultRequestHeaders.TryAddWithoutValidation(“IoTHub-CorrelationId”, CorrelationId);

client.DefaultRequestHeaders.TryAddWithoutValidation(“IoTHub-UserId”, user);


// var content = new StringContent(message, Encoding.UTF8, “application/json”);


HttpResponseMessage response = await client.PostAsJsonAsync(string.Format(“devices/{0}/messages/events?api-version=2016-02-03”, newDeviceId), message);


if (response.IsSuccessStatusCode)

{

result = await response.Content.ReadAsStringAsync();

 

 

}


DateTime.Now.ToString();


return result; //result;

 

}

 

}

Header

url

Request Message

Accept: application/json

Authorization: SharedAccessSignature sr=Myiothub.azure-devices.net&sig=WQrFLggGnhvkJeR%2fF7sh5p%2bobE9ZVHMObNlf%2bKBF2HA%3d&se=1496930912&skn=iothubowner

IoTHub-MessageId: PressureSensor_11_Sensor_1_20160701115000

IoTHub-CorrelationId: PressureSensor_11_Sensor_1

IoTHub-UserId: PressureSensor_11

Content-Type: application/json; charset=utf-8

Content-Length: 346

https://<YourIoTHub&gt;.azure-devices.net/devices/<DeviceID>

e.g.:

https://myiothub.azure-devices.net/devices/PressureSensor

{Method: POST, RequestUri: ‘https://myiothub.azure-devices.net/devices/PressureSensor_11/messages/events?api-version=2016-02-03&#8217;, Version: 1.1, Content: System.Net.Http.ObjectContent`1[[Newtonsoft.Json.Linq.JObject, Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed]], Headers:

{

Accept: application/json

Authorization: SharedAccessSignature sr=Myiothub.azure-devices.net&sig=WQrFLgGnhvkJeR%2fF7sh5p%2bobE9ZVHMObNlf%2bKBF2HA%3d&se=1496930912&skn=iothubowner

IoTHub-MessageId: PressureSensor_11_Sensor_1_20160701115000

IoTHub-CorrelationId: PressureSensor_11_Sensor_1

IoTHub-UserId: PressureSensor_11

Content-Type: application/json; charset=utf-8

Content-Length: 346

}}


 

Leave a comment