|
| 1 | +# Create a REST API with Lambda proxy integration using the AWS CLI |
| 2 | + |
| 3 | +This tutorial guides you through creating a REST API with Lambda proxy integration using the AWS Command Line Interface (AWS CLI). You'll learn how to create a Lambda function, set up an API Gateway REST API, configure Lambda proxy integration, and test your API endpoints. |
| 4 | + |
| 5 | +## Prerequisites |
| 6 | + |
| 7 | +Before you begin this tutorial, make sure you have the following: |
| 8 | + |
| 9 | +1. The AWS CLI installed and configured with appropriate credentials |
| 10 | +2. Basic familiarity with command line interfaces and REST API concepts |
| 11 | +3. Sufficient permissions to create and manage Lambda functions, API Gateway resources, and IAM roles |
| 12 | +4. `jq` command-line JSON processor installed (for parsing AWS CLI responses) |
| 13 | + - **Alternative**: If `jq` is not available, you can manually extract IDs from the AWS CLI output |
| 14 | + |
| 15 | +**Note**: If you don't have `jq` installed, you can install it using: |
| 16 | +- **macOS**: `brew install jq` |
| 17 | +- **Ubuntu/Debian**: `sudo apt-get install jq` |
| 18 | +- **CentOS/RHEL**: `sudo yum install jq` |
| 19 | + |
| 20 | +## Create an IAM role for Lambda execution |
| 21 | + |
| 22 | +Lambda functions require an execution role that grants them permission to access AWS services and write logs to CloudWatch. |
| 23 | + |
| 24 | +**Create a trust policy document** |
| 25 | + |
| 26 | +```bash |
| 27 | +cat > trust-policy.json << 'EOF' |
| 28 | +{ |
| 29 | + "Version": "2012-10-17", |
| 30 | + "Statement": [ |
| 31 | + { |
| 32 | + "Effect": "Allow", |
| 33 | + "Principal": { |
| 34 | + "Service": "lambda.amazonaws.com" |
| 35 | + }, |
| 36 | + "Action": "sts:AssumeRole" |
| 37 | + } |
| 38 | + ] |
| 39 | +} |
| 40 | +EOF |
| 41 | +``` |
| 42 | + |
| 43 | +**Create the IAM role** |
| 44 | + |
| 45 | +```bash |
| 46 | +aws iam create-role \ |
| 47 | + --role-name GetStartedLambdaBasicExecutionRole \ |
| 48 | + --assume-role-policy-document file://trust-policy.json |
| 49 | +``` |
| 50 | + |
| 51 | +**Attach the basic execution policy** |
| 52 | + |
| 53 | +```bash |
| 54 | +aws iam attach-role-policy \ |
| 55 | + --role-name GetStartedLambdaBasicExecutionRole \ |
| 56 | + --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole |
| 57 | +``` |
| 58 | + |
| 59 | +## Create and deploy a Lambda function |
| 60 | + |
| 61 | +Create a Lambda function that responds to API Gateway requests with a personalized greeting. |
| 62 | + |
| 63 | +**Create the Lambda function code** |
| 64 | + |
| 65 | +```bash |
| 66 | +cat > lambda_function.py << 'EOF' |
| 67 | +import json |
| 68 | +
|
| 69 | +def lambda_handler(event, context): |
| 70 | + print(event) |
| 71 | + |
| 72 | + greeter = 'World' |
| 73 | + |
| 74 | + try: |
| 75 | + if (event['queryStringParameters']) and (event['queryStringParameters']['greeter']) and ( |
| 76 | + event['queryStringParameters']['greeter'] is not None): |
| 77 | + greeter = event['queryStringParameters']['greeter'] |
| 78 | + except KeyError: |
| 79 | + print('No greeter') |
| 80 | + |
| 81 | + try: |
| 82 | + if (event['multiValueHeaders']) and (event['multiValueHeaders']['greeter']) and ( |
| 83 | + event['multiValueHeaders']['greeter'] is not None): |
| 84 | + greeter = " and ".join(event['multiValueHeaders']['greeter']) |
| 85 | + except KeyError: |
| 86 | + print('No greeter') |
| 87 | + |
| 88 | + try: |
| 89 | + if (event['headers']) and (event['headers']['greeter']) and ( |
| 90 | + event['headers']['greeter'] is not None): |
| 91 | + greeter = event['headers']['greeter'] |
| 92 | + except KeyError: |
| 93 | + print('No greeter') |
| 94 | + |
| 95 | + if (event['body']) and (event['body'] is not None): |
| 96 | + body = json.loads(event['body']) |
| 97 | + try: |
| 98 | + if (body['greeter']) and (body['greeter'] is not None): |
| 99 | + greeter = body['greeter'] |
| 100 | + except KeyError: |
| 101 | + print('No greeter') |
| 102 | + |
| 103 | + res = { |
| 104 | + "statusCode": 200, |
| 105 | + "headers": { |
| 106 | + "Content-Type": "*/*" |
| 107 | + }, |
| 108 | + "body": "Hello, " + greeter + "!" |
| 109 | + } |
| 110 | + |
| 111 | + return res |
| 112 | +EOF |
| 113 | +``` |
| 114 | + |
| 115 | +**Create a deployment package** |
| 116 | + |
| 117 | +```bash |
| 118 | +zip function.zip lambda_function.py |
| 119 | +``` |
| 120 | + |
| 121 | +**Create the Lambda function** |
| 122 | + |
| 123 | +```bash |
| 124 | +aws lambda create-function \ |
| 125 | + --function-name GetStartedLambdaProxyIntegration \ |
| 126 | + --runtime python3.12 \ |
| 127 | + --role arn:aws:iam::$(aws sts get-caller-identity --query Account --output text):role/GetStartedLambdaBasicExecutionRole \ |
| 128 | + --handler lambda_function.lambda_handler \ |
| 129 | + --zip-file fileb://function.zip |
| 130 | +``` |
| 131 | + |
| 132 | +## Create a REST API |
| 133 | + |
| 134 | +Create a REST API in API Gateway and set up the necessary resources and methods. |
| 135 | + |
| 136 | +**Create the REST API** |
| 137 | + |
| 138 | +```bash |
| 139 | +# Create API and capture response |
| 140 | +API_RESPONSE=$(aws apigateway create-rest-api \ |
| 141 | + --name LambdaProxyAPI \ |
| 142 | + --endpoint-configuration types=REGIONAL) |
| 143 | + |
| 144 | +# Extract API ID and root resource ID from response |
| 145 | +API_ID=$(echo $API_RESPONSE | jq -r '.id') |
| 146 | +ROOT_RESOURCE_ID=$(echo $API_RESPONSE | jq -r '.rootResourceId') |
| 147 | + |
| 148 | +echo "API ID: $API_ID" |
| 149 | +echo "Root Resource ID: $ROOT_RESOURCE_ID" |
| 150 | +``` |
| 151 | + |
| 152 | +**Create a resource** |
| 153 | + |
| 154 | +```bash |
| 155 | +# Create resource and capture response |
| 156 | +RESOURCE_RESPONSE=$(aws apigateway create-resource \ |
| 157 | + --rest-api-id $API_ID \ |
| 158 | + --parent-id $ROOT_RESOURCE_ID \ |
| 159 | + --path-part helloworld) |
| 160 | + |
| 161 | +# Extract resource ID from response |
| 162 | +RESOURCE_ID=$(echo $RESOURCE_RESPONSE | jq -r '.id') |
| 163 | + |
| 164 | +echo "Resource ID: $RESOURCE_ID" |
| 165 | +``` |
| 166 | + |
| 167 | +## Configure Lambda proxy integration |
| 168 | + |
| 169 | +Create an ANY method on your resource and configure it to use Lambda proxy integration. |
| 170 | + |
| 171 | +**Create an ANY method** |
| 172 | + |
| 173 | +```bash |
| 174 | +aws apigateway put-method \ |
| 175 | + --rest-api-id $API_ID \ |
| 176 | + --resource-id $RESOURCE_ID \ |
| 177 | + --http-method ANY \ |
| 178 | + --authorization-type NONE |
| 179 | +``` |
| 180 | + |
| 181 | +**Set up Lambda proxy integration** |
| 182 | + |
| 183 | +```bash |
| 184 | +# Get account ID and region |
| 185 | +ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) |
| 186 | +REGION=$(aws configure get region) |
| 187 | + |
| 188 | +# If region is not set in config, use default |
| 189 | +if [ -z "$REGION" ]; then |
| 190 | + REGION="us-east-1" |
| 191 | +fi |
| 192 | + |
| 193 | +echo "Account ID: $ACCOUNT_ID" |
| 194 | +echo "Region: $REGION" |
| 195 | + |
| 196 | +aws apigateway put-integration \ |
| 197 | + --rest-api-id $API_ID \ |
| 198 | + --resource-id $RESOURCE_ID \ |
| 199 | + --http-method ANY \ |
| 200 | + --type AWS_PROXY \ |
| 201 | + --integration-http-method POST \ |
| 202 | + --uri "arn:aws:apigateway:${REGION}:lambda:path/2015-03-31/functions/arn:aws:lambda:${REGION}:${ACCOUNT_ID}:function:GetStartedLambdaProxyIntegration/invocations" |
| 203 | +``` |
| 204 | + |
| 205 | +**Grant API Gateway permission to invoke Lambda** |
| 206 | + |
| 207 | +```bash |
| 208 | +aws lambda add-permission \ |
| 209 | + --function-name GetStartedLambdaProxyIntegration \ |
| 210 | + --statement-id apigateway-invoke \ |
| 211 | + --action lambda:InvokeFunction \ |
| 212 | + --principal apigateway.amazonaws.com \ |
| 213 | + --source-arn "arn:aws:execute-api:$REGION:$ACCOUNT_ID:$API_ID/*/*" |
| 214 | +``` |
| 215 | + |
| 216 | +## Deploy and test the API |
| 217 | + |
| 218 | +Deploy your API to make it accessible and test it using different methods. |
| 219 | + |
| 220 | +**Deploy the API** |
| 221 | + |
| 222 | +```bash |
| 223 | +aws apigateway create-deployment \ |
| 224 | + --rest-api-id $API_ID \ |
| 225 | + --stage-name test |
| 226 | +``` |
| 227 | + |
| 228 | +**Test the API** |
| 229 | + |
| 230 | +Get the invoke URL and test with different methods: |
| 231 | + |
| 232 | +```bash |
| 233 | +# Construct the invoke URL |
| 234 | +INVOKE_URL="https://$API_ID.execute-api.$REGION.amazonaws.com/test/helloworld" |
| 235 | +echo "Invoke URL: $INVOKE_URL" |
| 236 | + |
| 237 | +# Test with query parameter |
| 238 | +echo "Testing with query parameter..." |
| 239 | +curl -X GET "$INVOKE_URL?greeter=John" |
| 240 | + |
| 241 | +# Test with header |
| 242 | +echo "Testing with header..." |
| 243 | +curl -X GET "$INVOKE_URL" \ |
| 244 | + -H 'content-type: application/json' \ |
| 245 | + -H 'greeter: John' |
| 246 | + |
| 247 | +# Test with body |
| 248 | +echo "Testing with body..." |
| 249 | +curl -X POST "$INVOKE_URL" \ |
| 250 | + -H 'content-type: application/json' \ |
| 251 | + -d '{ "greeter": "John" }' |
| 252 | +``` |
| 253 | + |
| 254 | +All tests should return: `Hello, John!` |
| 255 | + |
| 256 | +## Clean up resources |
| 257 | + |
| 258 | +To avoid ongoing charges, delete the resources you created: |
| 259 | + |
| 260 | +```bash |
| 261 | +# Delete API |
| 262 | +aws apigateway delete-rest-api --rest-api-id $API_ID |
| 263 | + |
| 264 | +# Delete Lambda function |
| 265 | +aws lambda delete-function --function-name GetStartedLambdaProxyIntegration |
| 266 | + |
| 267 | +# Delete IAM role |
| 268 | +aws iam detach-role-policy \ |
| 269 | + --role-name GetStartedLambdaBasicExecutionRole \ |
| 270 | + --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole |
| 271 | + |
| 272 | +aws iam delete-role --role-name GetStartedLambdaBasicExecutionRole |
| 273 | + |
| 274 | +# Clean up local files |
| 275 | +rm lambda_function.py function.zip trust-policy.json |
| 276 | +``` |
| 277 | + |
| 278 | +## Next steps |
| 279 | + |
| 280 | +Now that you've successfully created a REST API with Lambda proxy integration, you can explore additional features: |
| 281 | + |
| 282 | +- Add authentication and authorization to your APIs |
| 283 | +- Implement request validation and transformation |
| 284 | +- Monitor your APIs with CloudWatch |
| 285 | +- Use Lambda layers to share code between functions |
0 commit comments