APIM – Challenges Guide

Check that you have everything ready to do the workshop

Please check that you have the following requirements to complete the hands-on lab:

  • Azure requirements
    • Access to the Azure Portal
    • Access to an active Azure subscription
    • Contributor role in a resource group to be able to deploy an API Management instance
  • During part 3 of this lab, we will add existing APIs to our API Management instance. The following APIs/websites should be available:
  • For part 8 you need to have access to a valid Azure DevOps organization.

Create an API Management instance

Due to the substantial infrastructure, an API Management instance can take some time to provision. Expect ~45-75 minutes. 

Deploy to Azure

Using either your own or Azure’s common naming convention, fill in each required field and press Review + Create, followed by Create to provision the service.

Please bear in mind that this APIM instance is entirely intended for the purposes of the lab, and the approach is simplified to provide every lab participant a common starting point. To that end, please do not modify any settings beyond the ones we ask for here as it may result in having to recreate the APIM instance later, which is costly with respect to time.

Once started, it is not necessary to remain on this page or in the Azure Portal. If you entered a valid email address, you will receive a provisioning completion email.

Please note that the service name must be unique. We recommend to include your initials and numeric date.

Take note of APIM service name as you will need it for forming URLs in this lab.

Please use the Developer tier, which provides all relevant features at the lowest cost.

APIM deploy blade

Please do not modify other settings. Specifically, the Virtual network tab should remain as None. We will allude to best practices for securing access to APIM later on in this workshop.

APIM deploy blade Virtual Network tab

Verifying the API Management instance

Once the APIM instance has been created, please verify that it functions correctly by following these steps:

1) Navigate to the newly-created APIM instance in the Azure Portal.
2) Select the APIs blade, then select the Echo API.
3) Press the Test tab, then select the GET Retrieve resource operation.
4) Press Send to issue a simple request.

APIM Echo API Test Send

5) Observe the 200 Success response.

APIM Echo API Test Success

At this time you have successfully verified that APIM is set up!

Verification Failure (and Path to Success)

You may have noticed the Request URL and may be tempted to put it in your browser, issue a CURL statement, etc. If you do, you may see a 401 error and wonder what’s happening.

APIM Echo API Test 401

The reason for this the unauthorized access status code is that the Echo API requires a subscription key to be set. Whereas tests originating in APIM account for this automatically, external callers cannot (and, naturally, should not).

Back in APIM, switch to the Settings tab and uncheck Subscription required and press Save at the bottom of the page.

Subscriptions are important and useful, but in this case, we just want to quickly verify the APIM instance is working as intended.

APIM Echo API Disable Required Subscription

Accessing the link in your browser should now show you no error message. In fact, in order to verify the 200, it’s easiest to open your Developer Tools (F12), navigate to the Network tab, and look at All requests to see the 200.

APIM Echo API Browser Success

Alternatively, you can issue a verbose (-v) CURL command against the Echo API and observe the 200 Success: curl -v https://<your apim instance>.azure-api.net/echo/resource?param1=sample

APIM Echo API Curl Success

Hands-On lab

 

Exercise 1: Developer Portal

Duration: 20 minutes

The Developer Portal is an automatically generated, fully customizable website with the documentation of your APIs. It is where API consumers can discover your APIs, learn how to use them, request access, and try them out.

TABLE OF CONTENTS

  • Publishing Developer Portal
  • Customizing Developer Portal
  • Product Management

Task 1 – Publishing the Developer Portal

The APIM Developer Portal uses role-based access control (RBAC). After creating the APIM instance, you need to first access the Developer Portal using the admin role, which will trigger its activation.

  • Click the Developer portal link in the Overview blade of the APIM instance:

    APIM Developer Portal

    APIM Developer Portal Admin Launch

  • You can now proceed with publishing the Developer Portal to allow anonymous and authenticated roles. Back in the Azure Portal, locate Developer Portal in the left-hand resource menu, then click on Portal overview. Press the Publish button and confirm with Yes in the popup. The portal will then be available for users to access.

    APIM Developer Portal Publish

  • You will see confirmation once the Developer Portal has been published.

    APIM Developer Portal Published


Enabling CORS for the Developer Portal

Cross-origin resource sharing (CORS) is a mechanism that allows resources on a web page to be requested from another domain, outside the domain from which the first resource was served. CORS is required to let portal visitors use the interactive console in the API reference pages and should be enabled for domains, including custom domains.

  • CORS is enabled by using policies. We will go deeper on this topic in part 4. For now we will enable this using a built-in UI by pressing the Enable CORS button.

    APIM Developer Portal Enable CORS

    APIM Developer Portal CORS Enabled


User Experience

Let’s experience how your users will navigate through your portal. In order to do this, we recommend opening a private tab in your browser or using another browser to avoid seeing the admin/edit version of the portal.

  • Navigate to https://{apim-service-name}.developer.azure-api.net.

    Keep this browser session open as we will use it frequently throughout our labs.

    APIM Developer Portal Unauthenticated Launch

Anonymous User

  • As an unauthenticated user, have a look around the portal by checking out the APIs and products.

    Notice the difference between the Starter & Unlimited products.

    APIM Developer Portal Products

  • Check out the APIs. As you can see, all operations exposed are described and can also be tested directly within the portal.

    APIM Developer Portal APIs

Register for an account

  • Let’s sign up for an account by pressing the Sign up link in the upper right-hand corner. The email can be your personal or a work email for this lab.

    APIM Developer Portal Sign-up

  • Check your inbox for the acceptance email and confirm to activate your account.

    APIM Developer Portal Sign-up Email

Sign into account

  • Back in the private browser, sign in with your new credentials.

    APIM Developer Portal Sign-in

  • Click on Products, then Starter.
  • Enter Starter as the subscription name, then press Subscribe. You should receive a confirmation email shortly.

    APIM Developer Portal Product Subscribe

  • Next, click back on Products, then Unlimited.
  • Enter Unlimited as the subscription name, then press Subscribe.

    Note that the Unlimited subscription requires admin approval.

  • You should receive an email confirming your subscription request.

Approving Subscriptions

  • Back in the Azure Portal, navigate to the Subscriptions blade to see the two new subscriptions that were just added.

    APIM Subscriptions

  • Enter the menu for the submitted Unlimited subscription, then press Activate subscription. – Provide additional comments, if you like, then confirm the activation. By default, this will send an activation confirmation email to the user.

    APIM Activate Subscription

  • Back in the private browser, refresh the profile page to see the activated Unlimited subscription.

    APIM Subscription Activated

Try an API

It’s now time to test one of the published APIs.

  • Open the APIs page and look at the Echo API:
    • Notice the developer information
    • Test the Echo API using the POST verb by pressing Try it, using the defaults, then pressing Send at the bottom. You should see a successful 200 response.

    APIM Developer Portal Try API

    APIM Developer Portal Try API

 

Task 2 – Customizing the Developer Portal

Site Configuration

The Developer Portal is based on a fork of the Paperbits Web framework and is enriched with API Management-specific features. The fork resides at https://github.com/Azure/api-management-developer-portal.

It is possible to self-host and manage your own Developer Portal outside of an API Management instance. This is an advanced option, which allows you to edit the portal’s codebase and extend the provided core functionality. This is documented at https://github.com/Azure/api-management-developer-portal/wiki and https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-developer-portal.

Before you make your portal available to visitors, you should personalize the automatically-generated content. Recommended changes include the layouts, styles, and the content of the home page. This is documented at https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-developer-portal-customize.

A video on customization is available at https://www.youtube.com/watch?v=5mMtUSmfUlw.

APIM Developer Portal Config

APIM Developer Portal Config

APIM Developer Portal Styles

Email Configuration

The templates for the email notifications are managed from the Azure Management Portal, directly on the blade’s resource menu.

Look at the available notifications and notifications templates which are customizable.

APIM Notifications

APIM Notification Templates

APIM Notification Template Edit

 

Task 3 – Product Management

A product contains one or more APIs as well as a usage quota and the terms of use. Once a product is published, developers can subscribe to the product and begin to use the product’s APIs.

Product definition

  • In the Azure Portal, open the resource menu item Products.

    APIM Products

  • Let’s add a new product tier called Gold Tier.

    APIM Add Product

    APIM Add Product

  • Next, we’ll change the access control by clicking on Gold Tier and selecting Access control in the left pane.

    APIM Add Product Access

    Press Add group, check Developers and Guests, then press Select. The two added roles are shown now.

    APIM Add Product Access

    Back in the private browsing session, browse to Products and observe the new Gold Tier.

    APIM Developer Portal Added Product

Exercise 2 – API Management

Duration: 25 minutes

An API represents a set of operations that can be invoked. New APIs are defined, and then the desired operations are added. An API is added to a product and can be published; it may then be subscribed to and used by developers.

TABLE OF CONTENTS

  • Add API from scratch
  • Import API using swagger
  • Calling Apis

Task 1: Add API from scratch

  • On the left menu, open the APIs blade. You will see all APIs, the possibility to add new ones, but also to customize existing ones.

    APIM APIs

Add API from Scratch

Instead of developing an API, for this lab you will use the existing Star Wars API:

1) Click on Add API.
2) Click on HTTP – Manually define an HTTP API.
3) Select the Full option in the Create an HTTP API dialog.
4) Enter Display nameName, and Description.
5) Assign https://swapi.dev/api to the Web service URL.
6) Keep the URL scheme at HTTPS as we strive to enforce HTTPS only.
7) Set the API URL suffix to sw. This allows us to compartmentalize the APIM URLs for distinct APIs.
8) Assign Starter and Unlimited products.
9) Press Create.

While it is conventionally a good idea to version APIs from the onset, we are omitting this step here for brevity of the labs.

