Azure App Service API Apps

The following is from Azure Developer Training lab for AZ-203

API Management overview

API Management (APIM) helps organizations publish APIs to external, partner, and internal developers to unlock the potential of their data and services. Businesses everywhere are looking to extend their operations as a digital platform, creating new channels, finding new customers and driving deeper engagement with existing ones. API Management provides the core competencies to ensure a successful API program through developer engagement, business insights, analytics, security, and protection. You can use Azure API Management to take any backend and launch a full-fledged API program based on it.

Overview

To use API Management, administrators create APIs. Each API consists of one or more operations, and each API can be added to one or more products.To use an API, developers subscribe to a product that contains that API, and then they can call the API’s operation, subject to any usage policies that maybe in effect. Common scenarios include:

  • Securing mobile infrastructure by gating access with API keys, preventing DOS attacks by using throttling, or using advanced security policies like JWT token validation.
  • Enabling ISV partner ecosystems by offering fast partner onboarding through the developer portal and building an API facade to   internal implementations that are not ripe for partner consumption.
  • Running an internal API program by offering a centralized location for the organization to communicate about the availability and latest changes to APIs, gating access based on organizational accounts, all based on a secured channel between the API gateway and the backend.

The system is made up of the following components:

  • The API gateway is the endpoint that:
    • Accepts API calls and routes them to your backends.
    • Verifies API keys, JWT tokens, certificates, and other credentials.
    • Enforces usage quotas and rate limits.
    • Transforms your API on the fly without code modifications.
    • Caches backend responses where set up.
    • Logs call metadata for analytics purposes.
  • The Azure portal is the administrative interface where you set up yourAPI program. Use it to:
    • Define or import API schema.
    • Package APIs into products.
    • Set up policies like quotas or transformations on the APIs.
    • Get insights from analytics.
    • Manage users.
  • The Developer portal serves as the main web presence for developers, where they can:
    • Read API documentation.
    • Try out an API via the interactive console.
    • Create an account and subscribe to get API keys.
    • Access analytics on their own usage.

 

APIs and operations

APIs are the foundation of an API Management service instance. Each API represents a set of operations available to developers. Each API contains a reference to the back-end service that implements the API, and its operations map to the operations implemented by the back-end service. Operations inAPI Management are highly configurable, with control over URL mapping, query and path parameters, request and response content, and operation response caching. Rate limit, quotas, and IP restriction policies can also be implemented at the API or individual operation level.

 

Products

Products are how APIs are surfaced to developers. Products in APIManagement have one or more APIs, and are configured with a title, description, and terms of use. Products can be Open or Protected. Protected products must be subscribed to before they can be used, while open product scan be used without a subscription. When a product is ready for use by developers, it can be published. Once it is published, it can be viewed (and in the case of protected products subscribed to) by developers. Subscription approval is configured at the product level and can either require administrator approval, or be auto-approved.

Groups are used to manage the visibility of products to developers. Products grant visibility to groups, and developers can view and subscribe to the products that are visible to the groups in which they belong.

 

Groups

Groups are used to manage the visibility of products to developers. APIManagement has the following immutable system groups:

  • Administrators – Azure subscription administrators are members of this group. Administrators manage API Management service instances, creating the APIs, operations, and products that are used by developers.
  • Developers – Authenticated developer portal users fall into this group.Developers are the customers that build applications using your APIs.Developers are granted access to the developer portal and build applications that call the operations of an API.
  • Guests – Unauthenticated developer portal users, such as prospective customers visiting the developer portal of an API Management instance fall into this group. They can be granted certain read-only access, such as the ability to view APIs but not call them.

In addition to these system groups, administrators can create custom groups or leverage external groups in associated Azure Active Directory tenants.Custom and external groups can be used alongside system groups in giving developers visibility and access to API products. For example, you could create one custom group for developers affiliated with a specific partner organization and allow them access to the APIs from a product containing relevant APIs only. A user can be a member of more than one group.

 

Developers

Developers represent the user accounts in an API Management service instance. Developers can be created or invited to join by administrators, or they can sign up from the Developer portal. Each developer is a member of one or more groups, and can subscribe to the products that grant visibility to those groups.

When developers subscribe to a product, they are granted the primary and secondary key for the product. This key is used when making calls into the product’s APIs.

 

Policies

Policies are a powerful capability of API Management that allow the Azure portal to change the behavior of the API through configuration. Policies are a collection of statements that are executed sequentially on the request or response of an API. Popular statements include format conversion from XML to JSON and call rate limiting to restrict the number of incoming calls from a developer, and many other policies are available.

