使用 Azure Functions 创建无服务器 APICreate a serverless API using Azure Functions

本教程介绍如何使用 Azure Functions 构建高度可缩放的 API。In this tutorial, you will learn how Azure Functions allows you to build highly scalable APIs. Azure Functions 附带了一系列内置 HTTP 触发器和绑定,方便使用各种语言(包括 Node.JS、C# 等等)创建终结点。Azure Functions comes with a collection of built-in HTTP triggers and bindings, which make it easy to author an endpoint in a variety of languages, including Node.JS, C#, and more. 在本教程中,将自定义一个 HTTP 触发器来处理 API 设计中的特定操作。In this tutorial, you will customize an HTTP trigger to handle specific actions in your API design. 此外,还要通过将 API 与 Azure Functions 代理集成并设置模拟 API,来准备扩展 API。You will also prepare for growing your API by integrating it with Azure Functions Proxies and setting up mock APIs. 所有这些操作会在 Functions 无服务器计算环境的顶层完成,因此,不需要考虑如何缩放资源 - 只需专注于自己的 API 逻辑。All of this is accomplished on top of the Functions serverless compute environment, so you don't have to worry about scaling resources - you can just focus on your API logic.

先决条件Prerequisites

本主题以在从 Azure 门户创建第一个函数主题中创建的资源为基础。This topic uses as its starting point the resources created in Create your first function from the Azure portal. 请现在就完成以下步骤,以便创建函数应用(如果尚未这样做)。If you haven't already done so, please complete these steps now to create your function app.

本教程的余下内容将使用生成的函数。The resulting function will be used for the rest of this tutorial.

登录 AzureSign in to Azure

打开 Azure 门户。Open the Azure portal. 为此,请使用 Azure 帐户登录到 https://portal.azure.cnTo do this, sign in to https://portal.azure.cn with your Azure account.

自定义 HTTP 函数Customize your HTTP function

默认情况下,HTTP 触发的函数已配置为接受任何 HTTP 方法。By default, your HTTP-triggered function is configured to accept any HTTP method. 此外,还有一个采用 http://<yourapp>.chinacloudsites.cn/api/<funcname>?code=<functionkey> 格式的默认 URL。There is also a default URL of the form http://<yourapp>.chinacloudsites.cn/api/<funcname>?code=<functionkey>. 如果已完成快速入门教程,<funcname> 可能类似于“HttpTriggerJS1”。If you followed the quickstart, then <funcname> probably looks something like "HttpTriggerJS1". 在本部分,将修改该函数,以便只响应针对 /api/hello 路由发出的 GET 请求。In this section, you will modify the function to respond only to GET requests against /api/hello route instead.

  1. 在 Azure 门户中导航到该函数。Navigate to your function in the Azure portal. 在左侧导航栏中选择“集成”。Select Integrate in the left navigation.

    自定义 HTTP 函数

  2. 使用表中指定的 HTTP 触发器设置。Use the HTTP trigger settings as specified in the table.

    字段Field 示例值Sample value 说明Description
    允许的 HTTP 方法Allowed HTTP methods 选定的方法Selected methods 确定可以使用哪些 HTTP 方法来调用此函数Determines what HTTP methods may be used to invoke this function
    选定的 HTTP 方法Selected HTTP methods GETGET 只允许使用选定的 HTTP 方法来调用此函数Allows only selected HTTP methods to be used to invoke this function
    路由模板Route template /hello/hello 确定可以使用哪个路由来调用此函数Determines what route is used to invoke this function
    授权级别Authorization Level 匿名Anonymous 可选:无需 API 密钥便可访问函数Optional: Makes your function accessible without an API key

    Note

    请注意,并未在路由模板中包含 /api 基路径前缀,因为此操作由某个全局设置处理。Note that you did not include the /api base path prefix in the route template, as this is handled by a global setting.

  3. 单击“保存” 。Click Save.

可以在 Azure Functions HTTP 绑定中详细了解如何自定义 HTTP 函数。You can learn more about customizing HTTP functions in Azure Functions HTTP bindings.

测试 APITest your API

接下来,请测试函数,确定它是否适用于新的 API 图面。Next, test your function to see it working with the new API surface.

  1. 在左侧导航栏中单击该函数的名称,导航回到开发页。Navigate back to the development page by clicking on the function's name in the left navigation.
  2. 单击“获取函数 URL”并复制该 URL。Click Get function URL and copy the URL. 应会看到它现在使用了 /api/hello 路由。You should see that it uses the /api/hello route now.
  3. 将 URL 复制到新的浏览器标签页或偏好的 REST 客户端中。Copy the URL into a new browser tab or your preferred REST client. 浏览器默认使用 GET。Browsers will use GET by default.
  4. 在 URL 中将参数添加到查询字符串,如 /api/hello/?name=JohnAdd parameters to the query string in your URL e.g. /api/hello/?name=John
  5. 按“Enter”确认其正常工作。Hit 'Enter' to confirm that it is working. 应当可以看到响应“Hello John”You should see the response "Hello John"
  6. 也可以尝试使用其他 HTTP 方法调用终结点,确认是否未执行该函数。You can also try calling the endpoint with another HTTP method to confirm that the function is not executed. 为此,需要使用 REST 客户端,例如 cURL、Postman 或 Fiddler。For this, you will need to use a REST client, such as cURL, Postman, or Fiddler.

代理概述Proxies overview

在下一部分,将通过代理呈现 API。In the next section, you will surface your API through a proxy. Azure Functions 代理可将请求转发到其他资源。Azure Functions Proxies allows you to forward requests to other resources. 定义 HTTP 终结点的过程与定义 HTTP 触发器类似,但调用终结点时不能写入要执行的代码,而要提供远程实现的 URL。You define an HTTP endpoint just like with HTTP trigger, but instead of writing code to execute when that endpoint is called, you provide a URL to a remote implementation. 这样,便可以将多个 API 源组合到可方便客户端使用的单个 API 图面中。This allows you to compose multiple API sources into a single API surface which is easy for clients to consume. 如果要以微服务的形式构建 API,这种做法特别有效。This is particularly useful if you wish to build your API as microservices.

代理可以指向任何 HTTP 资源,例如:A proxy can point to any HTTP resource, such as:

若要了解有关代理的详细信息,请参阅使用 Azure Functions 代理To learn more about proxies, see Working with Azure Functions Proxies.

创建第一个代理Create your first proxy

在本部分,将创建充当整个 API 的前端的新代理。In this section, you will create a new proxy which serves as a frontend to your overall API.

设置前端环境Setting up the frontend environment

重复创建 Function App 中的步骤,创建要在其中创建代理的新 Function App。Repeat the steps to Create a function app to create a new function app in which you will create your proxy. 此新应用的 URL 将充当 API 的前端,之前编辑的 Function App 将充当后端。This new app's URL will serve as the frontend for our API, and the function app you were previously editing will serve as a backend.

  1. 在门户中导航到新的前端 Function App。Navigate to your new frontend function app in the portal.

  2. 选择“平台功能”,并选择“应用程序设置”。Select Platform Features and choose Application Settings.

  3. 向下滚动到存储键/值对的“应用程序设置”,然后使用键“HELLO_HOST”创建新设置。Scroll down to Application settings where key/value pairs are stored and create a new setting with key "HELLO_HOST". 将其值设置为后端 Function App 的主机,例如 <YourBackendApp>.chinacloudsites.cnSet its value to the host of your backend function app, such as <YourBackendApp>.chinacloudsites.cn. 这是前面在测试 HTTP 函数时复制的 URL 的一部分。This is part of the URL that you copied earlier when testing your HTTP function. 稍后会在配置中引用此设置。You'll reference this setting in the configuration later.

    Note

    建议在主机配置中使用应用设置,以防止对代理的环境依赖关系进行硬编码。App settings are recommended for the host configuration to prevent a hard-coded environment dependency for the proxy. 使用应用设置意味着可以在环境之间移动代理配置,并应用特定于环境的应用设置。Using app settings means that you can move the proxy configuration between environments, and the environment-specific app settings will be applied.

  4. 单击“保存” 。Click Save.

在前端上创建代理Creating a proxy on the frontend

  1. 在门户中导航回到前端 Function App。Navigate back to your frontend function app in the portal.

  2. 在左侧导航栏中,单击“代理”旁边的加号“+”。In the left-hand navigation, click the plus sign '+' next to "Proxies". 创建代理Creating a proxy

  3. 使用表中指定的代理设置。Use proxy settings as specified in the table.

    字段Field 示例值Sample value 说明Description
    NameName HelloProxyHelloProxy 仅用于管理的友好名称A friendly name used only for management
    路由模板Route template /api/remotehello/api/remotehello 确定可以使用哪个路由来调用此代理Determines what route is used to invoke this proxy
    后端 URLBackend URL https://%HELLO_HOST%/api/hello 指定请求应代理的终结点Specifies the endpoint to which the request should be proxied
  4. 请注意,代理不提供 /api 基路径前缀,必须在路由模板中包含此前缀。Note that Proxies does not provide the /api base path prefix, and this must be included in the route template.

  5. %HELLO_HOST% 语法将引用前面创建的应用设置。The %HELLO_HOST% syntax will reference the app setting you created earlier. 解析的 URL 将指向原始函数。The resolved URL will point to your original function.

  6. 单击创建Click Create.

  7. 可以通过复制代理 URL 或使用偏好的 HTTP 客户端在浏览器中对其进行测试来试验新代理。You can try out your new proxy by copying the Proxy URL and testing it in the browser or with your favorite HTTP client.

    1. 对于匿名函数,请使用:For an anonymous function use:
      1. https://YOURPROXYAPP.chinacloudsites.cn/api/remotehello?name="Proxies"
    2. 对于具有授权的函数,请使用:For a function with authorization use:
      1. https://YOURPROXYAPP.chinacloudsites.cn/api/remotehello?code=YOURCODE&name="Proxies"

创建模拟 APICreate a mock API

接下来,使用代理来为解决方案创建模拟 API。Next, you will use a proxy to create a mock API for your solution. 这样,客户端开发便可以继续进行,而无需完全实现后端。This allows client development to progress, without needing the backend fully implemented. 以后在开发时,可以创建新的 Function App 来支持此逻辑并将代理重定向到此逻辑。Later in development, you could create a new function app which supports this logic and redirect your proxy to it.

为了创建此模拟 API,我们将创建一个新代理,但这一次我们使用的是应用服务编辑器To create this mock API, we will create a new proxy, this time using the App Service Editor. 要开始,请在门户中导航到 Function App。To get started, navigate to your function app in the portal. 选择“平台功能”并在“开发工具”下找到“应用服务编辑器”。Select Platform features and under Development Tools find App Service Editor. 单击该按钮会在新选项卡中打开应用服务编辑器。Clicking this will open the App Service Editor in a new tab.

在左侧导航栏中选择 proxies.jsonSelect proxies.json in the left navigation. 这是用于存储所有代理的配置的文件。This is the file which stores the configuration for all of your proxies. 若要详细了解此文件,请参阅代理高级配置To learn more about this file, see Proxies advanced configuration.

到目前为止,proxies.json 应如下所示:If you've followed along so far, your proxies.json should look like the following:

{
    "$schema": "http://json.schemastore.org/proxies",
    "proxies": {
        "HelloProxy": {
            "matchCondition": {
                "route": "/api/remotehello"
            },
            "backendUri": "https://%HELLO_HOST%/api/hello"
        }
    }
}

接下来,请添加模拟 API。Next you'll add your mock API. 将 proxies.json 文件替换为以下内容:Replace your proxies.json file with the following:

{
    "$schema": "http://json.schemastore.org/proxies",
    "proxies": {
        "HelloProxy": {
            "matchCondition": {
                "route": "/api/remotehello"
            },
            "backendUri": "https://%HELLO_HOST%/api/hello"
        },
        "GetUserByName" : {
            "matchCondition": {
                "methods": [ "GET" ],
                "route": "/api/users/{username}"
            },
            "responseOverrides": {
                "response.statusCode": "200",
                "response.headers.Content-Type" : "application/json",
                "response.body": {
                    "name": "{username}",
                    "description": "Awesome developer and master of serverless APIs",
                    "skills": [
                        "Serverless",
                        "APIs",
                        "Azure",
                        "Cloud"
                    ]
                }
            }
        }
    }
}

这会添加一个不带 backendUri 属性的新代理“GetUserByName”。This adds a new proxy, "GetUserByName", without the backendUri property. 此代理不会调用另一个资源,而是使用响应重写来修改代理的默认响应。Instead of calling another resource, it modifies the default response from Proxies using a response override. 也可以将请求和响应重写与后端 URL 结合使用。Request and response overrides can also be used in conjunction with a backend URL. 在代理需要修改标头、查询参数等元素的旧式系统时,这种做法特别有效。若要详细了解请求和响应重写,请参阅修改代理中的请求和响应This is particularly useful when proxying to a legacy system, where you might need to modify headers, query parameters, etc. To learn more about request and response overrides, see Modifying requests and responses in Proxies.

通过使用浏览器或偏好的 REST 客户端调用 <YourProxyApp>.chinacloudsites.cn/api/users/{username} 终结点来测试模拟 API。Test your mock API by calling the <YourProxyApp>.chinacloudsites.cn/api/users/{username} endpoint using a browser or your favorite REST client. 请务必将 {username} 替换为表示用户名的字符串值。Be sure to replace {username} with a string value representing a username.

后续步骤Next steps

本教程已介绍如何在 Azure Functions 中构建和自定义 API。In this tutorial, you learned how to build and customize an API on Azure Functions. 此外,还介绍了如何将多个 API(包括模拟 API)合并成统一的 API 图面。You also learned how to bring multiple APIs, including mocks, together as a unified API surface. 可以使用这些方法构建具有不同复杂性的 API,所有这些 API 都可在 Azure Functions 提供的无服务器计算模型上运行。You can use these techniques to build out APIs of any complexity, all while running on the serverless compute model provided by Azure Functions.

以下参考文档可以帮助进一步开发 API:The following references may be helpful as you develop your API further: