以下过程介绍如何使用 API Gateway 生成的 JavaScript SDK。
注意
这些说明假设您已完成为 API Gateway 中的 REST API 生成 SDK中的说明。
重要
如果您的 API 仅定义了 ANY 方法,则生成的开发工具包将不会包含 apigClient.js
文件,您将需要自己定义 ANY 方法。
要安装,请启动并调用由 API Gateway 为 REST API 生成的 JavaScript 开发工具包
-
提取您之前下载的 API Gateway 生成的 .zip 文件中的内容。
-
针对 API Gateway 生成的开发工具包将调用的所有方法启用跨源资源共享 (CORS)。有关说明,请参阅 针对 API Gateway 中的 REST API 的 CORS。
-
在您的网页中,添加对以下脚本的引用。
<script type="text/javascript" src="lib/axios/dist/axios.standalone.js"></script> <script type="text/javascript" src="lib/CryptoJS/rollups/hmac-sha256.js"></script> <script type="text/javascript" src="lib/CryptoJS/rollups/sha256.js"></script> <script type="text/javascript" src="lib/CryptoJS/components/hmac.js"></script> <script type="text/javascript" src="lib/CryptoJS/components/enc-base64.js"></script> <script type="text/javascript" src="lib/url-template/url-template.js"></script> <script type="text/javascript" src="lib/apiGatewayCore/sigV4Client.js"></script> <script type="text/javascript" src="lib/apiGatewayCore/apiGatewayClient.js"></script> <script type="text/javascript" src="lib/apiGatewayCore/simpleHttpClient.js"></script> <script type="text/javascript" src="lib/apiGatewayCore/utils.js"></script> <script type="text/javascript" src="apigClient.js"></script>
-
在代码中,使用类似于以下内容的代码初始化 API Gateway 生成的开发工具包。
var apigClient = apigClientFactory.newClient();
要使用 AWS 凭证初始化 API Gateway 生成的开发工具包,请使用类似于以下内容的代码。如果您使用 AWS 凭证,系统将签署针对 API 的所有请求。
var apigClient = apigClientFactory.newClient({ accessKey: 'ACCESS_KEY', secretKey: 'SECRET_KEY', });
要将 API 密钥用于 API Gateway 生成的开发工具包,您可以使用类似于以下内容的代码,将 API 密钥作为参数传递给
Factory
对象。如果您使用 API 密钥,它将被指定为x-api-key
标头的一部分,并且系统将签署针对 API 的所有请求。这意味着您必须为每个请求设置相应的 CORS Accept 标头。var apigClient = apigClientFactory.newClient({ apiKey: 'API_KEY' });
-
使用类似于以下内容的代码调用 API Gateway 中的 API 方法。每次调用都会返回成功和失败回调的承诺。
var params = { // This is where any modeled request parameters should be added. // The key is the parameter name, as it is defined in the API in API Gateway. param0: '', param1: '' }; var body = { // This is where you define the body of the request, }; var additionalParams = { // If there are any unmodeled query parameters or headers that must be // sent with the request, add them here. headers: { param0: '', param1: '' }, queryParams: { param0: '', param1: '' } }; apigClient.
methodName
(params, body, additionalParams) .then(function(result){ // Add success callback code here. }).catch( function(result){ // Add error callback code here. });此处,
methodName
由方法请求的资源路径和 HTTP 动词构成。对于 SimpleCalc API,API 方法的开发工具包方法为1. GET /?a=...&b=...&op=... 2. POST / { "a": ..., "b": ..., "op": ...} 3. GET /{a}/{b}/{op}
相应的开发工具包方法如下所示:
1. rootGet(params); // where params={"a": ..., "b": ..., "op": ...} is resolved to the query parameters 2. rootPost(null, body); // where body={"a": ..., "b": ..., "op": ...} 3. aBOpGet(params); // where params={"a": ..., "b": ..., "op": ...} is resolved to the path parameters