Policy expressions can be used as attribute values or text values in any of theAPI Management policies, unless the policy specifies otherwise. Some policies such as the Control flow and Set variable policies are based on policy expressions. For more information, see Advanced policies and Policy expressions.

 

Developer portal

The developer portal is where developers can learn about your APIs, view and call operations, and subscribe to products. Prospective customers can visit the developer portal, view APIs and operations, and sign up. The URL for your developer portal is located on the dashboard in the Azure portal for your API Management service instance.

 

API Management terminology

  • Backend API – An HTTP service that implements your API and its operations.
  • Frontend API/APIM API – An APIM API does not host APIs, it creates facades for your APIs in order to customize the facade according to your needs without touching the back end API.
  • APIM product – a product contains one or more APIs as well as a usage quota and the terms of use. You can include a number of APIs and offer them to developers through the Developer portal.
  • APIM API operation – Each APIM API represents a set of operations available to developers. Each APIM API contains a reference to the backend service that implements the API, and its operations map to the operations implemented by the back end service.
  • Version – Sometimes you want to publish new or different API features to some users, while others want to stick with the API that currently works for them.
  • Revision – When your API is ready to go and starts to be used by developers, you usually need to take care in making changes to that API and at the same time not to disrupt callers of your API. It’s also useful to let developers know about the changes you made.
  • Developer portal – Your customers (developers) should use theDeveloper portal to access your APIs. The Developer portal can be customized.

 

Create an Azure API Management service instance

Azure API Management (APIM) helps organizations publish APIs to external, partner, and internal developers to unlock the potential of their data and services. API Management provides the core competencies to ensure a successful API program through developer engagement, business insights, analytics, security, and protection. APIM enables you to create and manage modern API gateways for existing backend services hosted anywhere.

 

Steps to create an APIM instance in the Azure Portal

It takes just a few steps to create a new APIM instance:

  1. Log in to the Azure portal at https://portal.azure.com.
  2. In the Azure portal, select Create a resource > Integration > APImanagement.
  3. In the API Management service window, enter settings.
  4. Setting Suggested value Description
    Name A unique name for your APIManagement service The name can’t be changed later.Service name is used to generate a default domain name in the form of{name}.azure-api.net. Service name is used to refer to the service and the corresponding Azure resource.
    Subscription Your subscription The subscription under which this new service instance will be created. You can select the subscription among the different Azure subscriptions that you have access to.
    Resource Group apim ResourceGroup You can select a new or existing resource.A resource group is a collection of resources that share lifecycle, permissions, and policies.
    Location West USA Select the geographic region near you.Only the availableAPI Management service regions appear in the drop-down list box.
    Organization name The name of your organization This name is used in a number of places, including the title of the developer portal and sender of notification emails.
    Administrator email admin@org.com Set email address to which all the notifications fromAPI Management will be sent.
    Pricing tier Developer Set Developer tier to evaluate the service.

    Note: The Developer tier is not for production use.

  5. Choose Create. This is a long running operation and could take up to 15minutes to complete. Selecting Pin to dashboard makes finding a newly created service easier.

 

Clean up resources

When no longer needed, you can remove the resource group and all related resources by following these steps:

  1. In the Azure portal, select All services.
  2. Input resource groups in the search box and click on the result.
  3. Find your resource group and click on it.
  4. Click Delete resource group.
  5. Confirm the deletion by inputting the name of your resource group.
  6. Click Delete.

 

Create a new API

The steps in this tutorial show how to use the Azure portal to add an API manually to the API Management (APIM) instance you created earlier. A common scenario when you would want to create a blank API and define it manually is when you want to mock the API.

 

Create an API

  1. Login to the Azure Portal and select the APIM instance you created earlier.
  2. Select APIs from under API MANAGEMENT.
  3. From the left menu, select + Add API.
  4. Select Blank API from the list.
  5. Enter settings for the API.
    Name Value Description
    Display name Blank API This name is displayed in theDeveloper portal.
    Web Service URL(optional) http://httpbin.org If you want to mock an API, you might not enter anything. In this case, we enterhttp://httpbin.org.This is a public testing service.
    URL scheme HTTPS In this case, even though the back end has non-secureHTTP access, we specify a secureHTTPS APIM access to the back end.

    This kind of scenario (HTTPS to HTTP) is called HTTPS termination. You might do it if yourAPI exists within a virtual network (where you know the access is secure even if HTTPS is not used).

    You might want to use “HTTPS termination” to save on some CPU cycles.

    URL suffix hbin The suffix is a name that identifies this specific API in thisAPIM instance. It has to be unique in this APIM instance.
    Products Unlimited Publish the API by associating the API with a product. If you want for the API to be published and be available to developers, add it to a product. You can do it during API creation or set it later.

    Products are associations of one or more APIs. You can include a number of APIs and offer them to developers through the developer portal.

    Developers must first subscribe to a product to get access to the API. When they subscribe, they get a subscription key that is good for any API in that product. If you created the APIM instance, you are an administrator already, so you are subscribed to every product by default.

    By default, each API Management instance comes with two sample products:Starter andUnlimited.

  6. Select Create.

