Create an IoT hub using the resource provider REST API (.NET)

You can use the IoT Hub resource provider REST API to create and manage Azure IoT hubs programmatically. This tutorial shows you how to use the IoT Hub resource provider REST API to create an IoT hub from a C# program.


This article has been updated to use the Azure Az PowerShell module. The Az PowerShell module is the recommended PowerShell module for interacting with Azure. To get started with the Az PowerShell module, see Install Azure PowerShell. To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.

To complete this tutorial, you need the following:

  • Visual Studio.

  • An active Azure account. If you don't have an account, you can create a free account in just a couple of minutes.

  • Azure PowerShell 1.0 or later.

Prepare to authenticate Azure Resource Manager requests

You must authenticate all the operations that you perform on resources using the Azure Resource Manager with Azure Active Directory (AD). The easiest way to configure this is to use PowerShell or Azure CLI.

Install the Azure PowerShell cmdlets before you continue.

The following steps show how to set up password authentication for an AD application using PowerShell. You can run these commands in a standard PowerShell session.

  1. Sign in to your Azure subscription using the following command:

  2. If you have multiple Azure subscriptions, signing in to Azure grants you access to all the Azure subscriptions associated with your credentials. Use the following command to list the Azure subscriptions available for you to use:


    Use the following command to select subscription that you want to use to run the commands to manage your IoT hub. You can use either the subscription name or ID from the output of the previous command:

    Select-AzSubscription `
        -SubscriptionName "{your subscription name}"
  3. Make a note of your TenantId and SubscriptionId. You need them later.

  4. Create a new Azure Active Directory application using the following command, replacing the place holders:

    • {Display name}: a display name for your application such as MySampleApp

    • {Home page URL}: the URL of the home page of your app such as http://mysampleapp/home. This URL does not need to point to a real application.

    • {Application identifier}: A unique identifier such as http://mysampleapp. This URL does not need to point to a real application.

    • {Password}: A password that you use to authenticate with your app.

      $SecurePassword=ConvertTo-SecureString {password} –asplaintext –force
      New-AzADApplication -DisplayName {Display name} -HomePage {Home page URL} -IdentifierUris {Application identifier} -Password $SecurePassword
  5. Make a note of the ApplicationId of the application you created. You need this later.

  6. Create a new service principal using the following command, replacing {MyApplicationId} with the ApplicationId from the previous step:

    New-AzADServicePrincipal -ApplicationId {MyApplicationId}
  7. Set up a role assignment using the following command, replacing {MyApplicationId} with your ApplicationId.

    New-AzRoleAssignment -RoleDefinitionName Owner -ServicePrincipalName {MyApplicationId}

You have now finished creating the Azure AD application that enables you to authenticate from your custom C# application. You need the following values later in this tutorial:

  • TenantId
  • SubscriptionId
  • ApplicationId
  • Password

Prepare your Visual Studio project

  1. In Visual Studio, create a Visual C# Windows Classic Desktop project using the Console App (.NET Framework) project template. Name the project CreateIoTHubREST.

  2. In Solution Explorer, right-click on your project and then click Manage NuGet Packages.

  3. In NuGet Package Manager, check Include prerelease, and on the Browse page search for Microsoft.Azure.Management.ResourceManager. Select the package, click Install, in Review Changes click OK, then click I Accept to accept the licenses.

  4. In NuGet Package Manager, search for Microsoft.IdentityModel.Clients.ActiveDirectory. Click Install, in Review Changes click OK, then click I Accept to accept the license.

  5. In Program.cs, replace the existing using statements with the following code:

    using System;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using Microsoft.Azure.Management.ResourceManager;
    using Microsoft.Azure.Management.ResourceManager.Models;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using System.Linq;
    using System.Threading;
  6. In Program.cs, add the following static variables replacing the placeholder values. You made a note of ApplicationId, SubscriptionId, TenantId, and Password earlier in this tutorial. Resource group name is the name of the resource group you use when you create the IoT hub. You can use a pre-existing or a new resource group. IoT Hub name is the name of the IoT Hub you create, such as MyIoTHub. The name of your IoT hub must be globally unique. Deployment name is a name for the deployment, such as Deployment_01.

    static string applicationId = "{Your ApplicationId}";
    static string subscriptionId = "{Your SubscriptionId}";
    static string tenantId = "{Your TenantId}";
    static string password = "{Your application Password}";
    static string rgName = "{Resource group name}";
    static string iotHubName = "{IoT Hub name including your initials}";


    Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.

Obtain an Azure Resource Manager token

Azure Active Directory must authenticate all the tasks that you perform on resources using the Azure Resource Manager. The example shown here uses password authentication, for other approaches see Authenticating Azure Resource Manager requests.

  1. Add the following code to the Main method in Program.cs to retrieve a token from Azure AD using the application id and password.

    var authContext = new AuthenticationContext(string.Format  
      ("{0}", tenantId));
    var credential = new ClientCredential(applicationId, password);
    AuthenticationResult token = authContext.AcquireTokenAsync
      ("", credential).Result;
    if (token == null)
      Console.WriteLine("Failed to obtain the token");
  2. Create a ResourceManagementClient object that uses the token by adding the following code to the end of the Main method:

    var creds = new TokenCredentials(token.AccessToken);
    var client = new ResourceManagementClient(creds);
    client.SubscriptionId = subscriptionId;
  3. Create, or obtain a reference to, the resource group you are using:

    var rgResponse = client.ResourceGroups.CreateOrUpdate(rgName,
        new ResourceGroup("East US"));
    if (rgResponse.Properties.ProvisioningState != "Succeeded")
      Console.WriteLine("Problem creating resource group");

Use the resource provider REST API to create an IoT hub

Use the IoT Hub resource provider REST API to create an IoT hub in your resource group. You can also use the resource provider REST API to make changes to an existing IoT hub.

  1. Add the following method to Program.cs:

    static void CreateIoTHub(string token)
  2. Add the following code to the CreateIoTHub method. This code creates an HttpClient object with the authentication token in the headers:

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
  3. Add the following code to the CreateIoTHub method. This code describes the IoT hub to create and generates a JSON representation. For the current list of locations that support IoT Hub see Azure Status:

    var description = new
      name = iotHubName,
      location = "East US",
      sku = new
        name = "S1",
        tier = "Standard",
        capacity = 1
    var json = JsonConvert.SerializeObject(description, Formatting.Indented);
  4. Add the following code to the CreateIoTHub method. This code submits the REST request to Azure. The code then checks the response and retrieves the URL you can use to monitor the state of the deployment task:

    var content = new StringContent(JsonConvert.SerializeObject(description), Encoding.UTF8, "application/json");
    var requestUri = string.Format("{0}/resourcegroups/{1}/providers/Microsoft.devices/IotHubs/{2}?api-version=2016-02-03", subscriptionId, rgName, iotHubName);
    var result = client.PutAsync(requestUri, content).Result;
    if (!result.IsSuccessStatusCode)
      Console.WriteLine("Failed {0}", result.Content.ReadAsStringAsync().Result);
    var asyncStatusUri = result.Headers.GetValues("Azure-AsyncOperation").First();
  5. Add the following code to the end of the CreateIoTHub method. This code uses the asyncStatusUri address retrieved in the previous step to wait for the deployment to complete:

    string body;
      HttpResponseMessage deploymentstatus = client.GetAsync(asyncStatusUri).Result;
      body = deploymentstatus.Content.ReadAsStringAsync().Result;
    } while (body == "{\"status\":\"Running\"}");
  6. Add the following code to the end of the CreateIoTHub method. This code retrieves the keys of the IoT hub you created and prints them to the console:

    var listKeysUri = string.Format("{0}/resourceGroups/{1}/providers/Microsoft.Devices/IotHubs/{2}/IoTHubKeys/listkeys?api-version=2016-02-03", subscriptionId, rgName, iotHubName);
    var keysresults = client.PostAsync(listKeysUri, null).Result;
    Console.WriteLine("Keys: {0}", keysresults.Content.ReadAsStringAsync().Result);

Complete and run the application

You can now complete the application by calling the CreateIoTHub method before you build and run it.

  1. Add the following code to the end of the Main method:

  2. Click Build and then Build Solution. Correct any errors.

  3. Click Debug and then Start Debugging to run the application. It may take several minutes for the deployment to run.

  4. To verify that your application added the new IoT hub, visit the Azure portal and view your list of resources. Alternatively, use the Get-AzResource PowerShell cmdlet.


This example application adds an S1 Standard IoT Hub for which you are billed. When you are finished, you can delete the IoT hub through the Azure portal or by using the Remove-AzResource PowerShell cmdlet when you are finished.

Next steps

Now you have deployed an IoT hub using the resource provider REST API, you may want to explore further:

To learn more about developing for IoT Hub, see the following articles:

To further explore the capabilities of IoT Hub, see: