Deploy Your First Serverless API

Use AWS SAM CLI to build and deploy a serverless API with Lambda.

Introduction

30 Second Summary

Every time you check the weather, order food, or scroll social media, your phone is calling APIs that run without anyone managing a server behind the scenes.

In this project, you will deploy your own serverless API to AWS using the SAM CLI. You will build, deploy, update, and tear down a live API endpoint that anyone on the internet can call.

What You'll Build

A serverless Hello World API powered by AWS Lambda and Amazon API Gateway that returns a JSON greeting when you visit its public URL in a browser.

By the end of this project, you'll have:

  • A Lambda function that handles HTTP requests and returns a JSON greeting.
  • An API Gateway endpoint that exposes your Lambda function as a public REST API.
  • Hands-on experience with the full SAM CLI lifecycle: sam init, sam build, sam deploy, sam sync, and sam delete.
  • A Secret Mission where you add a second Lambda function and API route to your application.

Are there any prerequisites?

You need an AWS account with configured credentials, plus the AWS CLI, AWS SAM CLI, Python, and Git installed on your machine. This project costs $0. AWS Lambda includes 1M free requests per month permanently, and API Gateway includes 1M free calls per month for the first 12 months.

Before We Start

Before We Start...

Initialize Your Hello World Application

Before you can deploy anything to AWS, you need a serverless application on your local machine.

The SAM CLI comes with a scaffolding command called sam init that generates a complete project from a template.

In this step, you'll use it to create a Hello World serverless app, then explore the files it generates so you understand what you're about to deploy.

In This Step, Get Ready To:
  • Scaffold a Hello World serverless application using sam init.
  • Explore the project files that define your Lambda function and API Gateway endpoint.
  • Read the Lambda function code that returns a JSON greeting.
Run Sam Init to Create Your Project

The sam init command walks you through an interactive setup to generate a ready-to-deploy serverless project.

  • Open your terminal (Command Prompt or PowerShell on Windows).
  • Run the following command:
sam init

The CLI presents a series of prompts. Follow these selections:

  • Choose 1 - AWS Quick Start Templates as the template source.
  • Choose 1 - Hello World Example as the application template.
  • When asked "Use the most popular runtime and package type? (Python and zip)", enter y.
  • For X-Ray tracing, press ENTER to accept the default (no).
  • For CloudWatch Application Insights, press ENTER to accept the default (no).
  • For Structured Logging in JSON format, press ENTER to accept the default (no).
  • For the project name, press ENTER to accept the default (sam-app).

What should I see?

After the final prompt, the CLI generates a new folder called sam-app in your current directory.

You should see output confirming the project was created successfully.

Seeing an Error?

If you see a "command not found" error, your SAM CLI installation may not be on your system PATH. Help me troubleshoot my sam init error.

Navigate Into the Project and Explore the File Structure

The generated project contains everything you need to deploy a serverless API. Let's look at what sam init created for you.

  • Change into the project directory:
cd sam-app
  • List the contents of the directory to see the project files:
tree

Here are the key files to know about:

  • hello_world/app.py contains the Lambda function code that runs when your API receives a request.
  • template.yaml is the SAM template that defines your infrastructure as code. It declares your Lambda function, API Gateway endpoint, and IAM role.
  • samconfig.toml stores default deployment parameters so you don't have to re-enter them every time.
  • hello_world/requirements.txt lists the Python dependencies for your Lambda function.

What is Infrastructure as Code?

Infrastructure as Code (IaC) means defining your cloud resources in a file instead of clicking through the AWS console.

Your template.yaml file tells AWS exactly what to create. You can version it, share it, and recreate your entire setup with a single command.

Read the Lambda Function Code

The Lambda function is the code that actually runs when someone sends a request to your API. Let's see what it does.

  • Open hello_world/app.py in your text editor.

You'll see a function called lambda_handler that takes two parameters: event and context. It returns a JSON response with a statusCode of 200 and a body containing {"message": "hello world"}.

def lambda_handler(event, context):
    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello world",
        }),
    }

What Are Event and Context?

Every Lambda function receives these two parameters. The event object contains data about the incoming request, like HTTP headers and query parameters.

The context object provides information about the runtime environment, like how much time is left before the function times out. For this Hello World app, you don't need to use either one.

