Azure Sphere 公共 API 概述

Azure Sphere 公共 API 是一组服务终结点,支持用于创建和管理 Azure Sphere 资源(如租户、产品、部署和设备组)的 HTTP 操作。 Azure Sphere 公共 API 使用 REST (REpresentational State Transfer) HTTP 协议发送操作请求和响应。 操作响应中返回的数据采用 JSON (JavaScript 对象表示法) 格式。 Azure Sphere 公共 API 参考中介绍了可用的操作。

客户可能更喜欢使用 Azure Sphere 命令行接口 (CLI) 而不是公共 API 来执行资源管理任务。 CLI 通过抽象化公共 API 的大部分编程复杂性来简化操作请求和响应的发送和接收。 CLI 命令使用 Azure Sphere 公共 API 执行任务,但 CLI 命令的简单语法使它们更易于使用。

某些客户可能希望生成自己的用户界面 (UI) 来执行资源管理任务。 Azure Sphere 公共 API 可用于生成自定义 UI。 无法使用 Azure Sphere CLI 生成自定义 UI。

REST API 请求的组件

REST API 请求具有以下三个组件:

  1. 请求 URI,格式如下:

    VERB https://prod.core.sphere.azure.net/v{version}/{collection}/{id}…[{resourceId} | {collection}]

    参数:

    • 集合:一个或多个集合。 支持多个嵌套集合,因此相对路径可以包括 /collection/id/collection/id ...

      例子: /v2/tenants/{tenantId}/devices/{deviceId}/images

    • resourceId:特定资源的 ID,用于访问集合中的特定资源。

      例子: /v2/tenants/{tenantId}/devicegroups/{devicegroupid}

    • 版本:API 版本,用于标识 API 的版本。 每个 API 请求都应包含 API 版本,以避免随着 API 的发展而中断应用或服务。

      例子: /v2

  2. HTTP 请求消息标头字段:

    • 所需的 HTTP 方法 (也称为操作或谓词) ,它告知服务你请求的操作类型。
    • 指定 URI 和 HTTP 方法所需的其他标头字段。 具体来说,是一个授权标头,它提供一个持有者令牌,其中包含请求的客户端授权令牌。
  3. 用于支持 URI 和 HTTP 操作的可选 HTTP 请求消息正文字段。

    • 对于 HTTP POST 或 PUT 操作,正文应在 Content-Type 请求标头以及 application/json 中指定。

REST API 响应的组件

REST API 响应包含以下两个组件:

  1. HTTP 响应消息标头字段:

  2. 可选的 HTTP 响应消息正文字段:

    • 可以在 HTTP 响应正文中返回 MIME 编码的响应对象,例如来自返回数据的 GET 方法的响应。 这些对象始终以结构化 JSON 格式返回,如 Content-Type 响应标头所示。

请求身份验证

在发出有效请求之前,必须使用 Azure Sphere 公共 API 对应用程序或服务进行身份验证。 下表显示了一些可以进行身份验证的方式。

应用程序类型 描述 例子 身份验证机制
交互式客户端 基于 GUI 的客户端应用程序 枚举设备的 Windows 应用 Microsoft 身份验证库 (MSAL)
交互式 JavaScript 基于 GUI 的 JavaScript 应用程序 显示设备组部署的 AngularJS 单页应用。 MSAL
交互式 Web 基于 GUI 的 Web 应用程序 显示生成摘要的自定义 Web 仪表板 OAuth 2

注意

Azure Active Directory 平台 正在演变为 Microsoft 标识平台。 有关详细信息,请参阅 Azure Sphere 中的新增功能

身份验证库值

如果调用 Microsoft 身份验证库 (MSAL) 以获取用于身份验证的持有者令牌,则必须提供四个值:

  • Azure Sphere 客户端应用程序 ID: 0B1C8F7E-28D2-4378-97E2-7D7D63F7C87F 成功身份验证 ()
  • 用户的范围: https://sphere.azure.net/api/user_impersonation
  • Azure Sphere 租户 ID: 7d71c83c-ccdf-45b7-b3c9-9c41b94406d9
  • Azure Sphere API 终结点: https://prod.core.sphere.azure.net/