APIM Add Blank API

  • Once created, inside the Star Wars API press + Add operation to declare two new operations:

    1) GetPeople

    • Display name: GetPeople
    • Name: getpeople
    • URL: GET /people/

    2) GetPeopleById

    • Display name: GetPeopleById
    • Name: getpeoplebyid
    • URL: GET /people/{id}/

    APIM Star Wars API Add Operation

Access Star Wars API from Developer Portal

  • Switch now to the Developer Portal and sign in as a developer with a subscription.
  • Select Explore APIs. You should see both Echo API and Star Wars.

    APIM Developer Portal Echo & Star Wars APIs

  • Click on Star Wars. Try the GetPeople operation. Observe a successful 200 response.

    APIM Developer Portal Star Wars Try It

  • Now try the GetPeopleById operation with id = 2

    APIM Developer Portal Star Wars Try It

  • Examine the successful 200 response with C-3PO’s details in the response body payload.

    APIM Developer Portal Star Wars Try It

  •  

Task 2: Import API using swagger

Import API using OpenAPI

Instead of importing operations one-by-one, you can also import a full API. The OpenAPI specification (aka Swagger) is a definition format to describe RESTful APIs. The specification creates a RESTful interface for easily developing and consuming an API by effectively mapping all the resources and operations associated with it.

As a demo we will use an API that offers a simple calculator service : Calc API

APIM Calculator API

1) On the left menu, open the APIs blade.
2) Under Create from definition select OpenAPI.
3) Select the Full option in the Create from OpenAPI specification dialog.
4) Enter http://calcapi.cloudapp.net/calcapi.json as the OpenAPI specification value. You should subsequently see Display nameName, and Description populate.
> Note the intentional use of http instead of https as this backend does not presently support https.
5) While the backend service only runs on HTTP, we need to set URL scheme to Both to allow for APIM ingress to occur on HTTPS for callers such as the Developer Portal.
6) Set the API URL suffix to calc.
7) Assign Starter and Unlimited products.
8) Press Create.

APIM Add Calculator API

  • Once the API is created, it will show in the list of APIs along with all of its operations.

    APIM Add Calculator API

  • Back in the Developer Portal, try out the Calculator API via the Add two integers GET method, then examine the response.

    Accepting the defaults of 49 and 51 suffices. There’s presently an issue where defaults are shown in a dropdown. If you wanted to change the values, add new a and b parameters and values, then remove the dropdown values.

APIM Developer Portal Calculator API Try It

We can inspect / edit the Open API definition by selecting the Edit icon from the Frontend block:

APIM Calculator API Swagger

APIM Calculator API Swagger


Troubleshooting

Unable to complete the request

This is likely a mixed-content CORS error in which you are attempting a call to an APIM endpoint that is only set up for HTTP. It fails as the Developer Portal runs on HTTPS. Please check the setup steps above for the URL scheme.

APIM Calculator CORS Error

Task 3: Calling APIs

Calling API and testing Subscription Keys

Let’s add another API, the Color API.

APIM Color API

  • Create a new API with OpenAPI specification and import swagger from https://markcolorapi.azurewebsites.net/swagger/v1/swagger.json.
  • Use the API URL suffix color.

    APIM Add Color API

    APIM Add Color API

  • We can test the newly-added API from the Test tab. Note the successful 200 response.

    APIM Test Color API

  • Products can be configured after the API is initially created as well. On the Settings tab, set Products to include Starter and Unlimited, then press Save.

    APIM Color API Add Products

  • Switch to the Developer portal and look at the Color API.
  • Try the ApiRandomColorGet operation.
  • Notice the successful 200 response and the returned random color.

    APIM Developer Portal Color API Try It

    APIM Developer Portal Color API Try It

Rate limit

API Management uses rate limiting to protect APIs from being overwhelmed and helps prevent exposure to DDoS attacks. As APIM sits in between your API and their callers, it effectively governs access to your APIs.

We are going to use the Color website to demonstrate how rate limiting is applied. The website displays 500 lights. Each light will randomly make a call to the RandomColor API and then apply the returned color to the lights.

Color Website

First, we need to enable CORS for the domain name of the frontend. To achieve this we have to do the following in APIM:

  • On the sidemenu, click on APIs, then select the All APIs option.
  • Inside the Inbound processing area you will see the cors policy, which we added in part 2 by pressing the Enable Cors button.
  • Click on the pencil icon next to that policy to edit it.

    APIM Policy CORS All APIs

  • Here we will see this form where we can add the domain name of our frontend https://markcolorweb.azurewebsites.net or the * for all domains. Press Add allowed origin, enter the URL, then press Save.

    APIM Policy CORS All APIs

  • After enabling CORS in APIM lets go back to our frontend https://markcolorweb.azurewebsites.net and follow these steps:

  • Click on the hamburger menu next to Colors in the top left corner.
  • Click on Config.
  • Replace the API URL according to this format: https://YOURAPIM.azure-api.net/color/api/randomcolor
  • After setting the API URL correctly, press the hamburger menu again and go to Home.
  • Press Start to see how the frontend is calling the api. You should see a 401 response, indicating an auth error. This happens as our API requires a subscription, but we have not yet entered a subscription key.

    Color Website APIM 401

  • The subscription keys can be fetched from the Developer Portal. Open the main Developer Portal page, then click on Profile in the top menu.
  • Copy the following URL into Notepad, modify your APIM instance, then copy the URL, so that you have two of the same URLs. We will use them for the Starter and Unlimited pathways into APIM.
    • https://YOURAPIM.azure-api.net/color/api/RandomColor?key=
  • Append the primary keys for both subscriptions – one key per URL – to get unique URLs for Starter and Unlimited.

    Notepad Color API Subscription Keys

  • To see that Unlimited product has no rate limits:
    • Configure the Color website to use the Unlimited URL.
    • Select [Start].
    • Notice there is no rate limit – every light is randomly and continuously updated.

      Color Website APIM Unlimited Product

  • To see that Starter product is limited to 5 calls per minute:
    • Configure the Color website to use the Starter URL.
    • Select [Start].
    • Notice that only 5 lights get colored.

      Color Website APIM Starter Product

  • Try the same Starter URL directly in your web browser:
    • Notice the error status / message returned. For example: { "statusCode": 429, "message": "Rate limit is exceeded. Try again in 40 seconds." }

      APIM Color API URL in Browser for Starter Product 429

Exercise 3: Policy Expressions

Duration: 30 minutes

Policy Expressions are used to control traffic to and modify the behavior of the Backend API.

Policies can be applied at multiple scopes and follow this hierarchy. It is important to understand at what level to apply policy to appropriately yield security, robustness, and flexibility.

APIM Policy Scopes

TABLE OF CONTENTS

Task 1: Getting Started

Getting Started – Frontend/Inbound/Outbound/Backend

Select an API (e.g. Color). Policy can be configured for Inbound processingBackend, and Outbound processing. Most commonly, policies are applied in the Inbound processing section. Select the pencil icon to visually edit any section or the </> code brackets to edit the underlying XML. The configuration can be scoped to the API (All operations) or to an individual operation.

The Frontend section allows for editing of the OpenAPI / Swagger definition.

APIM Policy Editor

Editing the Frontend:

  • If editing an operation, there is a choice of the Code View or Forms-based editor.
  • If editing an API, the only option is the Code View editor.
  • The Code View editor allows amendments to the OpenAPI / Swagger definition.

    APIM Frontend Code Editor

    APIM Frontend Form Editor

Editing Inbound processing / Outbound processing / Backend:

  • Using the Code Editor:

    APIM Inbound Code Editor

  • Using the Form Editor:

    APIM Inbound Processing

    APIM Inbound Form Editor

Task 2: CORS Policy 

Cross-origin resource sharing (CORS)

The cors policy adds cross-origin resource sharing (CORS) support to an operation or an API to allow cross-domain calls from browser-based clients.

We have already configured the cors policy for our APIs in labs 2 & 3. Below is the resulting XML:

APIM Policy CORS All APIs


    
        <cors allow-credentials="true">
            
                https://apim-sk-12212021.developer.azure-api.net
                https://markcolorweb.azurewebsites.net
            
            <allowed-methods preflight-result-max-age="300">
                *
            
            
                
*

            
            
                
*

            
        
    
    
        <forward-request />
    
    <outbound />
    <on-error />

Task 3: Caching Policy

Caching

API Management can be configured for response caching which can significantly reduce API latency, bandwidth consumption, and web service load for data that does not change frequently.

Using the Azure Management portal, navigate to the Color API and set a set a caching policy for the ApiRandomColor GET:

  • Press Add policy.

    APIM Adding Enable Caching

  • Select Cache responses.

    APIM Enable Caching

  • Set a caching duration of 15 seconds.

    Simple caching configuration is not yet implemented in the Azure Management portal. We shall see later how it can be done using policy expressions.

    APIM Cache Duration

  • Configure the Color website from lab 3 to use the Unlimited subscription URL.
  • Select Start.
  • Notice that for each 15 second period the same color is set.

    Color Website Caching

  • Looking at the ApiRandomColor GET API policies in the Code View, you’ll see the caching policy defined:

    
        
            <base />
            <cache-lookup vary-by-developer="false" vary-by-developer-groups="false" downstream-caching-type="none" />
        
        
            <base />
        
        
            <base />
            <cache-store duration="15" />
        
        
            <base />
        
    
    

Task 4: Transformation Policy

Color API

Transformation – replace string

The find-and-replace policy finds a substring in a request or response and replaces it with a different string.

  • Open the Color API, then open the ApiRandomColorGet operation.
  • Enter the Policy code editor in the Outbound processing section.
  • Place the cursor after the  element in the  section.
  • Press Show snippets, then select the Find and replace string in body transformation policy.

    APIM Policy Find & Replace

  • Fill in the from and to values accordingly:

    
        <base />
        <find-and-replace from="blue" to="yellow" />
        <cache-store duration="15" />
    
    

    APIM Policy Find & Replace

  • Save the policy, then invoke the API using the Unlimited subscription key.

    APIM Policy Find & Replace