This is all the code your API needs. When someone sends a GET request to your API endpoint, AWS invokes this function and returns the JSON response to the caller.

Your application is scaffolded and ready to go. Next up, you'll build and package it for deployment to AWS.

Build Your Application

You have a serverless application scaffolded on your machine. Before you can deploy it to AWS, the SAM CLI needs to compile your code and resolve its dependencies into a deployment-ready package. This is what sam build does.

In This Step, Get Ready To:
  • Build your serverless application with sam build.
  • Explore the build output to understand what gets uploaded to AWS.
Run Sam Build

The sam build command reads your template.yaml, resolves dependencies from requirements.txt, copies your function code, and places everything into a .aws-sam/build directory. This directory is what gets uploaded to AWS during deployment.

  • Make sure you are in the sam-app directory.
  • Run the following command:
sam build

You should see "Build Succeeded" in the output.

What does this command do?

sam build packages your Lambda function code along with its Python dependencies into a self-contained folder. Think of it like packing a suitcase with everything your function needs to run in the cloud.

Build failed?

Make sure you are running the command from inside the sam-app directory, not its parent folder. The SAM CLI needs to find template.yaml in the current directory. Help me debug my sam build error.

Explore the Build Output

Now that the build succeeded, take a look at what it produced.

  • Open the .aws-sam/build directory in your file explorer or text editor.

Inside, you will find a HelloWorldFunction folder containing your compiled function code and all its dependencies. There is also a processed template.yaml file. This entire directory is what the SAM CLI uploads to AWS when you deploy.

Why does SAM need a separate build step?

Your Lambda function might depend on external Python packages listed in requirements.txt. AWS Lambda does not install packages for you. The build step bundles your code and its dependencies together so everything your function needs is in one package, ready to run in the cloud.

Your application is packaged and ready to go. Next up, you will deploy it to AWS and get a live API endpoint you can hit from anywhere.

Deploy Your Application to AWS

Your application is built and packaged locally. Now it is time to push it to the AWS Cloud so it becomes a live API anyone can access. The SAM CLI handles the entire deployment process for you. It uploads your code, creates your cloud resources, and hands you a public URL.

In This Step, Get Ready To:
  • Deploy your serverless application to AWS using the guided deployment flow.
  • Find your live API endpoint URL in the deployment output.
  • Test your API by sending it a request and seeing a JSON response.
Run the Guided Deployment

The sam deploy --guided command walks you through an interactive setup the first time you deploy. It asks you to confirm settings like the stack name, region, and permissions. These choices get saved so future deployments can skip the prompts.

  • Run the following command from your sam-app directory.
sam deploy --guided

Follow the interactive prompts with these responses:

  • Stack Name: Press ENTER to accept the default sam-app.
  • AWS Region: Press ENTER to accept your default region, or type a region like us-east-1.
  • Confirm changes before deploy: Enter n.
  • Allow SAM CLI IAM role creation: Press ENTER to accept Yes.
  • Disable rollback: Press ENTER to accept No.
  • HelloWorldFunction may not have authorization defined, Is this okay?: Enter y. This is expected for a public Hello World API.
  • Save arguments to configuration file: Press ENTER to accept Yes.
  • SAM configuration file: Press ENTER to accept samconfig.toml.
  • SAM configuration environment: Press ENTER to accept default.

What is a CloudFormation stack?

When you deploy, the SAM CLI transforms your SAM template into a CloudFormation template. CloudFormation is the AWS service that actually creates and manages your cloud resources. It groups everything into a "stack" so all your resources (Lambda function, API Gateway, IAM role) are tracked and managed together.

Watch the Deployment and Find Your API URL

The SAM CLI uploads your code to an S3 bucket, transforms your SAM template into CloudFormation, and provisions your resources. Watch the progress in your terminal as each resource is created.

When deployment completes, look for the Outputs section at the bottom of your terminal output.

  • Find the HelloWorldApi key in the Outputs section.
  • Copy its value. This is your live API endpoint URL.

What should I see?

Your API URL looks something like https://<id>.execute-api.<region>.amazonaws.com/Prod/hello/. The <id> and <region> parts are unique to your deployment.

Test Your Live API

Your Lambda function is now live and connected to a public API Gateway endpoint. Time to send it a request and see the response.

  • Open a new terminal window.
  • Run the following command, replacing the URL with your own API endpoint.
curl [[APIURL="your API endpoint URL from the Outputs section"]]

What does this command do?

The curl command sends an HTTP GET request to your API URL. You can also paste the URL directly into your browser to see the same result.

You should see the JSON response: {"message": "hello world"}. Your serverless API is live on the internet.

Getting an error or empty response?

Make sure you copied the full URL from the Outputs section, including the /Prod/hello/ path at the end. If you see a "Missing Authentication Token" message, you may have hit the base URL without the /hello/ path. Help me troubleshoot my API response.

Your serverless API is deployed and responding to requests. Next up, you will modify your Lambda function and use the SAM CLI to sync your changes to the cloud in real time.

Modify and Sync Your Changes

Your API is live, but real development means constant iteration. Every time you tweak your code, you need those changes reflected in the cloud. The SAM CLI has a purpose-built command for this: sam sync --watch. It watches your local files and pushes changes to AWS in real time, without running a full CloudFormation deployment.

In This Step, Get Ready To:
  • Start the SAM CLI sync watcher to monitor your project for changes.
  • Edit your Lambda function code and watch it sync automatically.
  • Verify your updated API returns the new response.
Start Sam Sync in Watch Mode

Instead of running sam deploy every time you change a line of code, sam sync uses Lambda and API Gateway APIs directly to update your code. This makes it much faster for development.

  • Make sure you are in the sam-app directory.
  • Run the following command:
sam sync --watch
  • When prompted to confirm you are synchronizing a development stack, enter y.

The SAM CLI performs an initial sync of your application and then begins watching for file changes.

Why sam sync instead of sam deploy?

Running sam deploy triggers a full CloudFormation stack update every time, which can take a minute or more. sam sync bypasses CloudFormation for code-only changes and updates your Lambda function directly. This is the workflow real serverless developers use during active development.

Modify Your Lambda Function

With the sync watcher running, any change you save to your project files gets picked up and pushed to AWS automatically. Let's change the greeting message your API returns.

  • Open hello_world/app.py in your text editor.
  • Find the line that says "hello world" inside the message value.
  • Change it to "hello everyone!" or any message you like.
  • Save the file.

Your updated function should look something like this:

import json

def lambda_handler(event, context):
    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello everyone!",
        }),
    }

Switch back to your terminal. The SAM CLI detects the change and automatically syncs it to AWS.

What should I see?

Watch your terminal for a message that says "Finished syncing Lambda Function HelloWorldFunction". This confirms your updated code is now live in the cloud.

Verify the Update

Your code is synced. Time to confirm the change is reflected in your live API.

  • Open a new terminal window or browser tab.
  • Send a GET request to the same API URL you used in the previous step.
curl [[APIURL="your API Gateway URL from the deploy step"]]

What does this command do?

This sends an HTTP GET request to your API Gateway endpoint, which triggers your Lambda function. The response should now contain your updated message instead of the original "hello world".

You should see your updated message in the JSON response. You just changed code on your local machine and saw it go live in the cloud within seconds.

  • Press Ctrl+C in the terminal running sam sync --watch to stop the sync watcher.

Still seeing the old message?

Make sure you saved the file after editing it. Also check that the sync watcher terminal shows the "Finished syncing" message before you test. If your browser is caching the old response, try using curl from the terminal instead.

If you are still stuck, help me debug my sam sync issue.

You have now experienced the full development loop: edit locally, sync to the cloud, and verify instantly. Next up, you will clean up all the AWS resources this project created.

Clean Up Your AWS Resources

In the previous step, you proved that your development workflow works end-to-end by modifying your Lambda function and watching SAM CLI sync the changes live. Your serverless API is fully deployed and tested. Now it is time to tear everything down so your AWS account stays clean and free of any lingering resources.

In This Step, Get Ready To:
  • Delete your entire CloudFormation stack and all associated AWS resources with a single command.
  • Verify that your Lambda function, API Gateway endpoint, and IAM role are completely removed.
Run Sam Delete

The sam delete command removes everything that sam deploy created. It deletes the CloudFormation stack (which tears down your Lambda function, API Gateway, and IAM role) and cleans up the S3 bucket that stored your deployment artifacts.

  • Make sure you are in the sam-app directory.
  • Run the following command:
