Skip to content

Commit e6beb34

Browse files
authored
Merge pull request #211314 from w-azure/winona-hub-rest
Reconstructing article
2 parents 568892b + 7e03e51 commit e6beb34

File tree

6 files changed

+97
-130
lines changed

6 files changed

+97
-130
lines changed

articles/iot-hub/iot-hub-rm-rest.md

Lines changed: 80 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -13,158 +13,128 @@ ms.custom: devx-track-csharp
1313

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

16-
[!INCLUDE [iot-hub-resource-manager-selector](../../includes/iot-hub-resource-manager-selector.md)]
17-
18-
You can use the [IoT Hub resource provider REST API](/rest/api/iothub/iothubresource) 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.
16+
You can use the [IoT Hub Resource](/rest/api/iothub/iothubresource) REST API to create and manage Azure IoT hubs programmatically. This article shows you how to use the IoT Hub Resource to create an IoT hub using **Postman**. Alternatively, you can use **cURL**. If any of these REST commands fail, find help with the [IoT Hub API common error codes](/rest/api/iothub/common-error-codes).
1917

2018
[!INCLUDE [updated-for-az](../../includes/updated-for-az.md)]
2119

2220
## Prerequisites
2321

24-
* Visual Studio
22+
* [Azure PowerShell module](/powershell/azure/install-az-ps) or [Azure Cloud Shell](/azure/cloud-shell/overview)
2523

