What is Serverless?
Serverless computing allows you to build and run applications without managing servers. AWS Lambda executes your code in response to events and automatically manages the compute resources.
Setting Up AWS Lambda Function
// lambda-function.js
exports.handler = async (event) => {
const response = {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
message: 'Hello from Lambda!',
input: event
})
};
return response;
};
Creating API Gateway Endpoint
Steps to create a REST API:
- Create a new API in API Gateway
- Create a resource (e.g., /users)
- Create methods (GET, POST, etc.)
- Connect methods to Lambda function
- Deploy API to a stage
Lambda Function with Database
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event) => {
try {
const params = {
TableName: 'Users',
Item: {
id: event.requestContext.requestId,
name: JSON.parse(event.body).name,
email: JSON.parse(event.body).email,
createdAt: new Date().toISOString()
}
};
await dynamodb.put(params).promise();
return {
statusCode: 201,
body: JSON.stringify({ message: 'User created successfully' })
};
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ error: error.message })
};
}
};
Benefits of Serverless
- No Server Management: AWS handles infrastructure
- Auto-scaling: Scales automatically with traffic
- Cost-effective: Pay only for execution time
- High Availability: Built-in fault tolerance
Best Practices
- Keep functions small and focused
- Use environment variables for configuration
- Implement proper error handling
- Set appropriate timeout values
- Use Lambda layers for shared code