Serverless Design Patterns and Best Practices
上QQ阅读APP看书,第一时间看更新

Wiring handler.py to Lambda via API Gateway

Next, we need to wire up our API endpoints to Lambda and our handler.py entry point. This wiring looks like this in a serverless.yml configuration file:

functions:
HandleSession:
handler: handler.session
events:
- http:
path: session
method: get
cors: true
- http:
path: session
method: post
cors: true
HandleSessionDetail:
handler: handler.session_detail
events:
- http:
path: session/{id}
method: get
cors: true
request:
parameters:
paths:
id: true
- http:
path: session/{id}
method: delete
cors: true
request:
parameters:
paths:
id: true

We define two Lambda functions that have different configuration options, HandleSession and HandleSessionDetail.

Under each function's name, there are multiple statements that control configuration. Look at both sections and you'll notice the handler: statement, which instructs Lambda what code to call when the Lambda function is executed. For both, we'll be running one of the Python functions in handler.py that we covered in the preceding code snippet.

But what calls these Lambda functions in the first place? The events: section is responsible for setting up invocation points and making the connection between a particular event and our Lambda function. Across the FaaS landscape, functions are invoked in response to an event. In the AWS landscape, the number of events that can trigger a Lambda function is quite large. In this scenario, we are configuring events to be HTTP endpoints with a particular path and HTTP method. API Gateway is the proxy that will provide us with unique HTTPS URLs, which get wired up to our Lambda functions according to our configuration. As you read through the configuration, our design and intent should be apparent. Again, there are a seemingly infinite number of ways to set up an API with these technologies and this example just scratches the surface to discuss the overall pattern.

Because the frontend JavaScript code will be making HTTP requests to the serverless backend, which is hosted on a different domain, CORS will need to be set up for each API endpoint. Controlling CORS is simple to do by adding cors: true for each endpoint in serverless.yml. In addition to this setting, the application code will explicitly need to return the proper headers in the responses.