26-
* [Azure PowerShell module](/powershell/azure/install-az-ps)
24+
* [Postman](/rest/api/azure/#how-to-call-azure-rest-apis-with-postman) or [cURL](https://curl.se/)
2725

28-
[!INCLUDE [iot-hub-prepare-resource-manager](../../includes/iot-hub-prepare-resource-manager.md)]
26+
## Get an Azure access token
2927

30-
## Prepare your Visual Studio project
28+
1. In the Azure PowerShell cmdlet or Azure Cloud Shell, sign in and then retrieve a token with the following command. If you're using Cloud Shell you are already signed in, so skip this step.
3129

32-
1. In Visual Studio, create a Visual C# Windows Classic Desktop project using the **Console App (.NET Framework)** project template. Name the project **CreateIoTHubREST**.
30+
```azurecli-interactive
31+
az account get-access-token --resource https://management.azure.com
32+
```
33+
You should see a response in the console similar to this JSON (except the access token is long):
3334

34-
2. In Solution Explorer, right-click on your project and then click **Manage NuGet Packages**.
35+
```json
36+
{
37+
"accessToken": "eyJ ... pZA",
38+
"expiresOn": "2022-09-16 20:57:52.000000",
39+
"subscription": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
40+
"tenant": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
41+
"tokenType": "Bearer"
42+
}
43+
```
3544

36-
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.
45+
1. In a new **Postman** request, from the **Auth** tab, select the **Type** dropdown list and choose **Bearer Token**.
3746

38-
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.
39-
> [!IMPORTANT]
40-
> The [Microsoft.IdentityModel.Clients.ActiveDirectory](https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory) NuGet package and Azure AD Authentication Library (ADAL) have been deprecated. No new features have been added since June 30, 2020. We strongly encourage you to upgrade. For more information see the [migration guide](../active-directory/develop/msal-migration.md).
47+
:::image type="content" source="media/iot-hub-rm-rest/select-bearer-token.png" alt-text="Screenshot that shows how to select the Bearer Token type of authorization in **Postman**.":::
4148

42-
5. In Program.cs, replace the existing **using** statements with the following code:
49+
1. Paste the access token into the field labeled **Token**.
4350

44-
```csharp
45-
using System;
46-
using System.Net.Http;
47-
using System.Net.Http.Headers;
48-
using System.Text;
49-
using Microsoft.Azure.Management.ResourceManager;
50-
using Microsoft.Azure.Management.ResourceManager.Models;
51-
using Microsoft.IdentityModel.Clients.ActiveDirectory;
52-
using Newtonsoft.Json;
53-
using Microsoft.Rest;
54-
using System.Linq;
55-
using System.Threading;
56-
```
51+
Keep in mind the access token expires after 5-60 minutes, so you may need to generate another one.
5752

58-
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**.
53+
## Create an IoT hub
5954

60-
```csharp
61-
static string applicationId = "{Your ApplicationId}";
62-
static string subscriptionId = "{Your SubscriptionId}";
63-
static string tenantId = "{Your TenantId}";
64-
static string password = "{Your application Password}";
55+
1. Select the REST command dropdown list and choose the PUT command. Copy the URL below, replacing the values in the `{}` with your own values. The `{resourceName}` value is the name you'd like for your new IoT hub. Paste the URL into the field next to the PUT command.
6556

66-
static string rgName = "{Resource group name}";
67-
static string iotHubName = "{IoT Hub name including your initials}";
68-
```
57+
```rest
58+
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}?api-version=2021-04-12
59+
```
6960

70-
[!INCLUDE [iot-hub-pii-note-naming-hub](../../includes/iot-hub-pii-note-naming-hub.md)]
61+
:::image type="content" source="media/iot-hub-rm-rest/paste-put-command.png" alt-text="Screenshot that shows how to add a PUT command in Postman.":::
7162

72-
[!INCLUDE [iot-hub-get-access-token](../../includes/iot-hub-get-access-token.md)]
63+
See the [PUT command in the IoT Hub Resource](/rest/api/iothub/iot-hub-resource/create-or-update?tabs=HTTP).
7364

74-
## Use the resource provider REST API to create an IoT hub
65+
1. From the **Body** tab, select **raw** and **JSON** from the dropdown lists.
7566

76-
Use the [IoT Hub resource provider REST API](/rest/api/iothub/iothubresource) 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.
67+
:::image type="content" source="media/iot-hub-rm-rest/add-body-for-put.png" alt-text="Screenshot that shows how to add JSON to the body of your request in Postman.":::
7768

78-
1. Add the following method to Program.cs:
69+
1. Copy the following JSON, replacing values in `<>` with your own. Paste the JSON into the box in **Postman** on the **Body** tab. Make sure your IoT hub name matches the one in your PUT URL. Change the location to your location (the location assigned to your resource group).
7970

80-
```csharp
81-
static void CreateIoTHub(string token)
71+
```json
8272
{
83-
73+
"name": "<my-iot-hub>",
74+
"location": "<region>",
75+
"tags": {},
76+
"properties": {},
77+
"sku": {
78+
"name": "S1",
79+
"tier": "Standard",
80+
"capacity": 1
81+
}
8482
}
8583
```
8684

87-
2. Add the following code to the **CreateIoTHub** method. This code creates an **HttpClient** object with the authentication token in the headers:
85+
See the [PUT command in the IoT Hub Resource](/rest/api/iothub/iot-hub-resource/create-or-update?tabs=HTTP).
8886

89-
```csharp
90-
HttpClient client = new HttpClient();
91-
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
92-
```
87+
1. Select **Send** to send your request and create a new IoT hub. A successful request will return a **201 Created** response with a JSON printout of your IoT hub specifications. You can save your request if you're using **Postman**.
9388

94-
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](https://azure.microsoft.com/status/):
89+
## View an IoT hub
9590

96-
```csharp
97-
var description = new
98-
{
99-
name = iotHubName,
100-
location = "East US",
101-
sku = new
102-
{
103-
name = "S1",
104-
tier = "Standard",
105-
capacity = 1
106-
}
107-
};
108-
109-
var json = JsonConvert.SerializeObject(description, Formatting.Indented);
110-
```
91+
To see all the specifications of your new IoT hub, use a GET request. You can use the same URL that you used with the PUT request, but must erase the **Body** of that request (if not already blank) because a GET request can't have a body. Here's the GET request template:
11192

112-
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:
93+
```rest
94+
GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}?api-version=2018-04-01
95+
```
11396

114-
```csharp
115-
var content = new StringContent(JsonConvert.SerializeObject(description), Encoding.UTF8, "application/json");
116-
var requestUri = string.Format("https://management.azure.com/subscriptions/{0}/resourcegroups/{1}/providers/Microsoft.devices/IotHubs/{2}?api-version=2021-04-12", subscriptionId, rgName, iotHubName);
117-
var result = client.PutAsync(requestUri, content).Result;
97+
See the [GET command in the IoT Hub Resource](/rest/api/iothub/iot-hub-resource/get?tabs=HTTP).
11898

