Create an OpenAPI definition for a serverless API using Azure API Management

REST APIs are often described using an OpenAPI definition. This definition contains information about what operations are available in an API and how the request and response data for the API should be structured.

In this tutorial, you create a function that determines whether an emergency repair on a wind turbine is cost-effective. You then create an OpenAPI definition for the function app using Azure API Management so that the function can be called from other apps and services.

In this tutorial, you learn how to:

  • Create a function in Azure
  • Generate an OpenAPI definition using Azure API Management
  • Test the definition by calling the function
  • Download the OpenAPI definition

Create a function app

You must have a function app to host the execution of your functions. A function app lets you group functions as a logical unit for easier management, deployment, scaling, and sharing of resources.

  1. From the Azure portal menu or the Home page, select Create a resource.

  2. In the New page, select Compute > Function App.

  3. On the Basics page, use the function app settings as specified in the following table.

    Setting Suggested value Description
    Subscription Your subscription The subscription under which this new function app is created.
    Resource Group myResourceGroup Name for the new resource group in which to create your function app.
    Function App name Globally unique name Name that identifies your new function app. Valid characters are a-z (case insensitive), 0-9, and -.
    Publish Code Option to publish code files or a Docker container.
    Runtime stack Preferred language Choose a runtime that supports your favorite function programming language. Choose .NET Core for C# and F# functions.
    Version Version number Choose the version of your installed runtime.
    Region Preferred region Choose a region near you or near other services your functions access.

    Basics

  4. Select Next : Hosting. On the Hosting page, enter the following settings.

    Setting Suggested value Description
    Storage account Globally unique name Create a storage account used by your function app. Storage account names must be between 3 and 24 characters in length and can contain numbers and lowercase letters only. You can also use an existing account, which must meet the storage account requirements.
    Operating system Preferred operating system An operating system is pre-selected for you based on your runtime stack selection, but you can change the setting if necessary.
    Plan Consumption (Serverless) Hosting plan that defines how resources are allocated to your function app. In the default Consumption plan, resources are added dynamically as required by your functions. In this serverless hosting, you pay only for the time your functions run. When you run in an App Service plan, you must manage the scaling of your function app.

    Hosting

  5. Select Next : Monitoring. On the Monitoring page, enter the following settings.

    Setting Suggested value Description
    Application Insights Default Creates an Application Insights resource of the same App name in the nearest supported region. By expanding this setting or selecting Create new, you can change the Application Insights name or choose a different region in an Azure geography where you want to store your data.

    Monitoring

  6. Select Review + create to review the app configuration selections.

  7. On the Review + create page, review your settings, and then select Create to provision and deploy the function app.

  8. Select the Notifications icon in the upper-right corner of the portal and watch for the Deployment succeeded message.

  9. Select Go to resource to view your new function app. You can also select Pin to dashboard. Pinning makes it easier to return to this function app resource from your dashboard.

    Deployment notification

Create the function

This tutorial uses an HTTP triggered function that takes two parameters:

  • The estimated time to make a turbine repair, in hours.
  • The capacity of the turbine, in kilowatts.