At this point, you have no operations in APIM that map to the operations in your back-end API. If you call an operation that is exposed through the backend but not through the APIM, you get a 404.

Note: By default, when you add an API, even if it is connected to some back-end service, APIM will not expose any operations until you whitelist them. To whitelist an operation of your back-end service, create an APIM operation that maps to the back-end operation.

 

Add and test an operation

This section shows how to add a /get operation in order to map it to the back end http://httpbin.org/get operation.

Add an operation
  1. Select the API you created in the previous step.
  2. Click + Add Operation.
  3. In the URL, select GET and enter /get in the resource.
  4. Enter FetchData for Display name.
  5. Select Save.
Test an operation

Test the operation in the Azure portal. Alternatively, you can test it in theDeveloper portal.

  1. Select the Test tab.
  2. Select FetchData.
  3. Press Send.

The response that the http://httpbin.org/get operation generates appears.

 

Add and test a parameterized operation

This section shows how to add an operation that takes a parameter. In this case, we map the operation to http://httpbin.org/status/200.

Add the operation
  1. Select the API you created in the previous step.
  2. Click + Add Operation.
  3. In the URL, select GET and enter /status/{code} in the resource.Optionally, you can provide some information associated with this parameter. For example, enter Number for TYPE, 200 (default) forVALUES.
  4. Enter GetStatus for Display name.
  5. Select Save.
Test the operation

Test the operation in the Azure portal. Alternatively, you can test it in theDeveloper portal.

  1. Select the Test tab.
  2. Select GetStatus. By default the code value is set to 200. You can change it to test other values. For example, type 418.
  3. Press Send. The response that the “http://httpbin.org/status/200”operation generates appears.

 

Create and publish a product

In Azure API Management, a product contains one or more APIs as well as a usage quota and the terms of use. Once a product is published, developer scan subscribe to the product and begin to use the product’s APIs.

  1. Select Products in the menu on the left to display the Products page.
  2. Select + Add. When you add a product, you need to supply the following information:
    Name Description
    Display name The name as you want it to be shown in the Developer portal.
    Name A descriptive name of the product.
    Description The Description field allows you to provide detailed information about the product such as its purpose, the APIs it provides access to, and other useful information.
    State Press Published if you want to publish the product. Before theAPIs in a product can be called, the product must be published.By default new products are unpublished, and are visible only to the Administrators group.
    Requires subscription Check Require subscription if a user is required to subscribe to use the product.
    Requires approval Check Require approval if you want an administrator to review and accept or reject subscription attempts to this product. If the box is unchecked, subscription attempts are auto-approved.
    Subscription count limit To limit the count of multiple simultaneous subscriptions, enter the subscription limit.
    Legal terms You can include the terms of use for the product which subscribers must accept in order to use the product.
    APIs Products are associations of one or more APIs. You can include a number of APIs and offer them to developers through the developer portal. You can add an existingAPI during the product creation.You can add an API to the product later, either from theProducts Settings page or while creating an API.
  3. Select Create to create the new product.
Add more configurations

You can continue configuring the product after saving it by choosing the Settings tab. View/add subscribers to the product from the Subscriptions tab.Set visibility of a product for developers or guest from the Access control tab.

 

Add APIs to a product

Products are associations of one or more APIs. You can include a number ofAPIs and offer them to developers through the developer portal. You can add an existing API during the product creation. You can add an API to the product later, either from the Products Settings page or while creating anAPI.

Developers must first subscribe to a product to get access to the API. When they subscribe, they get a subscription key that is good for any API in that product. If you created the APIM instance, you are an administrator already, so you are subscribed to every product by default.

Add an API to an existing product

  1. From the Products tab, select a product.
  2. Navigate to the APIs tab.
  3. Click + Add.
  4. Choose an API and click Select.

Tip: You can create or update user’s subscription to a Product with custom subscription keys through REST API or PowerShell command.

 

 

Using Swagger API

Getting started with Swashbuckle

