您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

使用 Azure API 管理为函数创建 OpenAPI 定义Create an OpenAPI definition for a function with 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 门户左上角的“创建资源”按钮,然后选择“计算” > “函数应用”。 Select the Create a resource button found on the upper left-hand corner of the Azure portal, then select Compute > Function App.

    在 Azure 门户中创建函数应用

  2. 使用图像下面的表格中指定的函数应用设置。Use the function app settings as specified in the table below the image.

    定义新的函数应用设置

    设置Setting 建议的值Suggested value 说明Description
    应用名称App name 全局唯一名称Globally unique name 用于标识新 Function App 的名称。Name that identifies your new function app. 有效的字符是 a-z0-9-Valid characters are a-z, 0-9, and -.
    订阅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.
    OSOS WindowsWindows 有哪些语言选项可用取决于函数应用的操作系统。The language options available depend on the OS of the function app. 例如,Python 需要 Linux。For example, Python requires Linux.
    托管计划Hosting plan 消耗量计划Consumption plan 定义如何将资源分配给 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 only pay for the time your functions run. 按应用服务计划运行时,必须管理函数应用的缩放When you run in an App Service plan, you must manage the scaling of your function app.
    位置Location 西欧West Europe 选择离你近或离函数访问的其他服务近的区域Choose a region near you or near other services your functions access.
    运行时堆栈Runtime stack 首选语言Preferred language 选择支持你喜欢的函数编程语言的运行时。Choose a runtime that supports your favorite function programming language. 对于 C# 和 F# 函数,选择 .NETChoose .NET for C# and F# functions.
    存储Storage 全局唯一名称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 may contain numbers and lowercase letters only. 也可使用现有帐户,但该帐户必须符合存储帐户要求You can also use an existing account, which must meets the storage account requirements.
    Application InsightsApplication Insights 默认Default 在最近的受支持的区域中,创建一个具有相同应用名称 的 Application Insights 资源。Creates an Application Insights resource of the same App name in the nearest supported region. 展开此设置即可更改“新建资源名称”,或者在 Azure 地理位置中选择另一个需要在其中存储数据的位置By expanding this setting, you can change the New resource name or choose a different Location in an Azure geography where you want to store your data.
  3. 选择“创建” 以预配和部署函数应用。Select Create to provision and deploy the function app.

  4. 选择门户右上角的“通知”图标,留意是否显示“部署成功”消息。 Select the Notification icon in the upper-right corner of the portal and watch for the Deployment succeeded message.

    定义新的函数应用设置

  5. 选择“转到资源” ,查看新的函数应用。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. 展开 Function App,选择“Functions”旁边的 + 按钮。Expand your function app and select the + button next to Functions. 选择“门户中” > “继续”。Select In-portal > Continue.

  2. 选择“更多模板...”,然后选择“完成并查看模板”Select More templates..., then select Finish and view templates

  3. 选择 HTTP 触发器,键入 TurbineRepair 作为函数名称,选择 Function 作为身份验证级别,然后选择“创建”。Select HTTP trigger, type TurbineRepair for the function Name, choose Function for Authentication level, and then select Create.

    创建用于 OpenAPI 的 HTTP 函数

  4. 将 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, as well as the revenue opportunity that the turbine represents, and the cost to fix the turbine.

  5. 若要测试该函数,请单击最右边的“测试”展开“测试”选项卡。在“请求正文”中输入以下值,然后单击“运行”。To test the function, click Test at the far right to expand the test tab. Enter the following value for the Request body, and then click Run.

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

    在 Azure 门户中测试函数

    响应正文中将返回以下值。The following value is returned in the body of the response.

    {"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 定义。Now you're ready to generate the OpenAPI definition.

  1. 选择函数应用,在“平台功能”中选择“API 管理”,然后选择“API 管理”下的“新建”。Select the function app, then in Platform features, choose API Management and select Create new under API Management.

    在“平台功能”中选择“API 管理”

  2. 使用图像下的表中指定的 API 管理设置。Use the API Management settings as specified in the table below the image.

    创建新的 API 管理服务

    设置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 美国西部West US 选择“美国西部”位置。Choose the West US 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 (preview) 消耗层目前为预览版,并非可在所有区域中使用。Consumption tier is in preview and isn't available in all regions. 如需完整的定价详细信息,请参阅 API 管理定价页For complete pricing details, see the API Management pricing page
  3. 选择“创建”以创建 API 管理实例,这可能需要几分钟的时间。Choose Create to create the API Management instance, which may take several minutes.

  4. 选择“启用 Application Insights”,将日志发送到函数应用所在的位置,然后接受余下的默认设置并选择“链接 API”。Select Enable Application Insights to send logs to the same place as the function application, then accept the remaining defaults and 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. 在“从 Function App 创建”页中接受默认设置,然后选择“创建”In the Create from Function App page, accept the defaults and select Create

    从 Function App 创建

现已为函数创建 API。The API is now created for the function.

测试 APITest the API

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

  1. 在函数的“测试”选项卡上,选择 POST 操作。On the Test tab of your function, select POST operation.

  2. 输入“小时”和“容量”的值Enter values for hours and capacity

    {
    "hours": "6",
    "capacity": "2500"
    }
    
  3. 单击“发送”,然后查看 HTTP 响应。Click Send, 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 文件并查看定义。Open the downloaded JSON file and 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 门户的左侧菜单中,选择“资源组” ,然后选择“myResourceGroup” 。From the left menu in the Azure portal, select Resource groups and then select myResourceGroup.

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

选择“删除” ,在文本框中键入 myResourceGroup,然后选择“删除” 。Select Delete, type myResourceGroup in the text box, 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.