sam delete
  • When prompted "Are you sure you want to delete the stack sam-app in the region <your-region>?", enter y.
  • When prompted "Are you sure you want to delete the folder sam-app in S3 which contains the artifacts?", enter y.

What does this command do?

The sam delete command does two things. First, it deletes the S3 artifacts (the packaged code that was uploaded during deployment). Then it deletes the CloudFormation stack, which automatically removes every resource the stack created: your Lambda function, API Gateway endpoint, and IAM role.

Verify Deletion

Watch your terminal as the SAM CLI processes the deletion. You should see a "Deleted successfully" message in the output.

I see "Deleted successfully"

Your Lambda function, API Gateway endpoint, IAM role, and S3 deployment artifacts are all gone. No resources remain in your AWS account from this project.

I see an error

If the deletion fails, it is usually because the stack is in a stuck state or a resource could not be removed.

  • Try running sam delete again.
  • If the error persists, open the AWS CloudFormation console, find the sam-app stack, and delete it manually.

Still having trouble?

Help me troubleshoot my sam delete error.

To double-check, you can try visiting your old API URL in the browser. You should get an error or a "Missing Authentication Token" message, confirming the endpoint no longer exists.

What is a CloudFormation Stack?

When you ran sam deploy, the SAM CLI transformed your template.yaml into a CloudFormation template and created a stack. A stack is a collection of AWS resources managed as a single unit. Deleting the stack removes all of those resources at once, so you do not have to hunt them down individually.

Secret mission

Add a Second API Route

Your API only has one trick right now. What if you wanted to add a second endpoint that returns a different message? Real serverless applications are built from multiple small functions, each handling a specific route. Time to level up your SAM template.

Before you go

Clean Up Your Resources

Decide whether to keep your resources running, pause them to come back later, or delete them entirely. AWS Lambda includes 1M free requests per month permanently, and API Gateway includes 1M free calls per month for the first 12 months. This project uses only a handful of requests, so costs are effectively $0.

Resources you used:

  • An AWS Lambda function (HelloWorldFunction).
  • An Amazon API Gateway REST API.
  • An IAM role for the Lambda function.
  • An S3 bucket for deployment artifacts (created by SAM CLI).
  • A CloudFormation stack named sam-app.
  • A local sam-app project folder on your machine.

Keep everything running

No action needed. Choose this if you are still actively building or want to experiment more with your deployed API.

  • Your Lambda function and API Gateway endpoint will remain live.
  • The free tier covers this project's usage easily. However, the S3 bucket used for deployment artifacts may accumulate small storage charges over time.
  • You can always clean up later by running sam delete from the sam-app directory.

Pause - I'll come back to this later

Serverless resources like Lambda and API Gateway do not run continuously. They only incur costs when invoked. There is no "pause" button needed for serverless applications because they are already idle when not in use.

  • Your resources will stay deployed but will not cost anything unless someone sends requests to your API endpoint.
  • Keep your local sam-app folder so you can redeploy or delete later.
  • When you are ready to clean up, run sam delete from the sam-app directory.

Delete - I don't want to use this again

Remove all project resources from AWS and your local machine. This is the recommended option to keep your AWS account clean.

  • If you already ran sam delete in Step 5, your AWS resources are already gone. Skip to the last item in this list.
  • If you completed the Secret Mission and redeployed, run sam delete from the sam-app directory now. Confirm both prompts with y to delete the CloudFormation stack and S3 artifacts.
  • Delete the local sam-app folder from your machine if you no longer need it.

Mission accomplished

That's a Wrap!

Nice work! You just deployed your first serverless API to AWS using the SAM CLI. You went from zero to a live API endpoint on the internet, modified it in real time, and cleaned it all up without ever touching the AWS Console.

Here's what you learned:

  • Scaffolded, built, and deployed a serverless application using sam init, sam build, and sam deploy --guided to create a Lambda function, API Gateway endpoint, and IAM role from a single SAM template.
  • Modified your Lambda function and pushed changes to the cloud in real time using sam sync --watch, skipping a full CloudFormation redeployment.
  • Tore down every AWS resource with a single sam delete command, leaving your account clean.
  • Added a second Lambda function and API route to your SAM template, learning how real serverless applications are structured with multiple functions handling different endpoints.

Ready to quiz yourself?