Lambda API is a lightweight web framework for AWS Lambda using AWS API Gateway Lambda Proxy Integration or ALB Lambda Target Support. This closely mirrors (and is based on) other web frameworks like Express.js and Fastify, but is significantly stripped down to maximize performance with Lambda's stateless, single run executions.
lambda-api@v1 is using AWS SDK v3. If you are using AWS SDK v2, please use lambda-api@v0.12.0.
// Require the framework and instantiate it const api = require('lambda-api')(); // Define a route api.get('/status', async (req, res) => { return { status: 'ok' }; }); // Declare your Lambda handler exports.handler = async (event, context) => { // Run the request return await api.run(event, context); };
For a full tutorial see How To: Build a Serverless API with Serverless, AWS Lambda and Lambda API.
Express.js, Fastify, Koa, Restify, and Hapi are just a few of the many amazing web frameworks out there for Node.js. So why build yet another one when there are so many great options already? One word: DEPENDENCIES.
These other frameworks are extremely powerful, but that benefit comes with the steep price of requiring several additional Node.js modules. Not only is this a bit of a security issue (see Beware of Third-Party Packages in Securing Serverless), but it also adds bloat to your codebase, filling your node_modules
directory with a ton of extra files. For serverless applications that need to load quickly, all of these extra dependencies slow down execution and use more memory than necessary. Express.js has 30 dependencies, Fastify has 12, and Hapi has 17! These numbers don't even include their dependencies' dependencies.
Lambda API has ZERO dependencies. None. Zip. Zilch.
Lambda API was written to be extremely lightweight and built specifically for SERVERLESS applications using AWS Lambda and API Gateway. It provides support for API routing, serving up HTML pages, issuing redirects, serving binary files and much more. Worried about observability? Lambda API has a built-in logging engine that can even periodically sample requests for things like tracing and benchmarking. It has a powerful middleware and error handling system, allowing you to implement just about anything you can dream of. Best of all, it was designed to work with Lambda's Proxy Integration, automatically handling all the interaction with API Gateway for you. It parses REQUESTS and formats RESPONSES, allowing you to focus on your application's core functionality, instead of fiddling with inputs and outputs.
You may have heard that a serverless "best practice" is to keep your functions small and limit them to a single purpose. I generally agree since building monolith applications is not what serverless was designed for. However, what exactly is a "single purpose" when it comes to building serverless APIs and web services? Should we create a separate function for our "create user" POST
endpoint and then another one for our "update user" PUT
endpoint? Should we create yet another function for our "delete user" DELETE
endpoint? You certainly could, but that seems like a lot of repeated boilerplate code. On the other hand, you could create just one function that handled all your user management features. It may even make sense (in certain circumstances) to create one big serverless function handling several related components that can share your VPC database connections.
Whatever you decide is best for your use case, Lambda API is there to support you. Whether your function has over a hundred routes, or just one, Lambda API's small size and lightning fast load time has virtually no impact on your function's performance. You can even define global wildcard routes that will process any incoming request, allowing you to use API Gateway or ALB to determine the routing. Yet despite its small footprint, it gives you the power of a full-featured web framework.
npm i lambda-api --save
Require the lambda-api
module into your Lambda handler script and instantiate it. You can initialize the API with the following options:
Property | Type | Description |
---|---|---|
base | String | Base path for all routes, e.g. base: 'v1' would prefix all routes with /v1 |
callbackName | String | Override the default callback query parameter name for JSONP calls |
logger | boolean or object | Enables default logging or allows for configuration through a Logging Configuration object. |
mimeTypes | Object | Name/value pairs of additional MIME types to be supported by the type() . The key should be the file extension (without the . ) and the value should be the expected MIME type, e.g. application/json |
serializer | Function | Optional object serializer function. This function receives the body of a response and must return a string. Defaults to JSON.stringify |
version | String | Version number accessible via the REQUEST object |
errorHeaderWhitelist | Array | Array of headers to maintain on errors |
s3Config | Object | Optional object to provide as config to S3 sdk. S3ClientConfig |
// Require the framework and instantiate it with optional version and base parameters const api = require('lambda-api')({ version: 'v1.0', base: 'v1' });
For detailed release notes see Releases.
Lambda API now supports API Gateway v2 payloads for use with HTTP APIs. The library automatically detects the payload, so no extra configuration is needed. Automatic compression has also been added and supports Brotli, Gzip and Deflate.
Lambda API now allows you to seamlessly switch between API Gateway and Application Load Balancers. New execution stacks enables method-based middleware and more wildcard functionality. Plus full support for multi-value headers and query string parameters.
Routes are defined by using convenience methods or the METHOD
method. There are currently eight convenience route methods: get()
, post()
, put()
, patch()
, delete()
, head()
, options()
and any()
. Convenience route methods require an optional route and one or more handler functions. A route is simply a path such as /users
. If a route is not provided, then it will default to /*
and will execute on every path. Handler functions accept a REQUEST
, RESPONSE
, and optional next()
argument. These arguments can be named whatever you like, but convention dictates req
, res
, and next
.
Multiple handler functions can be assigned to a path, which can be used to execute middleware for specific paths and methods. For more information, see Middleware and Execution Stacks.
Examples using convenience route methods:
api.get('/users', (req,res) => { // do something }) api.post('/users', (req,res) => { // do something }) api.delete('/users', (req,res) => { // do something }) api.get('/users', (req,res,next) => { // do some middleware next() // continue execution }), (req,res) => { // do something } ) api.post((req,res) => { // do something for ALL post requests })
Additional methods are support by calling METHOD
. Arguments must include an HTTP method (or array of methods), an optional route, and one or more handler functions. Like the convenience methods above, handler functions accept a REQUEST
, RESPONSE
, and optional next
argument.
api.METHOD('trace','/users', (req,res) => { // do something on TRACE }) api.METHOD(['post','put'],'/users', (req,res) => { // do something on POST -or- PUT }) api.METHOD('get','/users', (req,res,next) => { // do some middleware next() // continue execution }), (req,res) => { // do something } )
All GET
methods have a HEAD
alias that executes the GET
request but returns a blank body
. GET
requests should be idempotent with no side effects. The head()
convenience method can be used to set specific paths for HEAD
requests or to override default GET
aliasing.
Routes that use the any()
method or pass ANY
to api.METHOD
will respond to all HTTP methods. Routes that specify a specific method (such as GET
or POST
), will override the route for that method. For example:
api.any('/users', (req, res) => { res.send('any'); }); api.get('/users', (req, res) => { res.send('get'); });
A POST
to /users
will return "any", but a GET
request would return "get". Please note that routes defined with an ANY
method will override default HEAD
aliasing for GET
routes.
Lambda API supports both callback-style
and async-await
for returning responses to users. The RESPONSE object has several callbacks that will trigger a response (send()
, json()
, html()
, etc.) You can use any of these callbacks from within route functions and middleware to send the response:
api.get('/users', (req, res) => { res.send({ foo: 'bar' }); });
You can also return
data from route functions and middleware. The contents will be sent as the body:
api.get('/users', (req, res) => { return { foo: 'bar' }; });
If you prefer to use async/await
, you can easily apply this to your route functions.
Using return
:
api.get('/users', async (req, res) => { let users = await getUsers(); return users; });
Or using callbacks:
api.get('/users', async (req, res) => { let users = await getUsers(); res.send(users); });
If you like promises, you can either use a callback like res.send()
at the end of your promise chain, or you can simply return
the resolved promise:
api.get('/users', (req, res) => { getUsers().then((users) => { res.send(users); }); });
OR
api.get('/users', (req, res) => { return getUsers().then((users) => { return users; }); });
IMPORTANT: You must either use a callback like res.send()
OR return
a value. Otherwise the execution will hang and no data will be sent to the user. Also, be sure not to return undefined
, otherwise it will assume no response.
While callbacks like res.send()
and res.error()
will trigger a response, they will not necessarily terminate execution of the current route function. Take a look at the following example:
api.get('/users', (req, res) => { if (req.headers.test === 'test') { res.error('Throw an error'); } return { foo: 'bar' }; });
The example above would not have the intended result of displaying an error. res.error()
would signal Lambda API to execute the error handling, but the function would continue to run. This would cause the function to return
a response that would override the intended error. In this situation, you could either wrap the return in an else
clause, or a cleaner approach would be to return
the call to the error()
method, like so:
api.get('/users', (req, res) => { if (req.headers.test
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。
openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号