Building Your First Serverless Service With AWS Lambda Functions
Many developers have some familiarity with AWS Lambda functions. While relatively easy to set up, navigating the vast AWS ecosystem can be challenging. The sheer number of components makes it difficult to grasp the bigger picture and integrate Lambda functions smoothly into a standard web application.
The Serverless Framework simplifies this process considerably. It streamlines the creation, deployment, and—most importantly—the integration of Lambda functions into web applications. While its capabilities extend far beyond this, this article focuses on these core aspects. This introduction hopefully sparks your interest to explore Serverless's broader functionalities. If you're new to Lambda, consider reviewing this AWS introductory guide first.
The quick start guide provides the best instructions for initial installation and setup. Following it, you should be operational within 5-10 minutes, even if you need to create an AWS account.
Your First Serverless Service
Before diving into advanced features like file uploads and S3 buckets, let's create a basic Lambda function, connect it to an HTTP endpoint, and invoke it from an existing web application. The function won't perform any complex tasks, but it effectively demonstrates the ease of use of the Serverless Framework.
Begin by creating your service. In your web application (using create-react-app
is a quick way to start a new one), create a directory for your services (e.g., a lambda
folder). Navigate to this directory in your terminal and run:
sls create -t aws-nodejs --path hello-world
This creates a hello-world
directory. Let's examine its contents.
handler.js
contains an asynchronous function that returns a message. You could deploy this Lambda function immediately using sls deploy
, making it invokable. However, let's first make it accessible via the web.
Manual AWS configuration would involve setting up an AWS API Gateway endpoint and stage, then configuring it to proxy to your Lambda. Serverless handles all this with minimal configuration.
Still in the hello-world
directory, open serverless.yaml
.
The configuration file includes boilerplate for common setups. Uncomment the HTTP entries and specify a more descriptive path:
functions: hello: handler: handler.hello events: - http: path: msg method: get
That's it. Serverless manages the underlying complexities.
CORS Configuration
To invoke the function from front-end JavaScript using the Fetch API, CORS configuration is necessary. This section outlines the process.
Add cors: true
below the configuration:
functions: hello: handler: handler.hello events: - http: path: msg method: get cors: true
This configures CORS on the API endpoint, enabling cross-origin communication.
CORS Lambda Adjustment
While the HTTP endpoint is CORS-enabled, the Lambda function must return the appropriate headers. Let's automate this by modifying handler.js
:
const CorsResponse = obj => ({ statusCode: 200, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*", "Access-Control-Allow-Methods": "*" }, body: JSON.stringify(obj) }); module.exports.hello = async event => { return CorsResponse("HELLO, WORLD!"); };
Now, the Lambda function's response is processed through this function.
Run sls deploy
from the hello-world
directory to deploy the Lambda function.
The sls info
command provides the function's URL, eliminating the need to manually locate it in the AWS console. The URL will resemble:
<code>https://6xpmc3g0ch.execute-api.us-east-1.amazonaws.com/dev/msg</code>
Invoking the Function
Now, let's invoke the function from a web application using Fetch:
fetch("https://6xpmc3g0ch.execute-api.us-east-1.amazonaws.com/dev/msg") .then(resp => resp.json()) .then(resp => { console.log(resp); });
The message should appear in the browser's developer console.
Let's repeat this process, creating a more practical function: a Lambda that resizes images and uploads them to an S3 bucket. Instead of triggering on S3 uploads, the user uploads directly to the Lambda, eliminating the need for client-side AWS SDK resources.
Building a Practical Lambda
Let's create a new service (e.g., cover-art
):
sls create -t aws-nodejs --path cover-art
Add the HTTP endpoint path (POST method for file uploads) and enable CORS:
events: - http: path: upload method: post cors: true
Grant the Lambda access to your S3 bucket(s) by uncommenting and modifying the iamRoleStatements
section in serverless.yaml
:
iamRoleStatements: - Effect: "Allow" Action: - "s3:*" Resource: ["arn:aws:s3:::your-bucket-name/*"]
Configure the API Gateway to accept multipart/form-data
:
provider: name: aws runtime: nodejs12.x apiGateway: binaryMediaTypes: - 'multipart/form-data'
Rename the function in serverless.yaml
and handler.js
to upload
.
Implementing the Code
Install required packages:
npm i jimp uuid lambda-multipart-parser
Implement an S3 upload helper function and the main upload function in handler.js
(the complete code is too extensive to include here, but it's available in the original prompt).
Use a library like react-dropzone
on the client-side to handle file uploads (example code provided in the original prompt).
Optional: Bundling
Bundling your code reduces deployment size and improves performance. Install serverless-webpack
:
npm i serverless-webpack --save-dev
Add it to serverless.yaml
:
plugins: - serverless-webpack
Create webpack.config.js
(configuration provided in the original prompt). Redeploy to utilize webpack.
Conclusion
The Serverless Framework significantly simplifies the development and deployment of AWS Lambda functions. This introduction provides a foundation for further exploration of its capabilities. The resources mentioned in the original prompt offer valuable learning opportunities for deeper understanding.
The above is the detailed content of Building Your First Serverless Service With AWS Lambda Functions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

PHP templating often gets a bad rap for facilitating subpar code — but that doesn't have to be the case. Let’s look at how PHP projects can enforce a basic

Let’s attempt to coin a term here: "Static Form Provider." You bring your HTML