This section of the course focuses on Swashbuckle to generate Swagger objects in ASP.NET Core. There are three main components to Swashbuckle:

  • Swashbuckle.AspNetCore.Swagger: a Swagger object model and middleware to expose SwaggerDocument objects as JSON endpoints.
  • Swashbuckle.AspNetCore.SwaggerGen: a Swagger generator that builds SwaggerDocument objects directly from your routes, controllers, and models. It’s typically combined with the Swagger endpoint middleware to automatically expose Swagger JSON.
  • Swashbuckle.AspNetCore.SwaggerUI: an embedded version of the Swagger UI tool. It interprets Swagger JSON to build a rich, customizable experience for describing the Web API functionality. It includes built-in test harnesses for the public methods.

Package installation

Here’s how to install the Swashbuckle.AspNetCore package in Visual Studio:

  • From the Package Manager Console window:
    • Go to View > Other Windows > Package Manager Console
    • Navigate to the directory in which the TodoApi.csproj file exists
    • Execute the following command: Install-PackageSwashbuckle.AspNetCore
  • From the Manage NuGet Packages dialog:
    • Right-click the project in Solution Explorer > Manage NuGetPackages
    • Set the Package source to “nuget.org”
    • Enter “Swashbuckle.AspNetCore” in the search box
    • Select the “Swashbuckle.AspNetCore” package from the Browse ta band click Install

Add and configure Swagger middleware

Add the Swagger generator to the services collection in theStartup.ConfigureServices method:

public void ConfigureServices(IServiceCollection services) { services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList")); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); }

Import the following namespace to use the Info class:

using Swashbuckle.AspNetCore.Swagger;

In the Startup.Configure method, enable the middleware for serving the generated JSON document and the Swagger UI:

public void Configure(IApplicationBuilder app) { // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseMvc(); }

Launch the app, and navigate to http://localhost:<port>/swagger/v1/swagger.json. The generated document describing the endpoints appears as shown in Swagger specification (swagger.json).

The Swagger UI can be found at http://localhost:<port>/swagger. Explore the API via Swagger UI and incorporate it in other programs.

Tip: To serve the Swagger UI at the app’s root (http://localhost:<port>/), set the RoutePrefix property to an empty string:

app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); c.RoutePrefix = string.Empty; });

 

Documenting the object model – API info and description

The configuration action passed to the AddSwaggerGen method adds information such as the author, license, and description:

// Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "ToDo API", Description = "A simple example ASP.NET Core Web API", TermsOfService = "None", Contact = new Contact { Name = "Shayne Boyer", Email = string.Empty, Url = "https://twitter.com/spboyer" }, License = new License { Name = "Use under LICX", Url = "https://example.com/license" } }); });

The Swagger UI displays the version’s information:

 

Enabling XML comments

XML comments can be enabled in Visual Studio using the following approach:

  • Right-click the project in Solution Explorer and select Edit<project_name>.csproj.
  • Manually add the highlighted lines to the .csproj file:

    <PropertyGroup> <GenerateDocumentationFile>true</GenerateDocumentationFile> <NoWarn>$(NoWarn);1591</NoWarn> </PropertyGroup>

Enabling XML comments provides debug information for undocumented public types and members. Undocumented types and members are indicated by the warning message. For example, the following message indicates a violation of warning code 1591:

warning CS1591: Missing XML comment for publicly visible type or member ‘TodoController.GetAll()’

To suppress warnings project-wide, define a semicolon-delimited list of warning codes to ignore in the project file. Appending the warning codes to $(NoWarn); applies the C# default values too.
<PropertyGroup> <GenerateDocumentationFile>true</GenerateDocumentationFile> <NoWarn>$(NoWarn);1591</NoWarn> </PropertyGroup>

To suppress warnings only for specific members, enclose the code in #pragma warning preprocessor directives. This approach is useful for code that shouldn’t be exposed via the API docs. In the following example, warning code CS1591 is ignored for the entire Program class. Enforcement of the warning code is restored at the close of the class definition. Specify multiple warning codes with a comma-delimited list.

