# Introduction to Amazon API Gateway ## 实验概览 在本实验中,您将创建一个简单的 FAQ 微服务。该微服务通过可以调用 AWS Lambda 函数的 Amazon API Gateway 终端节点,返回一个 JSON 对象,其中包含随机问答对。以下是该微服务的架构模式: ![alt text](figures/micro_service.png) 图片描述:用户向 AWS 云中的服务发送 HTTP 请求或 GET 请求。Amazon API Gateway 是接收该请求的第一个服务。Amazon API Gateway 将 HTTP 请求转换为 JSON,然后转发到 AWS Lambda 服务。用户定义的 AWS Lambda 函数处理请求,并向 Amazon API Gateway 返回 JSON 格式的响应。Amazon API Gateway 将从 AWS Lambda 接收到的 JSON 响应转换为要发送给用户的最终 HTTP 响应。 ## 目标 - 完成本实验后,您应能够: - 1.创建一个 AWS Lambda 函数。 - 2.创建一个 Amazon API Gateway 终端节点。 - 3.借助 Amazon CloudWatch 调试 API Gateway 和 Lambda。 ## 实验环境 Amazon API Gateway 和 AWS Lambda 使用 Amazon API Gateway 的微服务包含一个定义的资源和 API Gateway 中关联的方法(GET、POST、PUT 等)以及后端目标。在本实验中,后端目标是一个 AWS Lambda 函数。但是,后端目标可以是任何其他 HTTP 终端节点(第三方 API 或侦听 Web 服务器)、AWS 服务代理或用作占位符的模拟集成。 本实验中使用的服务 Amazon API Gateway Amazon API Gateway 是 AWS 提供的一项托管服务,借助此服务,可轻松创建、部署和维护 API。 Amazon API Gateway 包含以下功能: 转换传入 API 请求的正文和标头以匹配后端系统。 转换传出 API 响应的正文和标头以匹配 API 要求。 通过 AWS Identity and Access Management 控制 API 访问。 创建和应用 API 密钥以用于第三方开发。 启用 Amazon CloudWatch 集成以实现 API 监控。 通过 Amazon CloudFront 缓存 API 响应以缩短响应时间。 将 API 部署到多个阶段,可轻松区分开发、测试、生产和版本控制。 将自定义域连接到 API。 定义模型以帮助对 API 请求和响应转换进行标准化处理。 AWS Lambda AWS Lambda 是一项由事件驱动的无服务器计算服务,让您可以为几乎任何类型的应用程序或后端服务运行代码,而无需预置或管理服务器。您可以通过 200 多种 AWS 服务和软件即服务 (SaaS) 应用程序触发 Lambda,并且只需按实际使用量付费。这些事件可能包括状态更改或更新,例如用户将商品加购到电子商务网站上的购物车中。您可以使用 AWS Lambda 通过自定义逻辑来扩展其他 AWS 服务,或创建您自己的按 AWS 规模、性能和安全性运行的后端服务。AWS Lambda 自动运行代码来响应多个事件,例如,通过 Amazon API Gateway 发送的 HTTP 请求、Amazon Simple Storage Service (Amazon S3) 存储桶中的对象修改、Amazon DynamoDB 中的表更新,以及 AWS Step Functions 中的状态转换。 AWS Lambda 包含以下功能: 用自定义逻辑扩展其他 AWS 服务。 构建自定义后端服务。 自带代码。 完全自动化管理。 内置容错能力。 将功能打包并部署为容器映像。 弹性伸缩。 连接到关系数据库。 对性能进行精细控制。 连接到共享文件系统。 编排多个函数。 将安全模型与 AWS Identity and Access Management (IAM) 集成。 对代码使用信任和完整性控制。 将 Lambda 与您喜欢的操作工具集成。 监控和可观测性。 ## 任务 1:创建 Lambda 函数 在本任务中,您将使用 AWS Lambda 控制台通过实验提供的代码创建一个函数,并完成配置以与 Amazon API Gateway 配合使用。 ### 任务 1.1:创建初始 Lambda 函数 在 AWS 管理控制台顶部的搜索栏中,搜索并选择 Lambda。 - 选择 Create a function(创建函数)。 了解详情:蓝图是指用于编写 Lambda 函数的代码模板。蓝图是为标准的 Lambda 触发器(例如创建 Alexa 技能和处理 Amazon Kinesis Firehose 流)提供的。本实验提供了一个预先编写好的 Lambda 函数供您使用。 - 选择 Author from scratch(从头开始编写)。 在 Basic information(基本信息)部分,进行以下配置: - 对于 Function name(函数名称),输入 FAQ。 - 对于 Runtime(运行时),选择 Node.js 16.x。 - 展开 Change default execution role(更改默认执行角色)。 - 对于 Execution role(执行角色),选择 Use an existing role(使用现有角色)。 - 对于 Existing role(现有角色),选择 lambda-basic-execution。 - 选择 Create function(创建函数)。 - Lambda 控制台显示一个页面来配置您的函数。 注意:如果您在创建 Lambda 函数时遇到错误,请检查函数名称,名称应为 FAQ。 - 选择 Code(代码)选项卡。 - 在 Code source(代码源)窗口中,选择(或双击)index.js 文件。 - 删除 index.js 选项卡下显示的默认内容。 - 复制下面显示的代码并将其粘贴到 index.js 选项卡中。 ``` var json = { "service": "lambda", "reference": "https://aws.amazon.com/lambda/faqs/", "questions": [{ "q": "What is AWS Lambda?", "a": "AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume - there is no charge when your code is not running. With Lambda, you can run code for virtually any type of application or backend service - all with zero administration. Just upload your code and Lambda takes care of everything required to run and scale your code with high availability. You can set up your code to automatically trigger from other AWS services or call it directly from any web or mobile app." },{ "q":"What events can trigger an AWS Lambda function?", "a":"You can use AWS Lambda to respond to table updates in Amazon DynamoDB, modifications to objects in Amazon S3 buckets, logs arriving in Amazon CloudWatch logs, incoming emails to Amazon Simple Email Service, notifications sent from Amazon SNS, messages arriving in an Amazon Kinesis stream, client data synchronization events in Amazon Cognito, and custom events from mobile applications, web applications, or other web services. You can also invoke a Lambda function on a defined schedule using the AWS Lambda console." },{ "q":"When should I use AWS Lambda versus Amazon EC2?", "a":"Amazon Web Services offers a set of compute services to meet a range of needs. Amazon EC2 offers flexibility, with a wide range of instance types and the option to customize the operating system, network and security settings, and the entire software stack, allowing you to easily move existing applications to the cloud. With Amazon EC2 you are responsible for provisioning capacity, monitoring fleet health and performance, and designing for fault tolerance and scalability. AWS Elastic Beanstalk offers an easy-to-use service for deploying and scaling web applications in which you retain ownership and full control over the underlying EC2 instances. Amazon Elastic Container Service is a scalable management service that supports Docker containers and allows you to easily run distributed applications on a managed cluster of Amazon EC2 instances. AWS Lambda makes it easy to execute code in response to events, such as changes to Amazon S3 buckets, updates to an Amazon DynamoDB table, or custom events generated by your applications or devices. With Lambda you do not have to provision your own instances; Lambda performs all the operational and administrative activities on your behalf, including capacity provisioning, monitoring fleet health, applying security patches to the underlying compute resources, deploying your code, running a web service front end, and monitoring and logging your code. AWS Lambda provides easy scaling and high availability to your code without additional effort on your part." },{ "q":"What kind of code can run on AWS Lambda?", "a":"AWS Lambda offers an easy way to accomplish many activities in the cloud. For example, you can use AWS Lambda to build mobile back-ends that retrieve and transform data from Amazon DynamoDB, handlers that compress or transform objects as they are uploaded to Amazon S3, auditing and reporting of API calls made to any Amazon Web Service, and server-less processing of streaming data using Amazon Kinesis." },{ "q":"What languages does AWS Lambda support?", "a":"AWS Lambda supports code written in Node.js (JavaScript), Python, and Java (Java 8 compatible). Your code can include existing libraries, even native ones. Lambda functions can easily launch processes using languages supported by Amazon Linux, including Bash, Go, and Ruby. Please read our documentation on using Node.js, Python and Java." },{ "q":"Can I access the infrastructure that AWS Lambda runs on?", "a":"No. AWS Lambda operates the compute infrastructure on your behalf, allowing it to perform health checks, apply security patches, and do other routine maintenance." },{ "q":"How does AWS Lambda isolate my code?", "a":"Each AWS Lambda function runs in its own isolated environment, with its own resources and file system view. AWS Lambda uses the same techniques as Amazon EC2 to provide security and separation at the infrastructure and execution levels." },{ "q":"How does AWS Lambda secure my code?", "a":"AWS Lambda stores code in Amazon S3 and encrypts it at rest. AWS Lambda performs additional integrity checks while your code is in use." },{ "q":"What is an AWS Lambda function?", "a":"The code you run on AWS Lambda is uploaded as a Lambda function. Each function has associated configuration information, such as its name, description, entry point, and resource requirements. The code must be written in a stateless style i.e. it should assume there is no affinity to the underlying compute infrastructure. Local file system access, child processes, and similar artifacts may not extend beyond the lifetime of the request, and any persistent state should be stored in Amazon S3, Amazon DynamoDB, or another Internet-available storage service. Lambda functions can include libraries, even native ones." },{ "q":"Will AWS Lambda reuse function instances?", "a":"To improve performance, AWS Lambda may choose to retain an instance of your function and reuse it to serve a subsequent request, rather than creating a new copy. Your code should not assume that this will always happen." },{ "q":"What if I need scratch space on disk for my AWS Lambda function?", "a":"Each Lambda function receives 500MB of non-persistent disk space in its own /tmp directory." },{ "q":"Why must AWS Lambda functions be stateless?", "a":"Keeping functions stateless enables AWS Lambda to rapidly launch as many copies of the function as needed to scale to the rate of incoming events. While AWS Lambda's programming model is stateless, your code can access stateful data by calling other web services, such as Amazon S3 or Amazon DynamoDB." },{ "q":"Can I use threads and processes in my AWS Lambda function code?", "a":"Yes. AWS Lambda allows you to use normal language and operating system features, such as creating additional threads and processes. Resources allocated to the Lambda function, including memory, execution time, disk, and network use, must be shared among all the threads/processes it uses. You can launch processes using any language supported by Amazon Linux." },{ "q":"What restrictions apply to AWS Lambda function code?", "a":"Lambda attempts to impose few restrictions on normal language and operating system activities, but there are a few activities that are disabled: Inbound network connections are managed by AWS Lambda, only TCP/IP sockets are supported, and ptrace (debugging) system calls are restricted. TCP port 25 traffic is also restricted as an anti-spam measure." },{ "q":"How do I create an AWS Lambda function using the Lambda console?", "a":"You can author the code for your function using the inline editor in the AWS Lambda console. You can also package the code (and any dependent libraries) as a ZIP and upload it using the AWS Lambda console from your local environment or specify an Amazon S3 location where the ZIP file is located. Uploads must be no larger than 50MB (compressed). You can use the AWS Eclipse plugin to author and deploy Lambda functions in Java and Node.js. If you are using Node.js, you can author the code for your function using the inline editor in the AWS Lambda console. Go to the console to get started." },{ "q":"How do I create an AWS Lambda function using the Lambda CLI?", "a":"You can package the code (and any dependent libraries) as a ZIP and upload it using the AWS CLI from your local environment, or specify an Amazon S3 location where the ZIP file is located. Uploads must be no larger than 50MB (compressed). Visit the Lambda Getting Started guide to get started." },{ "q":"Which versions of Python are supported?", "a":"Lambda provides a Python 2.7-compatible runtime to execute your Lambda functions. Lambda will include the latest AWS SDK for Python (boto3) by default." },{ "q":"How do I compile my AWS Lambda function Java code?", "a":"You can use standard tools like Maven or Gradle to compile your Lambda function. Your build process should mimic the same build process you would use to compile any Java code that depends on the AWS SDK. Run your Java compiler tool on your source files and include the AWS SDK 1.9 or later with transitive dependencies on your classpath. For more details, see our documentation." },{ "q":"What is the JVM environment Lambda uses for execution of my function?", "a":"Lambda provides the Amazon Linux build of openjdk 1.8." } ] } exports.handler = function(event, context) { var rand = Math.floor(Math.random() * json.questions.length); console.log("Quote selected: ", rand); var response = { body: JSON.stringify(json.questions[rand]) }; console.log(response); context.succeed(response); }; ``` - 查看代码。 - 它将执行以下步骤: 定义一个常见问题 (FAQ) 列表。 返回一个随机 FAQ。 - 选择 Deploy(部署)。 ### 任务 1.2:创建一个 API Gateway 终端节点 了解详情:API 终端节点是指 API 的主机名。API 终端节点可以是边缘优化或区域类型,具体取决于您的大部分 API 流量的源头位置。您可在创建 API 时选择特定的终端节点类型。 - 选择 Configuration(配置)选项卡。 - 选择 General configuration(常规配置),然后选择 Edit(编辑)。 - 对于 Description(描述),输入 Provide a random FAQ。 - 选择 Save(保存)。 - AWS Lambda 函数可以由各种活动自动触发,例如 Amazon Kinesis 接收数据或者在 Amazon DynamoDB 数据库中更新数据。在本实验中,每当调用 API Gateway 时,都会触发 Lambda 函数。 - 找到控制台页面顶部的 Function overview(函数概览)部分。 - 选择 Add trigger(添加触发器),然后配置以下各项: - 对于 Select a source(选择源),选择 API Gateway。 - 对于 Intent(意图),选择 Create a new API(创建新 API)。 - 对于 API type(API 类型),选择 REST API。 - 对于 Security(安全性),选择 Open(开放)。 - 展开 Additional settings(其他设置)。 - 对于 API name(API 名称),输入 FAQ-API。 - 对于 Deployment stage(部署阶段),输入 myDeployment。 - 选择 Add(添加)。 ## 任务 2:测试 Lambda 函数 在此任务中,您将测试 Lambda 函数,如果测试成功,将显示 FAQ Lambda 函数页面。 - 在 Configuration(配置)选项卡中,选择左侧导航菜单中的 Triggers(触发器)。 - 在 Triggers(触发器)部分,找到 API Gateway,然后展开 Details(详细信息)以查看 API 的详细信息。 - 将 API endpoint(API 终端节点)复制到剪贴板,然后: 在新的浏览器标签页中,粘贴 API endpoint(API 终端节点)。 按 Enter 转到该 URL。 系统会打开一个新的浏览器标签页。 网页上显示了 Lambda 代码的随机 FAQ 条目。 例如,类似于以下文本: - q "What languages does AWS Lambda support?" a "AWS Lambda supports code written in Node.js (JavaScript), Python, and Java (Java 8 compatible). Your code can include existing libraries, even native ones. Lambda functions can easily launch processes using languages supported by Amazon Linux, including Bash, Go, and Ruby. Please read our documentation on using Node.js, Python and Java." Lambda 函数还可以单独进行测试。 - 关闭该 FAQ 浏览器标签页并返回到显示 AWS Lambda 管理控制台的 Web 浏览器标签页。 - 选择 Test(测试)选项卡并配置新测试事件。 - 在 Test event(测试事件)部分,进行以下配置: - 对于 Event name(事件名称),输入 BasicTest。 删除提供的键值。 - 保留一个空 {} 来表示一个空的 JSON 对象: ``` {} ``` - 选择 Save(保存)。 - 选择 Test(测试)。 - 在 Execution result: succeeded(执行结果: 成功)窗口中,展开 Details(详细信息)。 输出将显示包装在 body 参数内的 FAQ 条目。 “Execution result”(执行结果)下有两列。Summary(摘要)显示 AWS Lambda 函数的总执行时间以及使用的资源。Log output(日志输出)显示日志记录信息。本部分将包含所有控制台日志记录以及错误消息。 - 选择 Monitor(监控)选项卡。 - 选择 View CloudWatch Logs(查看 CloudWatch Logs)。 - 选择其中一个日志流。 您将看到在 AWS Lambda 管理控制台中显示的相同事件数据。检查每行的内容以查看日志信息。 ## 总结 恭喜!您已经完成了本实验,并使用 Amazon API Gateway 和 AWS Lambda 成功创建了微服务。 - 现在,您知道了如何: 创建一个 AWS Lambda 函数。 创建一个 Amazon API Gateway 终端节点。 借助 Amazon CloudWatch 调试 API Gateway 和 Lambda。