Star Wars API

Transformation – conditional

Policies can be applied very granularly. In this example, you are modifying the Star Wars API to return a limited set of information if the caller is using the Starter subscription. Other products, such as the Unlimited subscription, will receive the full response.

The context variable that is implicitly available in every policy expression provides access to the Response and Product below.

  • Open the Star Wars API, then open the GetPeopleById operation.
  • Similarly to the Color API, add the outbound policy to conditionally change the response body.
    Note that the inbound Accept-Encoding header is set to deflate to ensure that the response body is not encoded as that causes the JSON parsing to fail.

    
        
            <base />
            <set-header name="Accept-Encoding" exists-action="override">
                deflate
            
        
        
            <base />
        
        
            <base />
                
                    <when condition="@(context.Response.StatusCode == 200 && context.Product.Name.Equals("Starter"))">
                        @{
                                var response = context.Response.Body.As();
    
                                foreach (var key in new [] {"hair_color", "skin_color", "eye_color", "gender"}) {
                                    response.Property(key).Remove();
                                }
    
                                return response.ToString();
                            }
                        
                    
                
            
        
            <base />
        
    
    
  • Test the API on the Test tab with id 1 and apply the appropriate Starter or Unlimited product scope. Examine the different responses.

  • With Starter product scope:

    APIM Policy Transform Starter Product

  • With Unlimited product scope. Notice the four properties in red that are not included in the Starter scope response.

    APIM Policy Transform Unlimited Product


Calculator API

Transformation – XML to JSON

A frequent requirement is to transform content, especially to maintain compatibility with legacy APIs. For this lab we are going back to the Calculator API that returned an XML response.

  • Add an outbound policy to the Add two integers operation on the Calculator API to transform the response body to JSON.

    
        <base />
        <xml-to-json kind="direct" apply="always" consider-accept-header="false" />
    
    
  • Test the API and examine the response. Note that it’s now JSON.

    APIM Policy Transform XML to JSON

Delete response headers

A frequent requirement is to remove headers, especially ones that return security-related or superfluous information.

  • Add an outbound policy to the same Calculator API operation to remove specific response headers.

    
        <base />
        <xml-to-json kind="direct" apply="always" consider-accept-header="false" />
        <set-header name="x-aspnet-version" exists-action="delete" />
        <set-header name="x-powered-by" exists-action="delete" />
    
    
  • Invoke the API and examine the response, which now no longer contains the two headers. See above screenshot for how it looked prior.

    APIM Policy Delete Response Header

Amend what’s passed to the backend

Query string parameters and headers can be easily modified prior to sending the request on to the backend.

  • Back in the same Calculator API operation, add inbound policies to modify the query string and headers.

    
        <base />
        <set-query-parameter name="x-product-name" exists-action="override">
            @(context.Product.Name)
        
        <set-header name="x-request-context-data" exists-action="override">
            @(context.Deployment.Region)
        
    
    
  • Test the call by using either the Starter or Unlimited product, then inspect the result on the Trace tab.

    APIM Policy Amend Backend Call

    APIM Policy Amend Backend Call

Task 5: Named Values 

Calculator API

Named Values collection

Named Values (aka Properties) are a collection of key/value pairs that are global to the service instance. These properties can be used to manage string constants across all API configurations and policies. Values can be expressions, secrets (encrypted by APIM), or Key Vault, which links to a corresponding secret in Azure Key Vault.

  • Open the Named values blade in the resource menu and press + Add.
  • Create the new property:
    • Name: TimeNow
    • Display name: TimeNow
    • Type: Plain
    • Value: @(DateTime.Now.ToString())

      APIM Named Values

  • Back in the APIs blade, open the Add two integers operation in the Calculator API.
  • Amend the set-header policy by clicking on the pencil icon.
  • Create a new header by pressing + Add header:
    • Name: x-request-received-time
    • Value: {{TimeNow}}
    • Action: override
  • The corresponding XML in the Code editor view should look like this:

    
        <base />
        <set-query-parameter name="x-product-name" exists-action="override">
            @(context.Product.Name)
        
        <set-header name="x-request-context-data" exists-action="override">
            @(context.Deployment.Region)
        
        <set-header name="x-request-received-time" exists-action="override">
            {{TimeNow}}
        
    
    
  • Test the operation by selecting the Starter or Unlimited product scope.
  • Examine the backend trace to find the added header with the evaluated named value:

    {
      "name": "x-request-received-time",
      "value": "12/30/2021 6:10:47 PM"
    }

Task 6: Mock Policy

Star Wars API

Mock responses