namespace TodoApi { #pragma warning disable CS1591 public class Program { public static void Main(string[] args) => BuildWebHost(args).Run(); public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } #pragma warning restore CS1591 }

Configure Swagger to use the generated XML file. For Linux or non-Windows operating systems, file names and paths can be case-sensitive. For example, a TodoApi.XML file is valid on Windows but not CentOS.

public void ConfigureServices(IServiceCollection services) { services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList")); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "ToDo API", Description = "A simple example ASP.NET Core Web API", TermsOfService = "None", Contact = new Contact { Name = "Shayne Boyer", Email = string.Empty, Url = "https://twitter.com/spboyer" }, License = new License { Name = "Use under LICX", Url = "https://example.com/license" } }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); }

In the preceding code, Reflection is used to build an XML file name matching that of the Web API project. The AppContext.BaseDirectoryproperty is used to construct a path to the XML file.

Adding triple-slash comments to an action enhances the Swagger UI by adding the description to the section header. Add a <summary> element above the Delete action:

/// <summary> /// Deletes a specific TodoItem. /// </summary> /// <param name="id"></param> [HttpDelete("{id}")] public IActionResult Delete(long id) { var todo = _context.TodoItems.Find(id); if (todo == null) { return NotFound(); } _context.TodoItems.Remove(todo); _context.SaveChanges(); return NoContent(); }

The Swagger UI displays the inner text of the preceding code’s <summary>element:

 

The UI is driven by the generated JSON schema:

"delete": { "tags": [ "Todo" ], "summary": "Deletes a specific TodoItem.", "operationId": "ApiTodoByIdDelete", "consumes": [], "produces": [], "parameters": [ { "name": "id", "in": "path", "description": "", "required": true, "type": "integer", "format": "int64" } ], "responses": { "200": { "description": "Success" } } }

 

Add a <remarks> element to the Create action method documentation. It supplements information specified in the <summary> element and provides a more robust Swagger UI. The <remarks> element content can consist of text, JSON, or XML.

 

/// <summary> /// Creates a TodoItem. /// </summary> /// <remarks> /// Sample request: /// /// POST /Todo /// { /// "id": 1, /// "name": "Item1", /// "isComplete": true /// } /// /// </remarks> /// <param name="item"></param> /// <returns>A newly created TodoItem</returns> /// <response code="201">Returns the newly created item</response> /// <response code="400">If the item is null</response> [HttpPost] [ProducesResponseType(201)] [ProducesResponseType(400)] public ActionResult<TodoItem> Create(TodoItem item) { _context.TodoItems.Add(item); _context.SaveChanges(); return CreatedAtRoute("GetTodo", new { id = item.Id }, item); }

Notice the UI enhancements with these additional comments:

 

Decorating the model with attributes

Decorate the model with attributes, found in theSystem.ComponentModel.DataAnnotations namespace, to help drive the Swagger UI components.

Add the [Required] attribute to the Name property of the TodoItemclass:

using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace TodoApi.Models { public class TodoItem { public long Id { get; set; } [Required] public string Name { get; set; } [DefaultValue(false)] public bool IsComplete { get; set; } } }

The presence of this attribute changes the UI behavior and alters the underlying JSON schema:

"definitions": { "TodoItem": { "required": [ "name" ], "type": "object", "properties": { "id": { "format": "int64", "type": "integer" }, "name": { "type": "string" }, "isComplete": { "default": false, "type": "boolean" } } } },

Add the [Produces(“application/json”)] attribute to the API controller. Its purpose is to declare that the controller’s actions support aresponse content type of application/json:

[Produces("application/json")] [Route("api/[controller]")] [ApiController] public class TodoController : ControllerBase { private readonly TodoContext _context;

The Response Content Type drop-down selects this content type as the default for the controller’s GET actions:

 

As the usage of data annotations in the Web API increases, the UI and API help pages become more descriptive and useful.

 

Describing response types

Consuming developers are most concerned with what’s returned—specifically response types and error codes (if not standard). The response types and error codes are denoted in the XML comments and data annotations.

The Create action returns an HTTP 201 status code on success. An HTTP 400 status code is returned when the posted request body is null. Without proper documentation in the Swagger UI, the consumer lacks knowledge of these expected outcomes. Fix that problem by adding the highlighted lines in the following example:

/// <summary> /// Creates a TodoItem. /// </summary> /// <remarks> /// Sample request: /// /// POST /Todo /// { /// "id": 1, /// "name": "Item1", /// "isComplete": true /// } /// /// </remarks> /// <param name="item"></param> /// <returns>A newly created TodoItem</returns> /// <response code="201">Returns the newly created item</response> /// <response code="400">If the item is null</response> [HttpPost] [ProducesResponseType(201)] [ProducesResponseType(400)] public ActionResult<TodoItem> Create(TodoItem item) { _context.TodoItems.Add(item); _context.SaveChanges(); return CreatedAtRoute("GetTodo", new { id = item.Id }, item); }

The Swagger UI now clearly documents the expected HTTP response codes:

 

References