Calling RESTful APIs from inline AWS Lambda functions

AWS LogoSometimes we need to make calls to some RESTful APIs from an AWS Lamda function. Let’s say we use Node.js as our platform. On the surface, there are two ways to do it:

1. Use Node.js low-level http module’s HTTP client functionality. The problem is that the low-level API is cumbersome to use, especially if sending and receiving request/response payloads is involved. You have to read the chunks, assemble the buffers, react to events, etc.

2. Use a 3rd party utility module, such as request, which is a fine solution, except it means that you have to create a full blown AWS Lambda deployment package zip, upload it to S3, etc. If we are talking about a tiny Lambda function, it would be preferable to be able to define it as an inline function without building and uploading any packages.

There is one other solution, however. The runtime environment for AWS Lambda’s always includes the AWS SDK module and since many of the AWS services expose this or that kind of RESTful APIs, the module includes everything one needs to make high level HTTP calls to anything, not necessarily an AWS service. The only problem is that this low level functionality included in the AWS SDK is not very well documented. Luckily, it’s all JavaScript, which mean we have access to all the sources. A little bit of digging around and you can see how it includes a lot of very high level and at the same time generic functionality. To be able to call our own RESTful API we need to define it as a “service”. Then, we define our API endpoints on the service as “operations”, after which we can call those operations on our service as methods, just like any authentic AWS service provided in the SDK. For example:

There is plenty of functionality in the AWS SDK module. You can start learning it from looking at the sources in the aws-sdk module (lib/protocol/rest_json.js, lib/model/shape.js, lib/service.js and others), but it is quite easy to understand and you will no longer need to look into the source code very soon. I can say now that AWS SDK is now my HTTP client library of choice for AWS Lambda functions (especially those are not part of a larger package)!

1 thought on “Calling RESTful APIs from inline AWS Lambda functions

Comments are closed.