119-
if (!result.IsSuccessStatusCode)
120-
{
121-
Console.WriteLine("Failed {0}", result.Content.ReadAsStringAsync().Result);
122-
return;
123-
}
99+
## Update an IoT hub
124100

125-
var asyncStatusUri = result.Headers.GetValues("Azure-AsyncOperation").First();
126-
```
101+
Updating is as simple as using the same PUT request from when we created the IoT hub and editing the JSON body to contain parameters of your choosing. Edit the body of the request by adding a **tags** property, then run the PUT request.
127102

128-
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:
129-
130-
```csharp
131-
string body;
132-
do
133-
{
134-
Thread.Sleep(10000);
135-
HttpResponseMessage deploymentstatus = client.GetAsync(asyncStatusUri).Result;
136-
body = deploymentstatus.Content.ReadAsStringAsync().Result;
137-
} while (body == "{\"status\":\"Running\"}");
138-
```
139-
140-
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:
141-
142-
```csharp
143-
var listKeysUri = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Devices/IotHubs/{2}/IoTHubKeys/listkeys?api-version=2021-04-12", subscriptionId, rgName, iotHubName);
144-
var keysresults = client.PostAsync(listKeysUri, null).Result;
145-
146-
Console.WriteLine("Keys: {0}", keysresults.Content.ReadAsStringAsync().Result);
147-
```
103+
```json
104+
{
105+
"name": "<my-iot-hub>",
106+
"location": "westus2",
107+
"tags": {
108+
"Animal": "Cat"
109+
},
110+
"properties": {},
111+
"sku": {
112+
"name": "S1",
113+
"tier": "Standard",
114+
"capacity": 1
115+
}
116+
}
117+
```
148118

149-
## Complete and run the application
119+
```rest
120+
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}?api-version=2018-04-01
121+
```
150122

151-
You can now complete the application by calling the **CreateIoTHub** method before you build and run it.
123+
The response will show the new tag added in the console. Remember, you may need to refresh your access token if too much time has passed since the last time you generated one.
152124

153-
1. Add the following code to the end of the **Main** method:
125+
See the [PUT command in the IoT Hub Resource](/rest/api/iothub/iot-hub-resource/create-or-update?tabs=HTTP).
154126

155-
```csharp
156-
CreateIoTHub(token.AccessToken);
157-
Console.ReadLine();
158-
```
127+
Alternatively, use the [PATCH command in the IoT Hub Resource](/rest/api/iothub/iot-hub-resource/update?tabs=HTTP) to update tags.
159128

160-
2. Click **Build** and then **Build Solution**. Correct any errors.
129+
## Delete an IoT hub
161130

162-
3. Click **Debug** and then **Start Debugging** to run the application. It may take several minutes for the deployment to run.
131+
If you're only testing, you might want to clean up your resources and delete your new IoT hub, by sending a DELETE request. be sure to replace the values in `{}` with your own values. The `{resourceName}` value is the name of your IoT hub.
163132

164-
4. To verify that your application added the new IoT hub, visit the [Azure portal](https://portal.azure.com/) and view your list of resources. Alternatively, use the **Get-AzResource** PowerShell cmdlet.
133+
```rest
134+
DELETE https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}?api-version=2018-04-01
135+
```
165136

166-
> [!NOTE]
167-
> 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](https://portal.azure.com/) or by using the **Remove-AzResource** PowerShell cmdlet when you are finished.
137+
See the [DELETE command in the IoT Hub Resource](/rest/api/iothub/iot-hub-resource/delete?tabs=HTTP).
168138

169139
## Next steps
170140

@@ -182,4 +152,4 @@ To learn more about developing for IoT Hub, see the following articles:
182152

183153
To further explore the capabilities of IoT Hub, see:
184154

185-
* [Deploying AI to edge devices with Azure IoT Edge](../iot-edge/quickstart-linux.md)
155+
* [Deploying AI to edge devices with Azure IoT Edge](../iot-edge/quickstart-linux.md)
73.7 KB
Loading
57.5 KB
Loading
75.2 KB
Loading

includes/iot-hub-prepare-resource-manager.md

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ You must authenticate all the operations that you perform on resources using the
1010

1111
Install the [Azure PowerShell cmdlets][lnk-powershell-install] before you continue.
1212

13-
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.
13+
The following steps show how to set up authentication for your app to register with Azure Active Directory. You can run these commands in a standard PowerShell session. Registering with Azure Active Directory is necessary to authenticate any future REST calls. For more information, see [How and why applications are added to Azure AD](/azure/active-directory/develop/active-directory-how-applications-are-added).
1414

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

@@ -26,47 +26,44 @@ The following steps show how to set up password authentication for an AD applica
2626
Get-AzSubscription
2727
```
2828

