Run locally

There are 2 ways of running a Serverless app locally:

  • By invoking an individual Lambda function
  • By running a local HTTP server that simulates API Gateway. See more here

In the terminal, run the following command from the root directory of the sam-app folder:

cd ~/environment/sam-app
sam local start-api --port 8080

In a Cloud9 workspace, you must use port 8080, 8081 or 8082 to be able to open the URL in the local browser for preview.

Test your endpoint

Once your local server is running, we can send HTTP requests to test it.

Using cURL

Without killing the running process, open a new terminal.
New terminal Test your endpoint by running a cURL command that triggers an HTTP GET request by open new terminal.

curl http://localhost:8080/hello

The response message will be displayed on terminal. Response

Note how SAM is pulling the Docker container image lambci/lambda:python3.7 automatically. This is how SAM is able to simulate the Lambda runtime locally and run your function within it. The first invocation might take a few seconds due to the docker pull command, but subsequent invocations should be much faster. Docker

Make the code change

While the app is still running, open the file sam-app/hello_world/ and make a simple code change.
Install one more packages.

cd ~/environment/sam-app/hello_world
pip3 install urllib3
pip3 freeze > requirements.txt

For example, change the response message to return your ip location instead of hello world. Your Lambda handler should look like this after the change:

import json

import urllib3

def lambda_handler(event, context):
    """Sample pure Lambda function

    event: dict, required
        API Gateway Lambda Proxy Input Format

        Event doc:

    context: object, required
        Lambda Context runtime methods and attributes

        Context doc:

    API Gateway Lambda Proxy Output Format: dict

        Return doc:

        http = urllib3.PoolManager()
        ip = http.request("GET","")
        location ="ascii").strip()
    except Exception as e:
        # Send some context about this error to Lambda Logs

        raise e

    return {
        "statusCode": 200,
        "body": json.dumps({
            "location": location

Note: Make sure you save the file after changing it. You don’t have to restart the sam local process, just refresh the terminal or re-trigger the cURL command to see the changes reflected in your endpoint. An the new response is your current ip location. Location

You only need to restart sam local if you change the template.yaml.