---
title: "AWS Serverless Application"
description: "Deploy a serverless application on AWS with Pulumi, AWS Lambda, and Amazon API Gateway in TypeScript, Python, Go, C#, YAML, or HCL."
url: "https://www.pulumi.com/dev/templates/serverless-application/aws/"
image: "https://www.pulumi.com/assets/og/dev/templates/serverless-application/aws.png"
---

# AWS Serverless Application

Deploy a serverless application on AWS with Pulumi, AWS Lambda, and Amazon API Gateway in TypeScript, Python, Go, C#, YAML, or HCL.

The AWS Serverless Application template scaffolds a Pulumi project that deploys a serverless web application to AWS. It provisions an [Amazon S3 bucket](https://www.pulumi.com/registry/packages/aws/api-docs/s3/bucket/) for static website hosting, an [AWS Lambda function](https://www.pulumi.com/registry/packages/aws/api-docs/lambda/function/) for the application backend, and an [Amazon API Gateway REST API](https://www.pulumi.com/registry/packages/aws/api-docs/apigateway/restapi/) that routes requests to the static content and the Lambda function. The template ships with a placeholder web page that displays the current time so the project deploys end to end out of the box.

![An architecture diagram of the AWS Serverless Application template](./architecture.svg)

## Before you begin

**TypeScript**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] An [AWS account](https://aws.amazon.com/free) with [programmatic access](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html)
- [x] The [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) (optional, but recommended and used in this guide)
- [x] Pulumi [configured with your AWS credentials](https://www.pulumi.com/registry/packages/aws/installation-configuration#credentials)
- [x] Permission to manage AWS Lambda, API Gateway, and IAM resources
- [x] A current version of [Node.js](https://nodejs.org/en/download) and [npm](https://www.npmjs.com/package/npm) installed locally

**Python**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] An [AWS account](https://aws.amazon.com/free) with [programmatic access](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html)
- [x] The [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) (optional, but recommended and used in this guide)
- [x] Pulumi [configured with your AWS credentials](https://www.pulumi.com/registry/packages/aws/installation-configuration#credentials)
- [x] Permission to manage AWS Lambda, API Gateway, and IAM resources
- [x] A current version of [Python](https://www.python.org/downloads/) and [pip](https://pip.pypa.io/en/stable/installation/), [Poetry](https://python-poetry.org/docs/) or [uv](https://docs.astral.sh/uv/getting-started/installation/) installed locally

**Go**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] An [AWS account](https://aws.amazon.com/free) with [programmatic access](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html)
- [x] The [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) (optional, but recommended and used in this guide)
- [x] Pulumi [configured with your AWS credentials](https://www.pulumi.com/registry/packages/aws/installation-configuration#credentials)
- [x] Permission to manage AWS Lambda, API Gateway, and IAM resources
- [x] A current version of [Go](https://go.dev/doc/install) installed locally

**C#**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] An [AWS account](https://aws.amazon.com/free) with [programmatic access](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html)
- [x] The [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) (optional, but recommended and used in this guide)
- [x] Pulumi [configured with your AWS credentials](https://www.pulumi.com/registry/packages/aws/installation-configuration#credentials)
- [x] Permission to manage AWS Lambda, API Gateway, and IAM resources
- [x] A current version of [.NET](https://dotnet.microsoft.com/en-us/download/dotnet) installed locally

**YAML**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] An [AWS account](https://aws.amazon.com/free) with [programmatic access](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html)
- [x] The [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) (optional, but recommended and used in this guide)
- [x] Pulumi [configured with your AWS credentials](https://www.pulumi.com/registry/packages/aws/installation-configuration#credentials)
- [x] Permission to manage AWS Lambda, API Gateway, and IAM resources

**HCL**

For this walkthrough, you'll need:

- [x] A current version of the [Pulumi CLI](https://www.pulumi.com/docs/install/) ([Pulumi HCL](https://www.pulumi.com/docs/iac/languages-sdks/hcl/) requires no additional runtime)
- [x] An [AWS account](https://aws.amazon.com/free) with [programmatic access](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html)
- [x] The [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) (optional, but recommended and used in this guide)
- [x] Pulumi [configured with your AWS credentials](https://www.pulumi.com/registry/packages/aws/installation-configuration#credentials)
- [x] Permission to manage AWS Lambda, API Gateway, and IAM resources

## Create a new project

Create a new [project](https://www.pulumi.com/docs/iac/concepts/projects/) from the template:

**TypeScript**

```bash
mkdir my-serverless-app; cd my-serverless-app
pulumi new serverless-aws-typescript
```

**Python**

```bash
mkdir my-serverless-app; cd my-serverless-app
pulumi new serverless-aws-python
```

**Go**

```bash
mkdir my-serverless-app; cd my-serverless-app
pulumi new serverless-aws-go
```

**C#**

```bash
mkdir my-serverless-app; cd my-serverless-app
pulumi new serverless-aws-csharp
```

**YAML**

```bash
mkdir my-serverless-app; cd my-serverless-app
pulumi new serverless-aws-yaml
```

**HCL**

```bash
mkdir my-serverless-app; cd my-serverless-app
pulumi new serverless-aws-hcl
```

The `pulumi new` command walks you through creating and configuring the new project and stack. A [stack](https://www.pulumi.com/docs/iac/concepts/stacks/) is an instance of a project, and you can have many of them (`dev`, `staging`, `prod`), each with its own [configuration](https://www.pulumi.com/docs/iac/concepts/config/) settings. Depending on the language, you may also be asked for your preferred package manager or toolchain.

This template's settings include:

**TypeScript / Python / Go / C# / YAML / HCL**

| Key | Description | Default |
| --- | --- | --- |
| `aws:region` | The AWS region to deploy into | `us-west-2` |

You can change values like these later with `pulumi config set`:

```bash
pulumi config set aws:region <value>
```

## Review the code

**TypeScript / Python / Go / C# / HCL**

When setup completes, you'll see a few files:

- `Pulumi.yaml` contains the project name and the language it's written in.
- `Pulumi.dev.yaml` contains the `dev` stack's settings, including the values you just entered.
- `index.ts` contains the program code that declares your cloud resources.

**YAML**

When setup completes, you'll see a few files:

- `Pulumi.yaml` contains the project name and the resources it declares.
- `Pulumi.dev.yaml` contains the `dev` stack's settings, including the values you just entered.

Take a moment to open them up and have a look. Here's what's in `index.ts`:

**TypeScript**

```typescript title="index.ts"
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import * as apigateway from "@pulumi/aws-apigateway";

// A Lambda function to invoke
const fn = new aws.lambda.CallbackFunction("fn", {
    callback: async (ev, ctx) => {
        return {
            statusCode: 200,
            body: new Date().toISOString(),
        };
    }
})

// An AWS provider for the REST API to deploy its resources with
const provider = new aws.Provider("provider", {
    region: aws.config.region,
});

// A REST API to route requests to HTML content and the Lambda function
const api = new apigateway.RestAPI("api", {
    routes: [
        { path: "/", localPath: "www"},
        { path: "/date", method: "GET", eventHandler: fn },
    ]
}, { providers: [provider] });

// The URL at which the REST API will be served.
export const url = api.url;
```

**Python**

```python title="__main__.py"
import json
import pulumi
import pulumi_aws as aws
import pulumi_aws_apigateway as apigateway

# An execution role to use for the Lambda function
role = aws.iam.Role("role", 
    assume_role_policy=json.dumps({
        "Version": "2012-10-17",
        "Statement": [{
            "Action": "sts:AssumeRole",
            "Effect": "Allow",
            "Principal": {
                "Service": "lambda.amazonaws.com",
            },
        }],
    }),
    managed_policy_arns=[aws.iam.ManagedPolicy.AWS_LAMBDA_BASIC_EXECUTION_ROLE])

# A Lambda function to invoke
fn = aws.lambda_.Function("fn",
    runtime="python3.12",
    handler="handler.handler",
    role=role.arn,
    code=pulumi.FileArchive("./function"))

# An AWS provider for the REST API to deploy its resources with
provider = aws.Provider("provider", region=aws.config.region)

# A REST API to route requests to HTML content and the Lambda function
api = apigateway.RestAPI("api",
  routes=[
    apigateway.RouteArgs(path="/", local_path="www"),
    apigateway.RouteArgs(path="/date", method=apigateway.Method.GET, event_handler=fn)
  ],
  opts=pulumi.ResourceOptions(providers=[provider]))

# The URL at which the REST API will be served.
pulumi.export("url", api.url)
```

**Go**

```go title="main.go"
package main

import (
	"encoding/json"

	"github.com/pulumi/pulumi-aws-apigateway/sdk/v3/go/apigateway"
	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws"
	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/config"
	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/iam"
	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/lambda"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {
		// An execution role to use for the Lambda function
		policy, err := json.Marshal(map[string]interface{}{
			"Version": "2012-10-17",
			"Statement": []map[string]interface{}{
				map[string]interface{}{
					"Action": "sts:AssumeRole",
					"Effect": "Allow",
					"Principal": map[string]interface{}{
						"Service": "lambda.amazonaws.com",
					},
				},
			},
		})
		if err != nil {
			return err
		}

		role, err := iam.NewRole(ctx, "role", &iam.RoleArgs{
			AssumeRolePolicy: pulumi.String(policy),
			ManagedPolicyArns: pulumi.StringArray{
				iam.ManagedPolicyAWSLambdaBasicExecutionRole,
			},
		})
		if err != nil {
			return err
		}

		// A Lambda function to invoke
		fn, err := lambda.NewFunction(ctx, "fn", &lambda.FunctionArgs{
			Runtime: pulumi.String("python3.12"),
			Handler: pulumi.String("handler.handler"),
			Role:    role.Arn,
			Code:    pulumi.NewFileArchive("./function"),
		})
		if err != nil {
			return err
		}

		// An AWS provider for the REST API to deploy its resources with
		provider, err := aws.NewProvider(ctx, "provider", &aws.ProviderArgs{
			Region: pulumi.String(config.GetRegion(ctx)),
		})
		if err != nil {
			return err
		}

		// A REST API to route requests to HTML content and the Lambda function
		localPath := "www"
		method := apigateway.MethodGET
		api, err := apigateway.NewRestAPI(ctx, "api", &apigateway.RestAPIArgs{
			Routes: []apigateway.RouteArgs{
				apigateway.RouteArgs{Path: "/", LocalPath: &localPath},
				apigateway.RouteArgs{Path: "/date", Method: &method, EventHandler: fn},
			},
		}, pulumi.Providers(provider))
		if err != nil {
			return err
		}

		// The URL at which the REST API will be served
		ctx.Export("url", api.Url)
		return nil
	})
}
```

**C#**

```csharp title="Program.cs"
using System.Collections.Generic;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;
using AwsApiGateway = Pulumi.AwsApiGateway;

return await Deployment.RunAsync(() => 
{
    var role = new Aws.Iam.Role("role", new()
    {
        AssumeRolePolicy = JsonSerializer.Serialize(new Dictionary<string, object?>
        {
            ["Version"] = "2012-10-17",
            ["Statement"] = new[]
            {
                new Dictionary<string, object?>
                {
                    ["Action"] = "sts:AssumeRole",
                    ["Effect"] = "Allow",
                    ["Principal"] = new Dictionary<string, object?>
                    {
                        ["Service"] = "lambda.amazonaws.com",
                    },
                },
            },
        }),
        ManagedPolicyArns = new[]
        {
            "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
        },
    });

    var fn = new Aws.Lambda.Function("fn", new()
    {
        Runtime = "python3.12",
        Handler = "handler.handler",
        Role = role.Arn,
        Code = new FileArchive("./function"),
    });

    var provider = new Aws.Provider("provider", new()
    {
        Region = new Config("aws").Require("region"),
    });

    var api = new AwsApiGateway.RestAPI("api", new()
    {
        Routes =
        {
            new AwsApiGateway.Inputs.RouteArgs
            {
                Path = "/",
                LocalPath = "www",
            },
            new AwsApiGateway.Inputs.RouteArgs
            {
                Path = "/date",
                Method = AwsApiGateway.Method.GET,
                EventHandler = fn,
            },
        },
    }, new ComponentResourceOptions
    {
        Providers = { provider },
    });

    return new Dictionary<string, object?>
    {
        ["url"] = api.Url,
    };
});
```

**YAML**

```yaml title="Pulumi.yaml"
name: my-project
description: A Pulumi YAML program to deploy a serverless application on AWS
runtime: yaml
resources:
  # An execution role to use for the Lambda function
  role:
    type: aws:iam:Role
    properties:
      assumeRolePolicy:
        fn::toJSON:
          Version: "2012-10-17"
          Statement:
            - Action: sts:AssumeRole
              Effect: Allow
              Principal:
                Service: lambda.amazonaws.com
      managedPolicyArns:
      - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

  # A Lambda function to invoke
  fn:
    type: aws:lambda:Function
    properties:
      runtime: python3.12
      handler: handler.handler
      role: ${role.arn}
      code:
        fn::fileArchive: ./function

  # An AWS provider for the REST API to deploy its resources with
  provider:
    type: pulumi:providers:aws
    properties:
      region: ${aws:region}

  # A REST API to route requests to HTML content and the Lambda function
  api:
    type: aws-apigateway:RestAPI
    properties:
      routes:
      - path: /
        localPath: www
      - path: /date
        method: GET
        eventHandler: ${fn}
    options:
      providers:
      - ${provider}

outputs:
  # The URL at which the REST API will be served.
  url: ${api.url}
```

**HCL**

```hcl title="main.tf"
terraform {
  required_providers {
    aws = {
      source = "pulumi/aws"
    }
    aws-apigateway = {
      source = "pulumi/aws-apigateway"
    }
  }
}

# An execution role to use for the Lambda function
resource "aws_iam_role" "role" {
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action    = "sts:AssumeRole"
      Effect    = "Allow"
      Principal = { Service = "lambda.amazonaws.com" }
    }]
  })
  managed_policy_arns = ["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]
}

# A Lambda function to invoke
resource "aws_lambda_function" "fn" {
  runtime  = "python3.12"
  handler  = "handler.handler"
  role     = aws_iam_role.role.arn
  filename = filearchive("./function")
}

# The AWS region to deploy into
data "aws_region" "current" {}

# An AWS provider for the REST API to deploy its resources with
provider "aws" {
  alias  = "api"
  region = data.aws_region.current.region
}

# A REST API to route requests to HTML content and the Lambda function
resource "aws-apigateway_rest_a_p_i" "api" {
  providers = [aws.api]

  routes {
    path       = "/"
    local_path = "www"
  }

  routes {
    path          = "/date"
    method        = "GET"
    event_handler = aws_lambda_function.fn
  }
}

# The URL at which the REST API will be served.
output "url" {
  value = aws-apigateway_rest_a_p_i.api.url
}
```

## Deploy the project

Deploy with [`pulumi up`](https://www.pulumi.com/docs/iac/cli/commands/pulumi_up). It starts with a preview of what it's about to create and asks before it changes anything. Choose `yes` to deploy.

```bash
$ pulumi up
```

Pulumi adds a random suffix to most resource names, so the Lambda function `fn` becomes something like `fn-4f8a2c1`. This is [autonaming](https://www.pulumi.com/docs/iac/concepts/resources/names/#autonaming). It lets you deploy the same program to more than one stack, and lets Pulumi create a replacement before it deletes the old resource, without names colliding.

When it finishes, Pulumi prints the stack's [outputs](https://www.pulumi.com/docs/iac/concepts/stacks/#outputs), values it only knows once the resources exist:

**`url`**

The HTTPS URL of the application, served by API Gateway.

Read one any time with `pulumi stack output <name>`, or pass it to another command. This opens the app in your browser:

**macOS**

```bash
$ open $(pulumi stack output url)
```

**Linux**

```bash
$ xdg-open $(pulumi stack output url)
```

**Windows**

```powershell
> Start-Process $(pulumi stack output url)
```

The page gets the time from the Lambda function at the `/date` path. Call it from the terminal with `curl`; it prints the current time:

**Linux / macOS**

```bash
$ curl -s "$(pulumi stack output url)date"
```

**Windows**

```powershell
> curl.exe -s "$(pulumi stack output url)date"
```

**Need help?**

If `pulumi up` reports `No valid credential sources found` or `ExpiredToken`, sign in again:

```bash
$ aws login
```

Still stuck? [Let us know](https://github.com/pulumi/docs/issues/new).

## Customize the project

The template has no [configuration](https://www.pulumi.com/docs/iac/concepts/config/) settings of its own; `aws:region` is the only one `pulumi new` sets. It deploys the website from the `www` folder.

**TypeScript**

The Lambda function's code is the `callback` in `index.ts`.

**Python / Go / C# / YAML / HCL**

The Lambda function's code is `function/handler.py`. It's Python, whatever language the program is written in.

### Using your own web content

If you already have a website you'd like to deploy, you can do so by replacing the contents of the `www` folder and redeploying with `pulumi up`.

### Customizing the application's functionality

You can customize the placeholder website by editing the Lambda function to perform another action, such as displaying a countdown to a future time. You can also add new functionality by creating a new Lambda function, adding a new path to the REST API, and updating the HTML to call the new path.

To start small, change the format of the time the function returns:

**TypeScript**

In `index.ts`:

```diff
const fn = new aws.lambda.CallbackFunction("fn", {
    callback: async (ev, ctx) => {
        return {
            statusCode: 200,
-           body: new Date().toISOString(),
+           body: new Date().toUTCString(),
        };
```

**Python / Go / C# / YAML / HCL**

In `function/handler.py`:

```diff
def handler(event, context):
    return {
        'statusCode': 200,
-       'body': datetime.now().isoformat()
+       'body': datetime.now().ctime()
    }
```

Deploy the change and call `/date` again:

**Linux / macOS**

```bash
$ pulumi up
$ curl -s "$(pulumi stack output url)date"
```

**Windows**

```powershell
> pulumi up
> curl.exe -s "$(pulumi stack output url)date"
```

**TypeScript**

The time now comes back like `Wed, 21 Oct 2026 14:05:09 GMT`.

**Python / Go / C# / YAML / HCL**

The time now comes back like `Wed Oct 21 14:05:09 2026`.

To see what else you can add, browse the [AWS provider](https://www.pulumi.com/registry/packages/aws/) in the Pulumi Registry.

## Cleaning up

You can cleanly destroy the stack and all of its infrastructure with [`pulumi destroy`](https://www.pulumi.com/docs/iac/cli/commands/pulumi_destroy):

```bash
$ pulumi destroy
```

## Learn more

- Browse other architecture templates in the [Templates gallery](https://www.pulumi.com/templates).
- Explore the [AWS provider API docs](https://www.pulumi.com/registry/packages/aws) in the Pulumi Registry.
- Walk through Pulumi from the ground up in [Pulumi Tutorials](https://www.pulumi.com/dev/browse/?type=tutorial).
- Read the latest [serverless posts on the Pulumi blog](https://www.pulumi.com/blog/tag/serverless).
