Overview of the Azure Sphere Public API

The Azure Sphere public API is a set of service endpoints that support HTTP operations for creating and managing Azure Sphere resources such as tenants, products, deployments, and device groups. The Azure Sphere public API uses the REST (REpresentational State Transfer) HTTP protocol to send operation requests and responses. The data returned in the operation response is formatted in JSON (JavaScript Object Notation). The available operations are documented in the Azure Sphere public API reference.

Customers may prefer to use the Azure Sphere command-line interface (CLI) instead of the public API to perform resource-management tasks. The CLI simplifies the sending and receiving of operation requests and responses by abstracting much of the programmatic complexity of the public API. The CLI commands use the Azure Sphere public API to perform tasks, but the simple syntax of the CLI commands make them much easier to use.

Some customers may want to build their own user interface (UI) to perform resource-management tasks. The Azure Sphere public API can be used to build a custom UI. It is not possible to build a custom UI with the Azure Sphere CLI.

Components of a REST API request

A REST API request has the following three components:

  1. The request URI, in the following form:

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

    Parameters:

    • collection: One or more collections. Multiple nested collections are supported, so relative paths can include /collection/id/collection/id …

      Example: /v2/tenants/{tenantId}/devices/{deviceId}/images

    • resourceId: The ID of a specific resource, which enables access to specific resources within a collection.

      Example: /v2/tenants/{tenantId}/devicegroups/{devicegroupid}

    • version: The API version, which identifies the version of the API. Every API request should include an api-version to avoid having your app or service break as APIs evolve.

      Example: /v2

  2. HTTP request message header fields:

    • A required HTTP method (also known as an operation or verb), which tells the service what type of operation you are requesting.
    • Additional header fields, as required by the specified URI and HTTP method. Specifically, an authorization header which provides a bearer token containing client authorization token for the request.
  3. Optional HTTP request message body fields to support the URI and HTTP operation.

    • For HTTP POST or PUT operations, the body should be specified in the Content-Type request header as well as application/json.

Components of a REST API response

A REST API response has the following two components:

  1. HTTP response message header fields:

  2. Optional HTTP response message body fields:

    • MIME-encoded response objects may be returned in the HTTP response body, such as a response from a GET method that is returning data. These objects are always returned in a structured JSON format, as indicated by the Content-Type response header.

Authentication of a request

Before you can make a valid request, your application or service must be authenticated with the Azure Sphere public API. The following table shows some of the ways you can authenticate.

Type of application Description Example Authentication mechanism
Interactive client-side GUI based client side application Windows app enumerating devices Microsoft Authentication Library (MSAL)
Interactive JavaScript GUI based JavaScript application AngularJS single page app displaying deployments for a device group. MSAL
Interactive web GUI based web application Custom Web dashboard displaying build summaries OAuth 2

Authentication library values

If you call the Active Directory Libraries to acquire a Bearer Token to use for authentication, you must supply four values:

  • Azure Sphere client application ID: 0b1c8f7e-28d2-4378-97e2-7d7d63f7c87f (required for successful authentication)
  • Scope for the user: https://sphere.azure.net/api/user_impersonation
  • Azure Sphere Tenant ID: 7d71c83c-ccdf-45b7-b3c9-9c41b94406d9
  • Azure Sphere API endpoint: https://prod.core.sphere.azure.net/

For more information about authentication, see Azure Active Directory Authentication Libraries and Authentication flows.

Make a request

After you have authenticated with Azure Sphere, you can make requests and receive responses.

The following C# example uses the HttpClient class to make a request.

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
}

Receive a response

Each call returns a JSON response in the following format:

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

Azure Sphere public API error codes

The Azure Sphere public API returns the following error codes:

  • 400 - Bad Request
  • 404 - Not Found
  • 409 - Conflict
  • 410 - Gone
  • 429 - Too Many Requests
  • 500 - Internal Server Error

Guidance for handling errors is provided in the following section. For detailed information on specific error codes, see RFC 7231.

Error-handling guidance

4xx errors: Malformed requests can lead to errors. Check your request syntax and the data being passed.

429 errors: To protect Azure Sphere services against distributed denial of service (DDoS) attacks, we track and throttle devices, users, or tenants that make large numbers of calls to our services. A 429 error message indicates that the device, user, or tenant tried to call Azure Sphere service too many times within a short period of time. Please wait before calling the Azure Sphere service again.

500 errors: Occasionally, transient server errors may occur. If you receive a server error, retry the request a few times to see if the error goes away.

CORS support

Cross-Region Origin Sharing (CORS) is not supported in this release.