# Create a Python Lambda Function in AWS in 5 minutes



Create a new Python file called app.py

Include a handler function that will be what our Lambda function returns 

```python

def handler(event, context):
    return "Greetings %s from %s!" % (event["name"], event["city"])

```

In this case our function will take a two values in the payload and return them. 

Create the permissions for your function. This will require the AWS cli to be configured. 
If you install the aws cli and type *aws configure* and answer the questions, you'll be good. You can install the AWS CLI using *pip install awscli*. 

Create the IAM role with policy attached that will allow function execution
```bash
aws iam create-role --role-name lambda-ex --assume-role-policy-document '{"Version": "2012-10-17","Statement": [{ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}'
```

Now, zip up your app.py

```bash
zip -r app.zip app.py
```

Now, create the function, replacing <AccountID> with your AWS Account ID. You can find it on the IAM role page. 
You can quickly retrieve your account ID by running 
```bash
aws sts get-caller-identity
```

```bash
aws lambda create-function --function-name pyHello --runtime python3.7 --zip-file fileb://app.zip --handler app.handler --role arn:aws:iam::<AccountID>:role/lambda-ex

```

Now invoke the function, passing in your Payload
```bash
aws lambda invoke --function-name pyHello --payload '{"name":"AJ", "city":"Cincy"}' output
```

Cat the *output* file to validate the success 

This is good, but if we're going to use this as an API, the return has to be JSON serializable. 
Let's modify our code a bit to return this message properly:

```python 
import json
def handler(event, context):
    msg = "Greetings %s from %s!" % (event["name"], event["city"])
    return { 
        'statusCode': 200,
        'body': json.dumps(msg),
        'headers': {
            'Content-Type': 'application/json'
        }
    }
```

To update the function, save the changes and recreate the zip file and run:
```bash
aws lambda update-function-code --function-name pyHello --zip-file fileb://app.zip
```

If I'm working frequently on a function, I put it all in one: 

```bash
rm -rf app.zip ; zip app.zip app.py ; aws lambda update-function-code --function-name pyHello --zip-file fileb://app.zip
```

Rerun the test to confirm json output. 
cat output
{"statusCode": 200, "body": "\"Greetings AJ from Cincy. !\"", "headers": {"Content-Type": "application/json"}}


Delete the function with the following command:
```bash
aws lambda delete-function --function-name pyHello 
```


[Thanks to this video for the guidance](https://www.youtube.com/watch?v=6Qj0XLsQe-0)

I hope you find this helpful. 

AJ
