IoT Central Rest Api Add/Update Device w/deviceTemplate returning 400 Bad Request

waiiki 20 Reputation points
2023-05-25T17:00:01.61+00:00

I'm going to go ahead and link the github issue I created. I closed the issue there and am moving it here because I'm not sure if its specific to me, or if the docs are incorrect. Please see this link:

https://github.com/MicrosoftDocs/azure-docs/issues/110004

Basically I am following the CreateDevice api request with a given device template id and am receiving this error:

"The model definition for this device was not found. You can contact support at https://aka.ms/iotcentral-support. Please include the following information. Request ID: ba7ybknx, Time: Thu, 25 May 2023 16:50:15 GMT."

Support for technical questions is $30/month which I'm hoping not to have to pay.

Azure IoT Central
Azure IoT Central
An Azure hosted internet of things (IoT) application platform.
{count} votes

Answer accepted by question author
  1. LeelaRajeshSayana-MSFT 17,866 Reputation points Moderator
    2023-05-25T17:51:34.2066667+00:00

    Hi @waiiki Greetings! Welcome to Microsoft Q&A forum. Thank you for posting this question here.

    If you inspect the device template IDs returned though the list of devices API https://{subdomain}.azureiotcentral.com/api/devices?api-version=2022-07-31, you would notice that Template ID returned from the API is different from what you see on the IoT Central portal. Perhaps it is Hashed for security purposes. Here is an example for one of the devices returned though the API.

    enter image description here

    Inspecting the Device Template on the Azure Portal reveals that this is not ID you have specified for the template.

    enter image description here

    A work around for this is to create a test device on the IoT Central portal by assigning the Template desired and fetch the template ID using the device list API.

    Kindly note that the API would need a Bearer token for authentication. Once you get the correct Template ID, you can use the following code to create a Device.

    using System;
    using System.Diagnostics;
    using Newtonsoft.Json;
    using Microsoft.Azure.Devices.Shared;
    using Microsoft.Azure.Devices.Provisioning.Client;
    using Microsoft.Azure.Devices.Provisioning.Client.Transport;
    
    
    namespace BulkProvision // Note: actual namespace depends on the project name.
    {
        internal class Program
        {
            static string subdomain = "<subdomain>";
            static string baseDomain = "azureiotcentral.com";
    
            static string displayName = "<DeviceName";
            static string apiVersion = "2022-07-31";
            static string DeviceId = "TestDPS1";
    
            static string modelId = "dtmi:dfwvpjdt:uwszlqrlil";
            static async Task Main(string[] args)
            {
                var token = GetAccessToken();
                Console.WriteLine(token);
                await CreateDevice(token);
                await GetDeviceCredentials(token);
            }
    
            public static string GetAccessToken()
            {
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "C:\\Program Files (x86)\\Microsoft SDKs\\Azure\\CLI2\\wbin\\az.cmd",
                        Arguments = $"account get-access-token --resource https://apps.azureiotcentral.com",
                        RedirectStandardOutput = true,
                        UseShellExecute = false,
                        CreateNoWindow = true
                    }
                };
    
                process.Start();
                var output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
    
                return output.Split('"')[3];
            }
    
            static async Task CreateDevice(string AccessToken)
            {
                string url = $"https://{subdomain}.{baseDomain}/api/devices/{DeviceId}?api-version={apiVersion}";
                string accessToken = AccessToken;
                string requestBody = $@"{{""name"": ""{displayName}"",""displayName"": ""{displayName}"",""template"": ""{modelId}"",""enabled"": true,""simulated"": false}}";
    
                using (var httpClient = new HttpClient())
                {
                    using (var request = new HttpRequestMessage(new HttpMethod("PUT"), url))
                    {
                        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                        request.Content = new StringContent(requestBody, System.Text.Encoding.UTF8, "application/json");
    
                        HttpResponseMessage response = await httpClient.SendAsync(request);
    
                        if (response.IsSuccessStatusCode)
                        {
                            Console.WriteLine("Device updated successfully.");
                        }
                        else
                        {
                            Console.WriteLine($"Failed to update device. Status code: {response}");
                        }
                    }
                }
            }
    
        }
    }
    
    

    Please note that the above code uses Azure CLI and references it's installation path using the FileName parameter. Please make sure to install it and refer the corresponding path if you prefer to use this code. Also, modify the code to assign the Subdomain, device name, device ID, model ID per your needs.

    Hope this helps. Please let us know if you have any additional questions or need further assistance.


    If the response helped, please do click Accept Answer and Yes. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.

    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Dominic 1,631 Reputation points Microsoft Employee
    2023-05-26T07:17:58.26+00:00

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.