29-
Select the subscription you want to use. You can use either the subscription name or ID from the output of the previous command.
29+
Select the subscription you want to use. You can use either the subscription name or `Id` from the output of the previous command.
3030

3131
```powershell
32-
Select-AzSubscription -SubscriptionName "{your subscription name}"
32+
Select-AzSubscription -SubscriptionName "{your-subscription-name}"
3333
```
3434

35-
1. Save your **Id** and **TenantId** for later.
35+
1. Save your `Id` and `TenantId` for later.
3636

37-
1. Create a new Azure Active Directory application using the following command, replacing the placeholders:
37+
1. Create a new Azure Active Directory application using the following command, replacing these placeholders with your own values:
3838

3939
* **{Display name}:** a display name for your application such as **MySampleApp**
40-
* **{Home page URL}:** the URL of the home page of your app such as **http:\//mysampleapp/home**. This URL doesn't need to point to a real application.
41-
* **{Application identifier}:** A unique identifier such as **http:\//mysampleapp**. This URL doesn't need to point to a real application.
42-
* **{Password}:** A password that you use to authenticate with your app.
40+
* **{Application identifier}:** A unique identifier such as your primary domain. To find the primary domain associated with your subscription, go to the [Azure portal](https://ms.portal.azure.com/#home) in the **Azure Active Directory** service on its **Overview page** and find **Primary domain**. See the different domain possibilities in the [Azure Active Directory app manifest](/azure/active-directory/develop/reference-app-manifest#identifieruris-attribute). Be sure to add `/your-id` at the end of your domain (`your-Id` can be any name), for example, `"https://microsoft.onmicrosoft.com/my-unique-ad-app"`.
41+
42+
:::image type="content" source="/includes/media/iot-hub-prepare-resource-manager/find-domain.png" alt-text="Screenshot showing location of your Primary domain in the Azure portal.":::
4343

4444
```powershell
45-
$SecurePassword=ConvertTo-SecureString {password} -asplaintext -force
46-
New-AzADApplication -DisplayName {Display name} -HomePage {Home page URL} -IdentifierUris {Application identifier} -Password $SecurePassword
45+
$myApp = New-AzADApplication -DisplayName "<your-display-name>" -IdentifierUris "<your-domain>/<your-id>"
46+
New-AzADServicePrincipal -AppId $myApp.AppId
4747
```
48-
1. Save the **ApplicationId** of the application you created for later.
48+
A confirmation of your `Display name`, `Id`, and `AppId` will print to the console.
4949
50-
1. Create a new service principal using the following command, replacing **{MyApplicationId}** with the **ApplicationId** from the previous step:
51-
52-
```powershell
53-
New-AzADServicePrincipal -ApplicationId {MyApplicationId}
54-
```
50+
1. Save the **AppId** of the application you created for later.
5551
56-
1. Set up a role assignment using the following command, replacing **{MyApplicationId}** with your **ApplicationId**.
52+
1. Set up a role assignment authorization using the following command, replacing **{MyAppId}** with your **AppId**.
5753
5854
```powershell
59-
New-AzRoleAssignment -RoleDefinitionName Owner -ServicePrincipalName {MyApplicationId}
55+
New-AzRoleAssignment -RoleDefinitionName "Owner" -ApplicationId {MyAppId}
6056
```
6157
58+
To understand roles and permissions, see [Create or update Azure custom roles using Azure PowerShell](/azure/role-based-access-control/custom-roles-powershell).
59+
6260
With your new Azure AD application, you can now authenticate from your custom C# application.
6361
6462
You need the following values later in this tutorial:
6563
6664
* TenantId
6765
* SubscriptionId
68-
* ApplicationId
69-
* Password
66+
* AppId
7067
7168
[lnk-authenticate-arm]: /rest/api/
7269
[lnk-powershell-install]: /powershell/azure/install-az-ps
32.5 KB
Loading

0 commit comments

Comments
 (0)