使用 Azure API 管理为无服务器 API 创建 OpenAPI 定义Create an OpenAPI definition for a serverless API using Azure API Management

通常使用 OpenAPI 定义描述 REST API。REST APIs are often described using an OpenAPI definition. 此定义中包含的信息涉及 API 中哪些操作可用,以及 API 的请求和响应数据应采用怎样的结构。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. 然后使用 Azure API 管理为该函数应用创建一个 OpenAPI 定义,使该函数可使用其他应用和服务进行调用。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:

  • 在 Azure 中创建一个函数Create a function in Azure
  • 使用 Azure API 管理生成 OpenAPI 定义Generate an OpenAPI definition using Azure API Management
  • 通过调用函数测试定义Test the definition by calling the function
  • 下载 OpenAPI 定义Download the OpenAPI definition

创建函数应用Create a function app

必须使用 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. 在 Azure 门户菜单或“主页”页中,选择“创建资源” 。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 myResourceGroupmyResourceGroup 要在其中创建 Function App 的新资源组的名称。Name for the new resource group in which to create your function app.
    函数应用名称Function App name 全局唯一名称Globally unique name 用于标识新 Function App 的名称。Name that identifies your new function app. 有效字符为 a-z(不区分大小写)、0-9-Valid characters are a-z (case insensitive), 0-9, and -.
    Publish 代码Code 用于发布代码文件或 Docker 容器的选项。Option to publish code files or a Docker container.
    运行时堆栈Runtime stack 首选语言Preferred language 选择支持你喜欢的函数编程语言的运行时。Choose a runtime that supports your favorite function programming language. 对于 C# 和 F# 函数,选择 .NET CoreChoose .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.

    基础知识

  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. 存储帐户名称必须为 3 到 24 个字符,并且只能包含数字和小写字母。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) 定义如何将资源分配给 Function App 的托管计划。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 InsightsApplication Insights 默认Default 当前不受支持Not supported currently

    监视

  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.

    部署通知

创建函数Create the function

本教程使用 HTTP 触发的函数,该函数采用两个参数: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.

然后函数计算修复的费用和涡轮机 24 小时可以产生的收入。The function then calculates how much a repair will cost, and how much revenue the turbine could make in a 24-hour period. 要在 Azure 门户中创建 HTTP 触发的函数,请执行以下步骤: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. 在“新建函数”窗口中,选择“Http 触发器”。In the New Function window, select Http trigger.

  3. 对于“新函数”,请输入 TurbineRepairFor New Function, enter TurbineRepair.

  4. 授权级别下拉列表中选择“函数”,然后选择“创建函数”。Choose Function from the Authorization level drop-down list, and then select Create Function.

    创建用于 OpenAPI 的 HTTP 函数

  5. 选择“代码 + 测试”,然后从下拉列表中选择“run.csx”。Select Code + Test, and then select run.csx from the drop-down list. 将 run.csx C# 脚本文件的内容替换为以下代码,然后选择“保存”: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
        });
    }
    

    此函数代码会返回 YesNo 消息,指示紧急修复是否具有成本效益。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"
    }
    

    在 Azure 门户中测试函数

    “输出”选项卡中会返回以下输出: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. 接下来,为该函数应用生成 OpenAPI 定义。Next, you generate an OpenAPI definition for the function app.

生成 OpenAPI 定义Generate the OpenAPI definition

若要生成 OpenAPI 定义,请执行以下操作:To generate the OpenAPI definition:

  1. 选择该函数应用,从左侧菜单中选择“API 管理”,然后在“API 管理”下选择“新建”。Select the function app, choose API Management from the left menu, and then select Create new under API Management.

    选择“API 管理”

  2. 使用下表中指定的“API 管理”设置: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 myResourceGroupmyResourceGroup 与函数应用相同的资源,系统会为你设置。The same resource as your function app, which should get set for you.
    位置Location 中国北部 2China North 2 选择中国北部 2 位置。Choose the China North 2 location.
    组织名称Organization name ContosoContoso 在开发人员门户中使用的组织名称,也用于电子邮件通知。The name of the organization used in the developer portal and for email notifications.
    管理员电子邮件Administrator email 你的电子邮件your email 从 API 管理接收了系统通知的电子邮件。Email that received system notifications from API Management.
    定价层Pricing tier 消耗Consumption 消耗层并非在所有区域中均可用。Consumption tier isn't available in all regions. 如需完整的定价详细信息,请参阅 API 管理定价页For complete pricing details, see the API Management pricing page

    创建新的 API 管理服务

  3. 选择“创建”以创建 API 管理实例,这可能需要几分钟的时间。Choose Create to create the API Management instance, which may take several minutes.

  4. Azure 创建该实例后,它会在页面上启用“启用 Application Insights”选项。After Azure creates the instance, it enables the Enable Application Insights option on the page. 选择该选项以将日志发送到函数应用程序所在的位置,然后选择“链接 API”。Select it to send logs to the same place as the function application, and then select Link API.

  5. 此时会打开“导入 Azure Functions”,其中突出显示了“TurbineRepair”函数。 The Import Azure Functions opens with the TurbineRepair function highlighted. 选择“选择”,继续操作。Choose Select to continue.

    将 Azure Functions 导入 API 管理

  6. 在“从函数应用创建”页中接受默认值,然后选择“创建”。In the Create from Function App page, accept the defaults, and then select Create.

    从函数应用创建

    Azure 会创建用于该函数的 API。Azure creates the API for the function.

测试 APITest the API

在使用 OpenAPI 定义之前,应验证 API 是否可以正常工作。Before you use the OpenAPI definition, you should verify that the API works.

  1. 在函数应用页上,依次选择“API 管理”、“测试”选项卡和“POST TurbineRepair”。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. 选择“发送”,然后查看“HTTP 响应”。Select Send, and then view the HTTP response.

    测试函数 API

下载 OpenAPI 定义Download the OpenAPI definition

如果 API 可按预期方式工作,则你可以下载 OpenAPI 定义。If your API works as expected, you can download the OpenAPI definition.

  1. 选择页面顶部的“下载 OpenAPI 定义”。Select Download OpenAPI definition at the top of the page.

    下载 OpenAPI 定义

  2. 保存下载的 JSON 文件,然后将其打开。Save the downloaded JSON file, and then open it. 查看定义。Review the definition.

清理资源Clean up resources

在前面的步骤中,你在资源组中创建了 Azure 资源。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.

从 Azure 门户菜单或“主页”页上,选择“资源组” 。From the Azure portal menu or Home page, select Resource groups . 然后,在“资源组”页上,选择“myResourceGroup” 。Then, on the Resource groups page, select myResourceGroup .

在“myResourceGroup”页中,确保列出的资源是要删除的资源。 On the myResourceGroup page, make sure that the listed resources are the ones you want to delete.

选择“删除资源组” ,在文本框中键入“myResourceGroup” 以确认,然后选择“删除” 。Select Delete resource group , type myResourceGroup in the text box to confirm, and then select Delete .

后续步骤Next steps

你已使用 API 管理集成生成了函数的 OpenAPI 定义。You have used API Management integration to generate an OpenAPI definition of your functions. 现在,可以在门户上的“API 管理”中编辑定义。You can now edit the definition in API Management in the portal. 还可以详细了解 API 管理You can also learn more about API Management.