The function then calculates how much a repair will cost, and how much revenue the turbine could make in a 24-hour period. To create the HTTP triggered function in the Azure portal:

  1. From the left menu of your functions app, select Functions, and then select Add from the top menu.

  2. In the New Function window, select Http trigger.

  3. For New Function, enter TurbineRepair.

  4. Choose Function from the Authorization level drop-down list, and then select Create Function.

    Create HTTP function for OpenAPI

  5. Select Code + Test, and then select run.csx from the drop-down list. Replace the contents of the run.csx C# script file with the following code, then choose Save:

    #r "Newtonsoft.Json"
    
    using System.Net;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Primitives;
    using Newtonsoft.Json;
    
    const double revenuePerkW = 0.12;
    const double technicianCost = 250;
    const double turbineCost = 100;
    
    public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
    {
        // Get query strings if they exist
        int tempVal;
        int? hours = Int32.TryParse(req.Query["hours"], out tempVal) ? tempVal : (int?)null;
        int? capacity = Int32.TryParse(req.Query["capacity"], out tempVal) ? tempVal : (int?)null;
    
        // Get request body
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
    
        // Use request body if a query was not sent
        capacity = capacity ?? data?.capacity;
        hours = hours ?? data?.hours;
    
        // Return bad request if capacity or hours are not passed in
        if (capacity == null || hours == null){
            return new BadRequestObjectResult("Please pass capacity and hours on the query string or in the request body");
        }
        // Formulas to calculate revenue and cost
        double? revenueOpportunity = capacity * revenuePerkW * 24;  
        double? costToFix = (hours * technicianCost) +  turbineCost;
        string repairTurbine;
    
        if (revenueOpportunity > costToFix){
            repairTurbine = "Yes";
        }
        else {
            repairTurbine = "No";
        };
    
        return (ActionResult)new OkObjectResult(new{
            message = repairTurbine,
            revenueOpportunity = "$"+ revenueOpportunity,
            costToFix = "$"+ costToFix
        });
    }
    

    This function code returns a message of Yes or No to indicate whether an emergency repair is cost-effective. It also returns the revenue opportunity that the turbine represents and the cost to fix the turbine.

  6. To test the function, select Test, select the Input tab, enter the following input for the Body, and then select Run:

    {
    "hours": "6",
    "capacity": "2500"
    }
    

    Test the function in the Azure portal

    The following output is returned in the Output tab:

    {"message":"Yes","revenueOpportunity":"$7200","costToFix":"$1600"}
    

Now you have a function that determines the cost-effectiveness of emergency repairs. Next, you generate an OpenAPI definition for the function app.

Generate the OpenAPI definition

To generate the OpenAPI definition:

  1. Select the function app, choose API Management from the left menu, and then select Create new under API Management.

    Choose API Management

  2. Use the API Management settings as specified in the following table:

    Setting Suggested value Description
    Name Globally unique name A name is generated based on the name of your function app.
    Subscription Your subscription The subscription under which this new resource is created.
    Resource group myResourceGroup The same resource as your function app, which should get set for you.
    Location West US Choose the West US location.
    Organization name Contoso The name of the organization used in the developer portal and for email notifications.
    Administrator email your email Email that received system notifications from API Management.
    Pricing tier Consumption Consumption tier isn't available in all regions. For complete pricing details, see the API Management pricing page

    Create new API Management service

  3. Choose Create to create the API Management instance, which may take several minutes.

  4. After Azure creates the instance, it enables the Enable Application Insights option on the page. Select it to send logs to the same place as the function application, and then select Link API.

  5. The Import Azure Functions opens with the TurbineRepair function highlighted. Choose Select to continue.

    Import Azure Functions into API Management

  6. In the Create from Function App page, accept the defaults, and then select Create.

    Create from Function App

    Azure creates the API for the function.

Test the API

Before you use the OpenAPI definition, you should verify that the API works.

  1. On your function app page, select API Management, select the Test tab, and then select POST TurbineRepair.

  2. Enter the following code in the Request body:

    {
    "hours": "6",
    "capacity": "2500"
    }
    
  3. Select Send, and then view the HTTP response.

    Test function API

Download the OpenAPI definition

If your API works as expected, you can download the OpenAPI definition.

  1. Select Download OpenAPI definition at the top of the page.

    Download OpenAPI definition

  2. Save the downloaded JSON file, and then open it. Review the definition.

Clean up resources

In the preceding steps, you created Azure resources in a resource group. If you don't expect to need these resources in the future, you can delete them by deleting the resource group.

From the Azure portal menu or Home page, select Resource groups. Then, on the Resource groups page, select myResourceGroup.

On the myResourceGroup page, make sure that the listed resources are the ones you want to delete.

Select Delete resource group, type myResourceGroup in the text box to confirm, and then select Delete.

Next steps

You have used API Management integration to generate an OpenAPI definition of your functions. You can now edit the definition in API Management in the portal. You can also learn more about API Management.