有关身份验证的详细信息,请参阅 Microsoft 身份验证库 (MSAL) 身份验证流

发出请求

使用 Azure Sphere 进行身份验证后,可以发出请求并接收响应。

下面的 C# 示例使用 HttpClient 类 发出请求。

namespace SpherePublicAPISample
{
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading;
    using System.Threading.Tasks;
    // You install the Microsoft.Identity.Client reference by using Nuget,
    // starting at https://www.nuget.org/packages/Microsoft.Identity.Client.
    // Follow the instructions to install using Package Manager.
    using Microsoft.Identity.Client;

    class Program
    {
        // Azure Sphere Public API resource URI
        private readonly List<string> Scopes = new List<string>() { "https://sphere.azure.net/api/user_impersonation" };

        // Azure Sphere Public API client application ID.
        private const string ClientApplicationId = "0b1c8f7e-28d2-4378-97e2-7d7d63f7c87f";

        // Azure Sphere Tenant ID.
        public const string Tenant = "7d71c83c-ccdf-45b7-b3c9-9c41b94406d9";

        // Azure Sphere Public API URI
        private static readonly Uri AzureSphereApiUri = new Uri("https://prod.core.sphere.azure.net/");

        // Program entry-point.
        // returns Zero on success, otherwise non-zero.
        private static int Main()
        {
            try
            {
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                Program program = new Program();

                program.ExecuteAsync(cancellationTokenSource.Token)
                    .GetAwaiter()
                    .GetResult();

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
                return -1;
            }
            return 0;
        } // end of main

        private async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            IPublicClientApplication publicClientApp = PublicClientApplicationBuilder
                .Create(ClientApplicationId)
                .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
                .WithRedirectUri("http://localhost")
                .Build();

            AuthenticationResult authResult = await publicClientApp.AcquireTokenInteractive(Scopes)
                .ExecuteAsync();

            string accessToken = authResult.AccessToken;

            // Call the Azure Sphere API to get tenants available to the authenticated user.
            string result = await GetAsync(accessToken, "v2/tenants", cancellationToken);

            Console.WriteLine(result);
        } // end of ExecuteAsync method

        private async Task<string> GetAsync(string accessToken, string relativeUrl, CancellationToken cancellationToken)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                Uri uri = new Uri(AzureSphereApiUri, relativeUrl);

                using (HttpResponseMessage response = await client.GetAsync(uri, cancellationToken))
                {
                    response.EnsureSuccessStatusCode();
                    return await response.Content.ReadAsStringAsync();
                }
            }
        } // end of GetAsync method

    } // end of class Program
}

接收响应

每个调用返回以下格式的 JSON 响应:

[{"Id":"{tenantId}","Name":"Contoso","Roles":null}]

Azure Sphere 公共 API 错误代码

Azure Sphere 公共 API 返回以下错误代码:

  • 400 - 错误的请求
  • 404 - 未找到
  • 409 - 冲突
  • 410 - 消失
  • 429 - 请求过多
  • 500 - 内部服务器错误

以下部分提供了有关处理错误的指南。 有关特定错误代码的详细信息,请参阅 RFC 7231

错误处理指南

4xx 错误: 格式不正确的请求可能会导致错误。 检查请求语法和传递的数据。

429 错误: 为了保护 Azure Sphere 服务免受分布式拒绝服务 (DDoS) 攻击,我们跟踪并限制对服务进行大量调用的设备、用户或租户。 429 错误消息指示设备、用户或租户在短时间内尝试调用 Azure Sphere 服务次数过多。 请稍候,然后再再次调用 Azure Sphere 服务。

500 个错误: 偶尔可能会出现暂时性服务器错误。 如果收到服务器错误,请重试请求几次,以查看错误是否消失。

CORS 支持

此版本不支持跨区域源共享 (CORS) 。