Mocking in APIM is a useful mechanism for API consumers to interact with APIs without waiting for the backend to be ready.

  • Open the Star Wars API and select + Add Operation
  • Create a new GET operation:
    • Display name: GetFilm
    • Name: getfilm
    • URL: /film
  • In the Responses configuration tab, press + Add response, return 200 OK with a representation with content type application/json and this sample data:

    {
      "count": 1,
      "films": [{ "title": "A New Hope", "release-date": "05/25/1977" }]
    }
    

    APIM Policy Mock Frontend

  • Open the Inbound processing ‘Code View’
  • Add Mock Response under Other policies after the ` tag.

    
        <base />
        <mock-response status-code="200" content-type="application/json" />
    
    

    APIM Policy Mock Inbound

  • Invoke the API to receive a 200 success with the mocked film data.

    APIM Policy Mock Response

Task 7: Send One Way Policy

Calculator API

APIM integrates well with external services via HTTP-based interaction.

This example shows a fire-and-forget send-one-way-request policy, which does not await a response. Alternatively, you can use a send-request policy to send a request and await a return. Some complex in-flight processing logic may also be better handled by using Logic Apps.

Send-One-Way-Request Setup

The following policy and payload applies for both examples in this lab. Please ensure that you replace the value in  with your webhook target URL. You will identify the URL in either example below.

  • Open the Calculator API ‘Code View’.
  • Add the send-one-way-request policy to Outbound processing and replace the webhook and payload as required. For demo purposes we are going to use the payload for a Teams message (even for Webhook.site) and also send the message on every successful request.

    
      <base />
      
        <when condition="@(context.Response.StatusCode == 200)">
          <send-one-way-request mode="new">
            
              https://enter-your-webhook-url
            
            POST
            @{
              return new JObject(
                new JProperty("@type","MessageCard"),
                new JProperty("@context", "http://schema.org/extensions"),
                new JProperty("summary","Summary"),
                new JProperty("themeColor", "0075FF"),
                new JProperty("sections",
                  new JArray (
                    new JObject (
                      new JProperty("text", "Hello!")
                    )
                  )
                )
              ).ToString();
            }
          
        
      
    
    

Send a message to Webhook.site

Webhook.site is a simple recipient to test webhook messages and requires no setup overhead, making this an ideal component in this lab, especially as we are not sending any sensitive information in our payload from our test APIM instance.

  • Go to Webhook.site and copy the value for Your unique URL.

    Webhook Site Setup

  • Use this URL as the value in the  property in the send-one-way-request policy.

  • Invoke the API from the APIM Test tab and observe the 200 success response.

  • Check the Trace for the Outbound one-way message.

    Webhook Site APIM Trace

  • Observe the success in the Webhook site.

    Webhook Site Success

Send a message to Microsoft Teams channel

An optional lab, for Microsoft Teams, please review Create an Incoming Webhook.

  • First, open Teams and enable a Webhook connector for your team.
    • Get the URL of the webhook.

      Teams Webhook

      Teams Webhook

      Teams Webhook

      Teams Webhook

  • Format the required payload. The payload sent to a Teams channel uses the MessageCard JSON schema. You can experiment with different cards in the MessageCard Playground.

  • Invoke the API from the Test tab and observe the 200 success response.

  • Look for a received message in your Teams channel:

    Teams APIM Message

Task 8: Abort processing Policy

Calculator API

Aborting the processing

The ability to terminate a response gracefully is of importance in a number of cases such as error handling or business logic. Using the return-response policies short-circuits the request and yields a response that often does not originate from the backend. Consider what general situations may make sense without shifting too much business logic into APIM.

  • Open the Calculator API ‘Code View’.
  • Add the inbound policy to test for a condition and return an error.
  • Invoke the API with the Authorization header as before.
  • Observe the 500 error.
  • Replace the condition with more meaningful code.

    
        <base />
        
            <when condition="@(true)">
                <return-response response-variable-name="existing response variable">
                    <set-status code="500" reason="Internal Server Error" />
                    <set-header name="failure" exists-action="override">
                        failure
                    
                    Internal Server Error
                
            
        
    
    

    APIM Policy Abort Response

    Clean Up

    Now that you have seen how to gracefully terminate a request with a response, it is time to clean up the code to prevent a downstream impact in subsequent labs. Please remove the  logic above to let all requests flow again, then save the changes.

Exercise 4: Versions and Revisions

Duration: 15 minutes

Versions and revisions provide you with elegant means to safely manage the lifecycle of your APIs.

Versions of APIs are differentiated by a version identifier (e.g. v1v2, etc.) through a versioning scheme such as a version path in the URL, a header, or a query string. Multiple versions can and may often be active at the same time to provide continued service while breaking changes may be introduced in newer versions.

Revisions allow you to safely make non-breaking changes to your API. Developers who consume the API can be given details about the changes. Revisions can safely be tested before being activated for your consumers. Revisions also allow you to rollback changes.

For more information, visit the Versions & Revisions documentation.

TABLE OF CONTENTS

Task 1: Versios

Version

Proper version management not only helps organize your API, it also aids in API Management. In this exercise we are going to version an existing API.

Integrate version management from the beginning with a v1 or similar identifier.

Add a new version

  • Select the Star Wars API.
  • Add a new version:
    • Version identifier: v2
    • Versioning scheme: Path
    • Full API version name: star-wars-v2

      This name must be unique across the APIM instance. Therefore, a combination of the API name and its version identifier is both semantic and suitable.

    • Products: Starter and Unlimited

      APIM Versions Add APIM Version Create

    • The new version, v2, is now added in the Star Wars API.

      Any previous implementation of the newly-versioned API will simply be set to Original. This is a purely organizational change within APIM. The version continues to operate on the same previous URL without a version identifier – there is no impact to the consumers.

      APIM Version Created

Test the new version

Sometimes, the version creation takes just a little bit of time. If you do not see it immediately, please keep refreshing and ensure you select the appropriate version as per below instructions.

  • Open the Developer Portal.
  • Select APIs and choose the v2 version of the Star Wars API.

    APIM Developer Portal Versions

  • Notice the request URL and the inclusion of v2 in the path.

    APIM Developer Portal Version 2

  • Test the GetPeople operation.

    APIM Developer Portal Test Version

What Versions Enable

Now that you have created a new version of the API, you have the ability to introduce breaking changes. Often times a breaking change in a backend API necessitates an API version change in APIM. Leaving a legacy implementation behind to focus on more contemporary API implementations also is a common versioning use case. Whatever the reason may be, APIM provides means to abstract breaking changes in a responsible and safe manner.

Task 2: Revision

Revisions

Add a new revision

  • Select the Star Wars API v2.
  • Select the Revisions tab.
  • Add a new revision with description Adding a caching policy.

    APIM Revisions Menu APIM Revision Create

    The new revision is online but not yet current. The previous revision continues to remain the active default. Having added the new revision has not resulted in change for your consumers.

    APIM Created Revision

Add caching

  • Select the GetPeople operation.

    Revision 2 automatically became the active revision you are now making changes in. You can also switch between revisions, but be aware that changes to the Current revisions are live immediately.

    APIM Revision Add Caching

  • Add a 10-second caching policy for the GET operation.

    APIM Revision Add Caching

Test the new revision

  • From the Azure portal, test the GetPeople operation.

    Note the revision number at the top of the page as well as in the request URL.
    The request URL should look similar to: https://.azure-api.net/sw/v2;rev=2/people/.

    APIM Revision Caching Test

  • Test the API twice. The test trace should then show that the cache-lookup occurred.

    APIM Revision Caching Test

Make current revision

  • Select the Revisions tab.
  • Make rev2 the current revision.

    APIM Revision Make Current

  • Choose to post to the public change log for the API and provide a meaningful update.

    APIM Revision Make Current

  • The new revision is now the current one. Note that the URL reflects the URL the consumer calls. The old revision is still online and can be accessed with the rev qualifier.

    Unlike versioning, revisioning requires no URL updates for the API consumer.

    APIM Revision Make Current

Exercise 5: Analytics and Monitoring

Task 1: Basic Monitoring with Azure Monitor

Analytics is available on the Analytics blade in APIM.

  • The dashboard has several tabs on it. For example, here are TimelineGeography, and APIs:

    APIM Azure Monitor Analytics

    APIM Azure Monitor Analytics

    APIM Azure Monitor Analytics

Task 2: Application Insights 

How to integrate Azure API Management with Azure Application Insights

Azure API Management allows for easy integration with Azure Application Insights – an extensible service for web developers building and managing apps on multiple platforms. This guide walks through every step of such an integration and describes strategies for reducing performance impact on your API Management instance.

Create an Azure Application Insights instance

Before you can use Azure Application Insights, you first need to create an instance of the service.

  1. Open the Azure portal and navigate to Application Insights.

    App Insights Create Instance

  2. Click + Create, then fill in the form. You may need to create a new Log Analytics Workspace if you don’t already have one.

    App Insights Create Instance

  3. Click Review + Create, followed by Create.

Create a connection between Azure Application Insights and Azure API Management service instance

  1. Navigate to your APIM instance in the Azure portal.
  2. Select Application Insights from the menu on the left.
  3. Click + Add.

    APIM App Insights Logger

  4. Select the previously created Application Insights instance and provide a short description.
  5. Click Create.
  6. You have just created an Azure Application Insights logger with an instrumentation key. It should now appear in the list.

    APIM App Insights Logger

    Behind the scenes, a Logger entity is created in your API Management instance, containing the Instrumentation Key of the Application Insights instance.

Enable Application Insights logging for your API

  1. Select APIs from the menu on the left.
  2. Click on the Color API.
  3. Go to the Settings tab from the top bar.
  4. Scroll down to the Diagnostics Logs section.
  5. On the Application Insights tab check the Enable box.
  6. In the Destination dropdown select the logger you just added in the Application Insights blade.
  7. Set sampling to 100 to capture all events.
  8. Check the Always log errors checkbox.

    APIM API App Insights Logger

  9. Click Save.

    Overriding the default value 0 in the Number of payload bytes to log field may significantly decrease the performance of your APIs.

    Behind the scenes, a Diagnostic entity named ‘applicationinsights’ is created at the API level.

What data is added to Azure Application Insights

Azure Application Insights receives:

  • Request telemetry item for every incoming request (frontend requestfrontend response),
  • Dependency telemetry item for every request forwarded to a backend service (backend requestbackend response),
  • Exception telemetry item, for every failed request.

A failed request is a request which:

  • failed because of a closed client connection, or
  • triggered an on-error section of the API policies, or
  • has a response HTTP status code matching 4xx or 5xx.

Generating Test Requests

Any request you make to the Color API in APIM will be subject to being received by Application Insights (recall the 100% sampling). To generate a large amount of requests quickly, you can invoke the API via the Color website. As we are presently caching the output for 15 seconds, you may get a lot of requests with the same color. Please feel free to disable the output caching in the Color API if you would like to see more variety.

Viewing Azure Application Insights Data

  • Go back to the Application Insights blade and click on the Application Insights instance.
  • In the Application Insights instance, you should be able to see logs and metrics after a few seconds.
  • Open the Transaction search to see details on a transactional level:

    APIM API App Insights Logger

Performance implications and log sampling

Logging all events may have serious performance implications, depending on incoming requests rate, payload size, etc.

Based on internal load tests, enabling this feature caused a 40%-50% reduction in throughput when request rate exceeded 1,000 requests per second. Azure Application Insights is designed to use statistical analysis for assessing application performances. It is not intended to be an audit system and is not suited for logging each individual request for high-volume APIs.

You can manipulate the number of requests being logged by adjusting the Sampling setting (see the steps above). 100% means all requests are logged, while 0% reflects no logging at all. Sampling helps to reduce the volume of telemetry, effectively preventing from significant performance degradation, while still carrying the benefits of logging. Sampling is an effective tool in diagnosing often general operational issues. For example, sampling can identify connectivity or integration issues as these would often occur in high quantity, not singular instances. A sampling rate of 50% is as effective in diagnosing such issues as 100% is.

Skipping logging of headers and body of requests and responses will also have positive impact on alleviating performance issues.

Task 3: Logging with Event Hub

Event Hub Overview

Azure Event Hubs is a fully managed, real-time data ingestion service. Millions of events per second can be aggregated to build dynamic data pipelines.

We can use Event Hubs with API Management to obtain analytics of our API usage.

Create an Event Hubs namespace

An Event Hubs namespace provides a unique scoping container in which you create one or more event hubs. To create a namespace in your resource group using the Azure portal, follow these steps:

  1. In the Azure portal select Create a resource at the top left of the screen.
  2. Search for Event Hubs, then click on the resource.
    If you cannot find it there, please try the same Event Hubs term in the top search bar.

    Select Event Hubs in Portal

  3. Press Create to create the namespace, then enter the following:
    1. Select the Resource Group you created in previous labs.
    2. Enter a unique Namespace name.
    3. Select the Location you used in previous labs.
    4. Choose Basic for the Pricing Tier. To learn about differences between tiers, see Quotas and limitsEvent Hubs Premium, and Event Hubs Dedicated articles.
    5. Leave the Throughput Units setting as it is. To learn more about throughput units or processing units: Event Hubs scalability.
    6. Select Review + Create at the bottom of the page, followed by Create.

      Create an Event Hub Namespace

    7. Press Go to resource.

      Event Hub Namespace Created

    8. Confirm that you see the Event Hubs Namespace page similar to the following example:

      Event Hub Namespace Home Page


Create an Event Hub

To create an event hub within the namespace, follow these steps:

  1. From the Event Hubs blade select + Event Hub>

    Add Event Hub

  2. Type a name for your event hub, then select Create.

    The partition count setting allows you to parallelize consumption across many consumers. For more information, see Partitions.

    The message retention setting specifies how long the Event Hubs service keeps data. For more information, see Event retention.

    Create Event Hub

  3. After the event hub is created, you see it in the list of event hubs.

    Event Hub Created

Create Access to the Event Hub

  1. Click on the newly-created event hub.
  2. Open the Shared access policies blade.
  3. Click on + Add.

    Event Hub Connection

  4. On the right side of your screen create a ´sendpolicy´ with just ´Send´ permissions

    Event Hub Send Policy

  5. Click on the new policy created and copy the Connection string-primary key to a notepad. Also copy the Event Hub namespace. You will use both values in the next section.

    Event Hub Connection


Create an API Management logger

Now that you have an Event Hub, the next step is to configure a Logger in your API Management service, so that it can log events to the Event Hub.

API Management loggers are configured using the API Management REST API. For this example we are going to use the “REST API Try it” Functionality to create the logger:

  1. Open the following link REST API Try It

    REST API Try It

  2. Press Sign in and use your Azure credentials that you have been using with this workshop, if prompted.
  3. Fill in the following Parameters:
    1. loggerId: eventhublogger
    2. resourceGroupName: your resource group
    3. serviceName: your Azure APIM instance
    4. subscriptionId: your Azure subscription

      RREST API Try It

  4. Replace the request Body with the following json. Make sure you replace the parameters appropriately:

     {
         "properties": {
             "loggerType": "azureEventHub",
             "description": "adding a new logger",
             "credentials": {
                 "name": "",
                 "connectionString": ""
             }
         }
     }
    
  5. Your request parameters might then look similar to this:

    Note my deviation by intential masking my SharedAccessKey. Please do not alter your key.

     {
         "properties": {
             "loggerType": "azureEventHub",
             "description": "adding a new logger",
             "credentials": {
                 "name": "eh-sjk-01062022/myeventhub",
                 "connectionString": "Endpoint=sb://eh-sjk-01062022.servicebus.windows.net/;SharedAccessKeyName=sendpolicy;SharedAccessKey=********;EntityPath=myeventhub"
             }
         }
     }
    
  6. Press Run.
  7. You should get a 201 response, confirming that the resource has been created.

    REST API Try It


Configure log-to-eventhub policies

Once your logger is configured in API Management, you can configure your log-to-eventhub policy to log the desired events. The log-to-eventhub policy can be used in either the inbound policy section or the outbound policy section.

  1. Browse to your APIM instance.
  2. Select the APIs blade.
  3. Select the API to which you want to add the policy.
    In this example, we’re adding a policy to the Echo API.
  4. Select All operations.
  5. On the top of the screen, select the Design tab.
  6. In the Inbound or Outbound processing window, enter the Code editor.
  7. Enter a new line after the  tag in the inbound or outbound policy section.
  8. Select Show snippets.
  9. In the window on the right, select Advanced policies > Log to EventHub. This inserts the log-to-eventhub policy statement template.

    APIM Add Log to Event Hub

  10. Replace the policy with this snippet:

     <log-to-eventhub logger-id="">
         @{
             return new JObject(
                 new JProperty("EventTime", DateTime.UtcNow.ToString()),
                 new JProperty("ServiceName", context.Deployment.ServiceName),
                 new JProperty("RequestId", context.RequestId),
                 new JProperty("RequestIp", context.Request.IpAddress),
                 new JProperty("OperationName", context.Operation.Name)
             ).ToString();
         }
     
    
  11. Replace  with the value you used for {loggerId} in the request URL to create the logger in the previous step (e.g. eventhublogger).

    You can use any expression that returns a string as the value for the log-to-eventhub element. In this example, a string in JSON format containing the date and time, service name, request ID, request IP address, and operation name is logged.

    APIM Add to Event Hub

  12. Click Save to save the updated policy configuration. As soon as it is saved the policy is active and events are logged to the designated Event Hub.

Verify Events are logged in Event Hub

  1. Issue a handful of test Echo API calls from within APIM (e.g. Get Retrieve Resource operation).
  2. In the Azure portal open the Event Hub you created earlier. You should see recent events. If not, give it a minute, then refresh.

    Event Hub APIM events

What to do with the data that is now in Event Hub is beyond the scope of this lab as this lab primarily focused on APIM to Event Hub integration.

Exercise 6: Security

Duration: 20 minutes

TABLE OF CONTENTS

Task 1: JSON Web Token Validation

In this lab, we are going to see how to use JSON Web Tokens with your APIs.

JSON Web Tokens (JWT) – Creation

JSON Web Tokens are an open-industry standard method for representing claims securely between two parties. More info at https://jwt.io.

Use the following sites:

  • https://www.unixtimestamp.com to get a future date using the Epoch Unix Timestamp at least one hour from the current time as the JWT will not work otherwise (e.g. 01/11/2029 = 1862842300)

  • https://jwt.io to create a JWT with payload. In the Decoded section make these changes:

    • Leave the Header as is.
    • Use the following Payload:

      {
        "sub": "1234567890",
        "name": "John Doe",
        "admin" : true,
        "exp": 1862842300
      }
      
    • In the Verify Signature area use a 256-bit key that will also be used in the APIM policy. We used 123412341234123412341234 as an example, which is a rather weak secret but serves the demo purpose.
    • Check secret base64 encoded.
    • Your configuration should be similar to this now:

      JWT.io Website

JSON Web Tokens (JWT) – Validation

  • Back in APIM, open the Calculator API and select All operations.
  • In the ‘Code View’ add an inbound validate-jwt policy with the signing key.

    
        
            <base />
            <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized">
                
                    123412341234123412341234
                
            
        
        ...
    
    
  • Invoke the Divide two integers method on the API from the Test tab. Observe the 401 Unauthorized error.

    APIM Request with no JWT

  • Now add the following Authorization header to the test:
    • Name: Authorization
    • Value: Bearer

    Note the bearer token in the Request payload.

    APIM Request Add Valid Authorization Header

  • Execute the test once more to see a 200 Success.

JSON Web Tokens (JWT) – Check that a Claim Exists

Not only is it important that a JWT is valid, but as we use it for authorization, we must also assert that the token contains expected claims before granting access to our APIs.

  • Open the Calculator API and select All operations.
  • Modify the inbound validate-jwt policy to not only validate the JWT but ensure that a specific admin claim exists. Recall that we set admintrue in our JWT token on https://jwt.io above.

    
        
            <base />
            <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized">
                
                    123412341234123412341234
                
                
                    <claim name="admin" match="any">
                        true
                    
                
            
        
        ...
    
    
  • Invoke the Divide two integers method with the Authorization header as above and observe the 200 success. We have not fundamentally changed the test scenario as we only restricted the claims to something that we already had in our payload.

  • Now change the required-claims with a claim that does not exist (e.g. adminx)

    
        
            <base />
            <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized">
                
                    123412341234123412341234
                
                
                    <claim name="adminx" match="any">
                        true
                    
                
            
        
        ...
    
    
  • Invoke the Divide two integers method with the Authorization header once more and observe the 401 Unauthorized error as the token specifies admin but the policy requires adminx.

JSON Web Tokens (JWT) – Extract Claim and Pass to Backend

It may often be necessary to pass (specific) claims onto the backend API to inform further processing. One such way – and this can be tailored to an API’s individuality – is to extract a claim and place it into a designated header the backend expects.

  • Open the Calculator API and select All operations.
  • Append the inbound policy section to extract the name claim and place it into a header underneath the validate-jwt policy.
  • Change the claim back from adminx to admin as we are interested in a successful test again.

    
        
            <base />
            <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized">
                
                    123412341234123412341234
                
                
                    <claim name="admin" match="any">
                        true
                    
                
            
            <set-header exists-action="override" name="username">
                @{
                    Jwt jwt;
                    context.Request.Headers.GetValueOrDefault("Authorization","scheme param").Split(' ').Last().TryParseJwt(out jwt);
                    return jwt.Claims.GetValueOrDefault("name", "?");
                }
            
        
        ...
    
    
  • Invoke the Divide two integers method with the Authorization header once more and observe the 200 Success.
  • Use the Trace feature to inspect what was passed to backend. You should see the new header and the correct value from the claims.

    APIM JWT Claim in Trace

JSON Web Tokens (JWT) – Improvements

Based on what you have learned thus far, consider how you can improve your policies. For example, you may not want to hard-code the issuer-signing-key and instead use a Named Value that you can more easily administer and change outside of an API’s policies. If you have time in this exercise, go ahead and give it a try.

Task 2: Oauth2 

2.1: Azure APIM and Oauth2

Based on the Microsoft Tech Community blog post by Sherry Sahni.

The API Management is a proxy to the backend APIs, it’s a good practice to implement security mechanism to provide an extra layer of security to avoid unauthorized access to APIs.

Diagram showing APIM and OAuth 2.0

In this Diagram we can see the OAUTH flow with API Management in which:

  • The Developer Portal requests a token from Azure AD using app registration client id and client secret.
  • In the second step, the user is challenged to prove their identity by supplying User Credentials.
  • After successful validation, Azure AD issues the access/refresh token.
  • User makes an API call with the authorization header and the token gets validated by using validate-jwt policy in APIM by Azure AD.
  • Based on the validation result, the user will receive the response in the developer portal.

Different grant types:

Grant FlowDescriptionUse Case
Authorization CodeIt is the most used grant type to authorize the Client to access protected data from a Resource Server.Used by the secure client like a web server.
ImplicitIt is intended for user-based clients who can’t keep a client secret because all the application code and storage is easily accessible.Used by the client that can’t protect a client secret/token, such as a mobile app or single page application.
Client CredentialsThis grant type is non interactive way for obtaining an access token outside of the context of a user.It is suitable for machine-to-machine authentication where a specific user’s permission to access data is not required.
Resource Owner password CredentialsIt uses the username and the password credentials of a Resource Owner (user) to authorize and access protected data from a Resource Server.For logging in with a username and password (only for first-party apps)

High-level steps required to configure OAUTH

To configure Oauth2 with APIM the following needs to be created:

  • Register an application (backend-app) in Azure AD to represent the protected API resource.​
  • Register another application (client-app) in Azure AD which represent a client that wants to access the protected API resource.​
  • In Azure AD, grant permissions to client(client-app) to access the protected resource (backend-app).​
  • Configure the Developer Console to call the API using OAuth 2.0 user authorization.​
  • Add the validate-jwt policy to validate the OAuth token for every incoming request.​​

2.2: AAD Create a new tenant

  1. Sign in to your organization’s Azure portal.

  2. From the Azure portal menu, select Create a resource.

    Azure Active Directory Create resoure page

  3. Select Identity, and then select Azure Active Directory.

    The Create directory page appears.

    Azure Active Directory Create page

  4. On the Create directory page, enter the following information:

    • Type Contoso into the Organization name box.

    • Type Contoso into the Initial domain name box.

    • Leave the United States option in the Country or region box.

  5. Select Create.

Your new tenant is created with the domain labapimtenant.onmicrosoft.com.

2.3: Authorization Code

In Authorization code grant type, User is challenged to prove their identity providing user credentials. Upon successful authorization, the token end point is used to obtain an access token. The obtained token is sent to the resource server and gets validated before sending the secured data to the client application.

Authorization Code Flow

Register an application (backend-app) in Azure AD to represent the Basic Calculator API​

To protect an API with Azure AD, first register an application in Azure AD that represents the API. The following steps use the Azure portal to register the application.

First we need to access our the AAD tenant we created in the excercise before, be sure you are in the right tenant. Then select App registrations under Azure Portal to register an application:

  • Select New registration.

backend app registration1

  • In the Name section, enter a meaningful application name that will be displayed to users of the app. For example oauth-backend-app
  • In the Supported account types section, select an option that suits your scenario.
  • Leave the Redirect URI section empty.
  • Select Register to create the application.

backend app registration2

  • On the app Overview page, find the Application (client) ID value and record it for later.

backend app registration3

  • Select Expose an API and set the Application ID URI with the default value. Record this value for later.
  • Select the Add a scope button to display the Add a scope page. Then create a new scope that’s supported by the API (for example, Calculator.Read).
  • Select the Add scope button to create the scope. Repeat this step to add all scopes supported by your API.
  • When the scopes are created, make a note of them for use in a subsequent step.

backend app registration4

Register another application (client-app) in Azure AD to represent the Developer Portal( client application)​

Every client application that calls the API needs to be registered as an application in Azure AD. In this example, the client application is the Developer Console in the API Management developer portal. In this case we will register another application in Azure AD to represent the Developer Console:

  • Select New registration.

client app registration1

  • In the Name section, enter a meaningful application name that will be displayed to users of the app. For example oauth-client-app
  • In the Supported account types section, select an option that suits your scenario.
  • Leave the Redirect URI section empty.
  • Select Register to create the application.

client app registration2

  • On the app Overview page, find the Application (client) ID value and record it for later.
  • Create a client secret for this application to use in a subsequent step.
    • From the left menu options for your client app, select Certificates & secrets, and select New client secret.
    • Under Add a client secret, provide a Description. Choose when the key should expire and select Add. When the secret is created, note the key value for use in a subsequent step.

client app registration5

Grant permissions for client-app to call backend-app

  • Now we have to open our client app and choose the option API permissions
  • In here we need to click on Add a permission
  • Then choose My APIs
  • Select the record for backend-app-oauth

client app registration5.1

  • Then select the Delegated Permissions option
  • Then mark the Calculator.Read checkbox
  • Then click the Add Permissions button

client app registration5.2

  • Finally click the Grant admin consent for ...

client app registration5.3

Enable OAuth 2.0 in the Developer Console for Authorization Code Grant type

At this point, we have created the applications in Azure AD, and granted proper permissions to allow the client-app to call the backend-app.

In this demo, the Developer Console is the client-app and has a walk through on how to enable OAuth 2.0 user authorization in the Developer Console. Steps mentioned below:

  • In Azure portal, browse to your API Management instance and Select OAuth 2.0 > Add.
  • Provide a Display name and Description.
  • For the Client registration page URL, enter a placeholder value, such as http://localhost.
  • For Authorization grant types, select Authorization code.

authcode6

Specify the Authorization endpoint URL and Token endpoint URL. These values can be retrieved from the Endpoints page in your Azure AD tenant. Browse to the client App registrations page again and select Endpoints.

authcode7

authcode8

ENDPOINTS VERSIONS

We recommend using v2 endpoints. When using v2 endpoints, use the scope you created for the backend-app in the Default scope field. Also, make sure to set the value for the accessTokenAcceptedVersion property to 2 in your application manifest in Azure AD Client APP and Backend app.

authcode9

  • Next, specify the client credentials. These are the credentials for the client-app.
  • For Client ID, use the Application ID of the client-app.

authcode10

  • For Client secret, use the key you created for the client-app earlier.
  • Immediately following the client secret is the redirect_urls

authcode11

  • Go back to your client-app registration in Azure Active Directory under Authentication.
  • Paste the redirect_url under Redirect URI, and check the issuer tokens then click on Configure button to save.

authcode12

Now that you have configured an OAuth 2.0 authorization server, the Developer Console can obtain access tokens from Azure AD.

The next step is to enable OAuth 2.0 user authorization for your API. This enables the Developer Console to know that it needs to obtain an access token on behalf of the user, before making calls to your API.

  • Go to APIs menu under the APIM
  • Select the Basic Calculator API and Go to Settings.
  • Under Security, choose OAuth 2.0, select the OAuth 2.0 server you configured earlier and select save.

authcode13

  • Publish the developer portal again to refresh this changes

CALLING THE API FROM THE DEVELOPER PORTAL

Now that the OAuth 2.0 user authorization is enabled on your API, the Developer Console will obtain an access token on behalf of the user, before calling the API.

  • Copy the developer portal url from the overview blade of apim

authcode14

  • Browse to any operation under the Basic Calculator API in the developer portal and select Try it. This brings you to the Developer Console.
  • Note a new item in the Authorization section, corresponding to the authorization server you just added.

authcode15

  • Select Authorization code from the authorization drop-down list, and you are prompted to sign in to the Azure AD tenant. If you are already signed in with the account, you might not be prompted.

authcode16

  • After successful sign-in, an Authorization header is added to the request, with an access token from Azure AD. The following is a sample token (Base64 encoded):

authcode17

Select Send to call the API successfully with 200 ok response.

authcode18

Validate-jwt policy to pre-authorize requests with AD token:

At this point we can call the APIs with the obtained bearer token. However, what if someone calls your API without a token or with an invalid token? For example, try to call the API without the Authorization header, the call will still go through. This is because the API Management does not validate the access token, It simply passes the Authorization header to the back-end API.

To pre-Authorize requests, we can use validate-jwt Policy by validating the access tokens of each incoming request. If a request does not have a valid token, API Management blocks it.

We will now configure the Validate JWT policy to pre-authorize requests in API Management, by validating the access tokens of each incoming request. If a request does not have a valid token, API Management blocks it.

  • Browses to the APIs from the left menu of APIM
  • Click on Basic Calculator Api and open the inbound policy to add the validate-jwt policy(It checks the audience claim in an access token and returns an error message if the token is not valid.) and save it.

authcode19

  • You will need to get the id of your scope, you set from you backend-app registration. Normally this comes in the form api://d183fdbe-fc28-4ef7-9ca1-e7b4a4cd1ff8/Calculator.read , we need to use the id d183fdbe-fc28-4ef7-9ca1-e7b4a4cd1ff8 as audience

backend app registration4

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
    <openid-config url="https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration" />
    
        YOUR-BACKENDAPP-SCOPE-ID
    

  • Go back to the developer portal and send the api with invalid token.
  • You would observe the 401 unauthorized.

authcode20

  • Modify the token from authorization header to the valid token and send the api again to observe the 200-ok response.

UNDERSTANDING VALIDATE-JWT POLICY

authcode21

In this section, we will be focusing on understanding how validate-jwt policy works (the image in the right side is the decoded JWT Token)

  • The validate-jwt policy supports the validation of JWT tokens from the security viewpoint, It validates a JWT (JSON Web Token) passed via the HTTP Authorization header
  • If the validation fails, a 401 code is returned. The policy requires an openid-config endpoint to be specified via an openid-config element. API Management expects to browse this endpoint when evaluating the policy as it has information which is used internally to validate the token. Please Note : OpenID config URL differs for the v1 and v2 endpoints.
  • The required-claims section contains a list of claims expected to be present on the token for it to be considered valid. The specified claim value in the policy must be present in the token for validation to succeed.

The claim value should be the Application ID of the Registered Azure AD Backend-APP.

Task 3: Managed Identities

Security

Managed Service Identity

In Azure, an Active Directory identity can be assigned to a managed resource such as an Azure Function, App Service or even an API Management instance. Once an identity is assigned, it has many capabilities to work with other resources that leverage Azure AD for authentication, much like a service principal.

REGISTER API MANAGEMENT WITH ACTIVE DIRECTORY

Register APIM

KEY VAULT – CREATE KEY VAULT AND ADD A SECRET

  • Create a Key Vault instance
  • Add a secret to the Key Vault instance
    • Name:favoritePerson
    • Value: 3

Create Key Vault

KEY VAULT – ACCESS POLICY AND PRINCIPAL ASSIGNMENT

Create an access policy

Create Key Vault

Select the Get operation from the list of Secret permissions

Create Key Vault

Select the principal and search for the name of your API Management instance

Create Key Vault

Create Key Vault

Remember to click Save

Create Key Vault

API MANAGEMENT, KEY VAULT AND MANAGED SERVICE IDENTITY

  • Add a new operation to the Star Wars API
  • Update the policies for the new operation

New operation


<base />
<send-request mode="new" response-variable-name="secretResponse" timeout="20" ignore-error="false">
    https://{your-keyvault-base-uri}.azure.net/secrets/favoritePerson/?api-version=7.0
    GET
    <authentication-managed-identity resource="https://vault.azure.net" />

<set-variable name="favoritePersonRequest" value="@{
    var secret = ((IResponse)context.Variables["secretResponse"]).Body.As<JObject>();
    return "/people/" + secret["value"].ToString() + "/";
}" />
<rewrite-uri template="@((string)context.Variables["favoritePersonRequest"])" />

TEST THE OPERATION

  • Test the operation (use the developer portal, Azure portal or tools like Postman and curl)
  • Notice the request URL will be similar to: https://{your-apim-instance}.azure-api.net/sw/favorite

Exercise 7: DevOps

Duration: 30 minutes

TABLE OF CONTENTS

Task 1: Azure DevOps + Apim Devops Kit

Please see aka.ms/apimdevops for more guidance and tools around automating deployment across multiple API Management environments.

Continuos Integration and Continuos Deployment using Azure DevOps

The following instructions demonstrate how to deploy the contents of this example repository using Azure DevOps Repos and Azure DevOps Pipelines.

Pre-reqs

There are two options to execute te apim devops kit, locally with .net and azure cli or using the azure cloude shell. Please select your prefered option:

Local

Azure Cloud Shell

Optional(if you want to deploy with a build pipeline):

Architecture

This is one example of how to use Azure DevOps Repo and Azure DevOps Pipelines to enable a Continuous Integration and Continuous Deployment (CI/CD) for API's on an Azure API Management Service. There’re other ways to do this, but this is a “Keep it Simple” to help you start. (Planning to have another version using Github and Github Actions soon).

This is our Development API management. In general, developers will create their API's in one instance of APIM to test it.

Create your API’s on API Management Development environment. (How to create API’s on API Management)

APIM DevOps Toolkit

Running the Extractor

After a developer creates and tests APIs in API management, it is time to extract those APIs using this DevOps Resource Kit.

Below are the steps to run the extractor from source code:

  • Clone this repository and navigate to {path_to_folder}/src/APIM_ARMTemplate/apimtemplate
      git clone https://github.com/Azure/azure-api-management-devops-resource-kit.git
      cd src/APIM_ARMTemplate/apimtemplate
    
  • Restore its packages using

      dotnet restore 
    
  • Make sure you have signed in using Azure CLI and have switched to the subscription containing the API Management instance from which the configurations will be extracted. Ensure you are using the correct Azure subscription:

     # View subscriptions
     az account list
    
     # Verify selected subscription
     az account show
    
     # Set correct subscription (if needed)
     az account set --subscription 
    
     # Verify correct subscription is now set
     az account show
    

Extractor Arguments

You have two choices when specifying your settings:

  • By using a JSON file with key-values where the keys matches the table below. Use the extractorConfig argument:

    extract --extractorConfig c:/temp/extractSettings.json

  • Or you can also pass the arguments on the command line. For instance extract --sourceApimName my-feature-apim --destinationApimName company-stable-apim --resourceGroup my-feature-rg --fileFolder c:\\temp\\apim-extract --apiName MyFeatureV1Api

    Where:

    sourceApimName: API Management where you created your API

    destinationApimName: It's just a convention to set the DESTINATION-API-NAME in front of the generated files.

    resourceGroup: Resource group where the DEV-APIM-NAME is hosted.

    fileFolder: (NOTE: git clone and create the local repos before executing the dotnet run extract)

    For more information on how to run the application and parameters, go to this page.

  • For this example, we will pass the arguments on the command line. So, run the application with:

      dotnet run extract --sourceApimName  --resourceGroup  --destinationApimName   --fileFolder apim-extract
    

    i.e.

      dotnet run extract --sourceApimName famc-apimlab2 --resourceGroup famc-apimlab2 --destinationApimName famc-apimlab2-prod  --fileFolder apim-extract 
    

After executing the command above, you will see something similar to this:

Then you see the JSON files extracted:

Now, push them to your Azure DevOps Repo

git add *
git commit -a -m "add extracted *.json files to devops repository
git push

Build Pipeline

We will use a Build Pipeline to pull the extracted files from a repo and put it on Azure DevOps Artefacts Folder.

1 – Add these tasks to your build:

  • Get Sources
  • Copy Publish Artifacts

2 – Configure the fields as show bellow:

A screenshot of a cell phone Description automatically generated

A screenshot of a cell phone Description automatically generated

Release Pipeline

You can use this document as a reference on how to create a release pipeline.

1 – Add an Azure Deployment tasks for each file generated by the extractor, following the order:

- Products.template.json
- Tags.template.json
- namedValues.template.json
- apis.template.json
- globalServicePolice.template.json

2 – Set “Override template parameters” field with “-ApimServiceName “

3 – Set set Deployment mode to Incremental

When you finish the steps above, you will see something like this:

Clone your QA environment and update the Resource Group and ApimServiceName value on “Override template parameters” field to reflect your “production” APIM.

Now you will see your Release Pipeline like this:

By using a combination of manual deployment approvals, gates, and manual intervention within a release pipeline in Azure Pipelines, you can quickly and easily configure a release pipeline with all the control and auditing capabilities you require for your DevOps CI/CD processes. You will find more information on this link.

Exercise 8: Fusion Dev

Duration: 30 minutes

TABLE OF CONTENTS

Task 1: Powerapp + Azure Apim API

The premier Star Wars Fan club is growing and the club officers would like to upgrade from their existing member tracking worksheet to a mobile application that would be available to their members all over the world. The members would also like to see information about their favorite Star Wars movies and characters in the application that would update as new shows and movies are released.

In this exercise, you will be using Star Wars API with Azure API Management instance that you created in part three of this lab. The Excel worksheet of member profiles will serve as the primary backing data source and will be used to generate a base application. You will export the Star Wars API from API Management as a Power Platform Custom Connector so that the Canvas App can access real-time Star Wars character information. For each of the Fan Club members, you can then search the Star Wars API character data and show information about their favorite character in the Canvas App.

Note: This exercise requires access to Power Apps Premium connectors. Sign up for a free Developer Plan.

Create a custom connector

From the existing Star Wars API Api in Azure API Management, click the ellipsis  and select the Create Power Connector option to generate a custom connector in your Power Platform environment.

If you are unable to create a Power Connector from Azure API Management, you can also export an OpenAPI v2 (JSON) file that can be imported as a Custom Connector within Power Platform. You can find a sample here.

View your custom connector in Power Platform

  1. Go to https://make.powerapps.com and sign in with your organizational account.
  2. Select Data from the left pane, and then select Custom Connectors to see your generated custom connector to your API Management API.

  1. From here, select the pencil icon to edit the custom connector.
  2. On the Definition screen, we need to define a search query string for people so that the Power App can search for character records by name. Select the GetPeople action, and in the Request section, select + Import from sample. Enter a sample request URL with the search query string:

https://apim-star-wars-xxxx.azure-api.net/sw/people?search=Luke

  1. In the Response section of the getpeople action, select the 200 response and then select + Import from sample. Copy and paste a sample JSON response into the Body section of the response. Close the import panel and select Update connector.

Repeat this import for the getpeoplebyid action.

  1. On the Test screen, create a new connection instance in the Connections section. You will then be redirected to the Connections area in Power Platform where your connection was created. Navigate back to the Custom Connectors page and edit the Star Wars API again. Return to the Test page and test each of the API actions.

Generate the Star Wars Fan Club Application

Connect to the backing data source

  1. Download the FanClubMembers.xlsx workbook and save it to your OneDrive for Business account.
  2. Back in the Power Apps Editor, in the left pane, select Home.
  3. Under Start from data , select Other data sources and then select New from the left pane.
  4. Select OneDrive for Business data source, and then Phone layout.
  5. Under OneDrive for Business , select Create.
  6. Under Connections , select OneDrive for Business and browse to the file location. You might need to select New Connection to see the OneDrive for Business connection.
  7. Under Choose an Excel file , select the FanClubMembers.xlsx file.
  8. Under Choose a table , select the Members table.
  9. Select Connect on the bottom right.
  10. Power Apps will generate the app by inspecting your data and matching it with Power Apps screens.

Add Favorite Character information

Your generated app will now be in edit mode in the Power Apps Studio.

Add the Star Wars API Data Source

  1. Select Data from the left pane and then select + Add data from the drop-down menu.
  2. Search for Star Wars in the search field and choose the connection to the Star Wars API.

Customize the generated app

Your generated app will now be in edit mode in the Power Apps Studio.

You can customize your app theme using the Theme drop-down menu and selecting an option. You can change or format the fields that are shown in the Gallery by selecting Tree view in the left pane, clicking on the BrowseGallery1, and making edits in the right formatting pane.

Add controls to the View Detail screen

  1. In the Tree view, select DetailScreen1.
  2. Select the + icon on the left side of the screen to bring up the Insert panel.
  3. Select Text Label and add labels for the Favorite Character section header and for each one of the character description fields.
  4. For each label control, change the Text property in the right-side Properties panel to describe each field.
  5. Drag the controls on the screen so they are below the header and are aligned with the center of the screen.

Connect the Detail Screen to the Star Wars API

  1. In the left pane, select the Tree view and then the BrowseGallery1 on Browsescreen1.
  2. Using the drop-down menu, select the OnSelect action that will be executed when a user selects a Fan Club member from the gallery.
  3. In the OnSelect function, we will navigate to DetailScreen1 and call the Star Wars API to get the character details for the member's favorite character.
Navigate(DetailScreen1, ScreenTransition.None);

ClearCollect(characterCollection, StarWarsAPI.getpeople({search: ThisItem.MemberFavoriteCharacter}).results);

Show the Star Wars character information on the Detail Screen

  1. For each of the description labels on DetailScreen1 , change the Text property in the right-side Properties panel to include the data from the API. For example, for the Name: label:

"Name:" & " " & First(characterCollection).name

  1. Select Play in the upper-right corner to practice using the app.

Exercise 9: Additional Topics

Task 1: Architecture Desing Session

In this section we provide you with a template architecture diagram for your apim baseline architecture. We recommend you take the time and answer the following questions:

  • What type of apis are you onboarding to Azure Apim?
  • What deployment model works for you(no vnet, internal, external)?
  • What tier of apim is the right for you?
  • What security will you add to your apis?
  • What products are we going to define?
  • What teams and processess need to be in place to manage the Azure Apim?

 | Edit As New

Download Diagram:

Task 2: Provision your own instance of ColoursWeb/ColoursAPI

Some of the demos use the ColourWeb web application and the ColourAPI API application. In this lab we will show you how to deploy your own instances of the Colours Web and Colours API. Note – ColoursWeb / ColoursAPI is new version of ColorsWeb/ColorsAPI … do not mix the web client and API versions.

The code for the ColourWeb / ColourAPI applications is available here:

Docker Containers exist for these applications and so provides an easy deployment option ( IMPORTANT : due to the new pull restrictions on Docker Hub images, in this lab we will be using the GitHub registry):

  • Github (Colours)
    • docker pull ghcr.io/markharrison/coloursapi:latest
    • docker pull ghcr.io/markharrison/coloursweb:latest
  • DockerHub (Colors)
    • docker pull markharrison/colorweb:latest
    • docker pull markharrison/colorapi:latest

With the container we can deploy to multiple hosting options : VM’s, App Services, ACI and also AKS. In this lab we are going to show you how to do it with Azure Container Instances.

Deploying Web and API containers with Azure Container Instances

  1. Login to Azure Portal at http://portal.azure.com.
  2. Open the Azure Cloud Shell and choose Bash Shell (do not choose Powershell)

    Azure Cloud Shell

  3. The first time Cloud Shell is started will require you to create a storage account.
  4. We proceed to create a unique identifier suffix for resources created in this Lab:

     APIMLAB_UNIQUE_SUFFIX=$USER$RANDOM
     # Remove Underscores and Dashes
     APIMLAB_UNIQUE_SUFFIX="${APIMLAB_UNIQUE_SUFFIX//_}"
     APIMLAB_UNIQUE_SUFFIX="${APIMLAB_UNIQUE_SUFFIX//-}"
     # Check Unique Suffix Value (Should be No Underscores or Dashes)
     echo $APIMLAB_UNIQUE_SUFFIX
     # Persist for Later Sessions in Case of Timeout
     echo export APIMLAB_UNIQUE_SUFFIX=$APIMLAB_UNIQUE_SUFFIX >> ~/.bashrc
    
  5. Now we proceed to create a resource group for our ACI objects:

     #we define some variables first
     APIMLAB_RGNAME=myColorsAppRg-$APIMLAB_UNIQUE_SUFFIX
     APIMLAB_LOCATION=eastus
     # Persist for Later Sessions in Case of Timeout
     echo export APIMLAB_RGNAME=$APIMLAB_RGNAME >> ~/.bashrc
     echo export APIMLAB_LOCATION=$APIMLAB_LOCATION >> ~/.bashrc
    
     #we create the resource group
     az group create --name $APIMLAB_RGNAME --location $APIMLAB_LOCATION
    
  6. Now we create our ACI and specify our colors-web github container

    #we define some variables first
    APIMLAB_COLORS_WEB=mycolorsweb-$APIMLAB_UNIQUE_SUFFIX
    APIMLAB_IMAGE_WEB=ghcr.io/markharrison/coloursweb:latest
    APIMLAB_DNSLABEL_WEB=acicolorweb$APIMLAB_UNIQUE_SUFFIX
    # Persist for Later Sessions in Case of Timeout
    echo export APIMLAB_COLORS_WEB=$APIMLAB_COLORS_WEB >> ~/.bashrc
    echo export APIMLAB_IMAGE_WEB=$APIMLAB_IMAGE_WEB >> ~/.bashrc
    echo export APIMLAB_DNSLABEL_WEB=$APIMLAB_DNSLABEL_WEB >> ~/.bashrc
    
    
    #we create the container instance for the colors web
    az container create --resource-group $APIMLAB_RGNAME --name $APIMLAB_COLORS_WEB --image $APIMLAB_IMAGE_WEB --dns-name-label $APIMLAB_DNSLABEL_WEB --ports 80 --restart-policy OnFailure --no-wait
    
  7. Now we run the following command to check the status of the deployment and get the FQDN to access the app:

     #we check the status
     az container show --resource-group $APIMLAB_RGNAME --name $APIMLAB_COLORS_WEB --query "{FQDN:ipAddress.fqdn,ProvisioningState:provisioningState}" --out table
    

    The output should something like this:

     FQDN                                                  ProvisioningState
     ----------------------------------------------------  -------------------
     aci-color-web-fernando22287.eastus.azurecontainer.io  Succeeded
    

    Once we have a “Succeeded” message we proceed to navigate to the FQDN. And we should see our home page for our Colours Web:

  8. Now we proceed to create the ACI for the colors-api github container:

    #we define some variables first
    APIMLAB_COLORS_API=mycolorsapi-$APIMLAB_UNIQUE_SUFFIX
    APIMLAB_IMAGE_API=ghcr.io/markharrison/coloursapi:latest
    APIMLAB_DNSLABEL_API=aci-color-api-$APIMLAB_UNIQUE_SUFFIX
    # Persist for Later Sessions in Case of Timeout
    echo export APIMLAB_COLORS_WEB=$APIMLAB_COLORS_WEB >> ~/.bashrc
    echo export APIMLAB_IMAGE_WEB=$APIMLAB_IMAGE_WEB >> ~/.bashrc
    echo export APIMLAB_DNSLABEL_WEB=$APIMLAB_DNSLABEL_WEB >> ~/.bashrc
    
    
    #we create the container instance for the colors api
    az container create --resource-group $APIMLAB_RGNAME --name $APIMLAB_COLORS_API --image $APIMLAB_IMAGE_API --dns-name-label $APIMLAB_DNSLABEL_API --ports 80 --restart-policy OnFailure --no-wait
    
  9. Now we run the following command to check the status of the deployment and get the FQDN to access the app:

    #we check the status
    az container show --resource-group $APIMLAB_RGNAME --name $APIMLAB_COLORS_API --query "{FQDN:ipAddress.fqdn,ProvisioningState:provisioningState}" --out table
    

    The output should something like this:

    FQDN                                                  ProvisioningState
    ----------------------------------------------------  -------------------
    aci-color-api-fernando22287.eastus.azurecontainer.io  Succeeded
    

    Once we have a “Succeeded” message we proceed to navigate to the FQDN. And we should see our home page (Swagger UI) for our Colours API:

Task 3: API Proxy to Serverless

Azure Serverless (Functions and Logic Apps) can be configured to benefit from the advantages of API Management.

Azure Functions

  • Create a simple function that is Triggered by an HTTP Request

Example:

    //string[] strColors = { "blue", "lightblue", "darkblue" };
    string[] strColors = { "green", "lightgreen", "darkgreen" };

    Random r = new Random();
    int rInt = r.Next(strColors.Length);

    return  (ActionResult)new OkObjectResult(strColors[rInt]);

Lets add the function to API Management. In the API blade select [+Add API] and the [Function App] tile

  • Select the [Browse] button to get a list of Functions in the subscription

  • Select the Function App and then the Function

  • Amend the Names / Descriptions, URL suffix and select the Products

  • As previously add CORS policy

  • Validate the function works – either from the Azure management portal or the developer portal

Azure Logic Apps

  • Create a simple logic app that is Triggered by an HTTP Request

Example:

Use the following sample message to generate the schema of the Request body payload. By specifying the schema, the individual fields (in this case msg) can be extracted and referred to in the subsequent logic

{
  "msg": "text"
}

Lets add the function to API Managament. In the API blade select [+Add API] and the [Logic App] tile

  • Select the [Browse] button to get a list of Logic Apps in the subscription

  • Select the Logic App

  • Amend the Names / Descriptions, URL suffix and select the Products

As previously add CORS policy

  • Validate the Logic App works – either from the Azure management portal or the developer poral

  • Check the Logic App audit

  • Check the email was sent

Task 4: Self-hosted Gateway

With the API Management self-hosted gateway, organisations have the ability to deploy an instance of the APIM gateway component to the environments where they host their applications and/or APIs – for example, in an on-premise data center.

The self-hosted gateways are hosted in a Docker or Kuberenetes environment, and are managed from the API Management service they are connected to.

This part of the lab assumes that the user has Docker Desktop installed. Installation instructions are here

There are two terms to become familiar with:

  • Gateway Deployment … this is a set of APIM configuration details that will be used by the Gateway Node(s)
  • Gateway Node … this is a running instance of a APIM gateway proxy i.e. a containerised instance of the gateway

There can be multiple Gateway Deployments and multiple Gateway Nodes. The Gateway Deployments are chargeable – the Gateway Nodes are free i.e. an organization pays for the management control plane, but the compute is free (you are running on the organizations own hardware)

Deploy the Self-hosted Gateway

To deploy a self-hosted gateway:

  • Select the Gateways option from the menu
  • Select + Add

  • Enter a Name and Location for the Gateway
  • Select the required APIs from those that are configured in the APIM instance
    • Our lab will use the Color API – this was configured in an earlier module
  • Select the Add button

The added gateway will appear in the list … this is the Gateway Deployment.

  • Click on the gateway in the list – a blade appears allowing further configuration

  • Select the Deployment option from the menu
    • There are scripts for deploying on Docker and Kuberenetes … for this lab, we will be using the Docker option
  • Save the env.conf file to your desktop
  • Copy the Docker run command but remove the -d parameter … this is so the logs are displayed to the terminal
docker run -p 80:8080 -p 443:8081 --name OnPremiseGateway --env-file env.conf mcr.microsoft.com/azure-api-management/gateway:latest

From a command line – elevated to Administrator (needed for Docker commands)

  • Navigate to the location where the env.conf is located
  • Run the Docker run command

The first time this is executed, it will need to pull down the Docker image – and so there will be a small delay. Subsequently – if restarted – it will just use the downloaded image.

Once downloaded, the log output from the container will display a Sputnik logo (this was an internal code name) and some diagnostic logs.

Note that in the Gateway blade we can see the status – it will show there is one healthy Gateway Node connected to the Deployment. The Gateway Node will keep in sync, and be automatically updated should any of the Gateway Deployment config changes.

Testing the API

Our Gateway Node is now deployed – and we can test that it works.

  • Open Developer portal, go in the Profile page and get API key for Unlimited products
  • Open Notepad – make note of URLs including the key. For our lab test, the machine name is just localhost
    • https://localhost/color/api/RandomColor?key=Unlimited-Key

  • Use a tool like Postman to test the API … should see the random color appear in the response and this confirms everything is working properly
  • If tested with a browser, then a warning needs to accepted to proceed – this is because trusted TLS certificates have not been set up

Diagnostics for the API call will be logged by the container.

 

Scroll to top