Tutorial: Build a Hello World REST API with Lambda proxy integration
Lambda proxy integration is a lightweight, flexible API Gateway API integration type that allows you to integrate an API method – or an entire API – with a Lambda function. The Lambda function can be written in any language that Lambda supports. Because it's a proxy integration, you can change the Lambda function implementation at any time without needing to redeploy your API.
In this tutorial, you do the following:
-
Create a "Hello, World!" Lambda function to be the backend for the API.
-
Create and test a "Hello, World!" API with Lambda proxy integration.
Create a "Hello, World!" Lambda function
- Old REST API console
-
Note
We've redesigned the API Gateway console. The old console experience will no longer be available starting December 2023.
This function returns a greeting to the caller as a JSON object in the following format:
{ "greeting": "Good{time},{name}of{city}.[ Happy{day}!]" }Create a "Hello, World!" Lambda function in the Lambda console
Sign in to the Lambda console at https://console.aws.amazon.com/lambda
. -
On the AWS navigation bar, choose a region (for example, US East (N. Virginia)).
Note
Note the region where you create the Lambda function. You'll need it when you create the API.
-
Choose Functions in the navigation pane.
-
Choose Create function.
-
Choose Author from scratch.
-
Under Basic information, do the following:
-
In Function name, enter
GetStartedLambdaProxyIntegration. -
Under Permissions, expand Choose or create an execution role. From the Execution role dropdown list, choose Create new role from AWS policy templates.
-
In Role name, enter
GetStartedLambdaBasicExecutionRole. -
Leave the Policy templates field blank.
-
Choose Create function.
-
-
Under Function code, in the inline code editor, copy/paste the following code:
'use strict'; console.log('Loading hello world function'); export const handler = async (event) => { let name = "you"; let city = 'World'; let time = 'day'; let day = ''; let responseCode = 200; console.log("request: " + JSON.stringify(event)); if (event.queryStringParameters && event.queryStringParameters.name) { console.log("Received name: " + event.queryStringParameters.name); name = event.queryStringParameters.name; } if (event.queryStringParameters && event.queryStringParameters.city) { console.log("Received city: " + event.queryStringParameters.city); city = event.queryStringParameters.city; } if (event.headers && event.headers['day']) { console.log("Received day: " + event.headers.day); day = event.headers.day; } if (event.body) { let body = JSON.parse(event.body) if (body.time) time = body.time; } let greeting = `Good ${time}, ${name} of ${city}.`; if (day) greeting += ` Happy ${day}!`; let responseBody = { message: greeting, input: event }; // The output from a Lambda proxy integration must be // in the following JSON object. The 'headers' property // is for custom response headers in addition to standard // ones. The 'body' property must be a JSON string. For // base64-encoded payload, you must also set the 'isBase64Encoded' // property to 'true'. let response = { statusCode: responseCode, headers: { "x-custom-header" : "my custom header value" }, body: JSON.stringify(responseBody) }; console.log("response: " + JSON.stringify(response)) return response; }; -
Choose Deploy.
- New REST API console
-
To create a "Hello, World!" Lambda function in the Lambda console
Sign in to the Lambda console at https://console.aws.amazon.com/lambda
. -
On the AWS navigation bar, choose a region (for example, US East (N. Virginia)).
Note
Note the region where you create the Lambda function. You'll need it when you create the API.
-
Choose Functions in the navigation pane.
-
Choose Create function.
-
Choose Author from scratch.
-
Under Basic information, do the following:
-
In Function name, enter
GetStartedLambdaProxyIntegration. -
Under Permissions, expand Choose or create an execution role. From the Execution role dropdown list, choose Create new role from AWS policy templates.
-
In Role name, enter
GetStartedLambdaBasicExecutionRole. -
Leave the Policy templates field blank.
-
Choose Create function.
-
-
Under Function code, in the inline code editor, copy/paste the following code:
export const handler = function(event, context, callback) { console.log('Received event:', JSON.stringify(event, null, 2)); var res ={ "statusCode": 200, "headers": { "Content-Type": "*/*" } }; var greeter = 'World'; if (event.greeter && event.greeter!=="") { greeter = event.greeter; } else if (event.body && event.body !== "") { var body = JSON.parse(event.body); if (body.greeter && body.greeter !== "") { greeter = body.greeter; } } else if (event.queryStringParameters && event.queryStringParameters.greeter && event.queryStringParameters.greeter !== "") { greeter = event.queryStringParameters.greeter; } else if (event.multiValueHeaders && event.multiValueHeaders.greeter && event.multiValueHeaders.greeter != "") { greeter = event.multiValueHeaders.greeter.join(" and "); } else if (event.headers && event.headers.greeter && event.headers.greeter != "") { greeter = event.headers.greeter; } res.body = "Hello, " + greeter + "!"; callback(null, res); }; -
Choose Deploy.
Create a "Hello, World!" API
Now create an API for your "Hello, World!" Lambda function by using the API Gateway console.
- Old REST API console
-
Note
We've redesigned the API Gateway console. The old console experience will no longer be available starting December 2023.
Build a "Hello, World!" API
Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway
. -
If this is your first time using API Gateway, you see a page that introduces you to the features of the service. Under REST API, choose Build. When the Create Example API popup appears, choose OK.
If this is not your first time using API Gateway, choose Create API. Under REST API, choose Build.
-
Create an empty API as follows:
-
Under Create new API, choose New API.
-
Under Settings:
-
For API name, enter
LambdaSimpleProxy. -
If desired, enter a description in the Description field; otherwise, leave it empty.
-
Leave Endpoint Type set to Regional.
-
-
Choose Create API.
-
-
Create the
helloworldresource as follows:-
Choose the root resource (/) in the Resources tree.
-
Choose Create Resource from the Actions dropdown menu.
-
Leave Configure as proxy resource unchecked.
-
For Resource Name, enter
helloworld. -
Leave Resource Path set to /helloworld.
-
Leave Enable API Gateway CORS unchecked.
-
Choose Create Resource.
-
-
In a proxy integration, the entire request is sent to the backend Lambda function as-is, via a catch-all
ANYmethod that represents any HTTP method. The actual HTTP method is specified by the client at run time. TheANYmethod allows you to use a single API method setup for all of the supported HTTP methods:DELETE,GET,HEAD,OPTIONS,PATCH,POST, andPUT.To set up the
ANYmethod, do the following:-
In the Resources list, choose /helloworld.
-
In the Actions menu, choose Create method.
-
Choose ANY from the dropdown menu, and choose the checkmark icon
-
Leave the Integration type set to Lambda Function.
-
Choose Use Lambda Proxy integration.
-
From the Lambda Region dropdown menu, choose the region where you created the
GetStartedLambdaProxyIntegrationLambda function. -
In the Lambda Function field, type any character and choose
GetStartedLambdaProxyIntegrationfrom the dropdown menu. -
Leave Use Default Timeout checked.
-
Choose Save.
-
Choose OK when prompted with Add Permission to Lambda Function.
-
- New REST API console
-
To create a "Hello, World!" API
Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway
. -
If this is your first time using API Gateway, you see a page that introduces you to the features of the service. Under REST API, choose Build. When the Create Example API popup appears, choose OK.
If this is not your first time using API Gateway, choose Create API. Under REST API, choose Build.
For API name, enter
LambdaProxyAPI.(Optional) For Description, enter a description.
Keep API endpoint type set to Regional.
Choose Create API.
After you create an API, you create a resource. Typically, API resources are organized in a resource tree according to the application logic. For this example, you create a /helloworld resource.
To create a resource
Select the / resource, and then choose Create resource.
Keep Proxy resource turned off.
Keep Resource path as
/.For Resource name, enter
helloworld.Keep CORS (Cross Origin Resource Sharing) turned off.
Choose Create resource.
In a proxy integration, the entire request is sent to the backend Lambda function as-is, via a catch-all
ANYmethod that represents any HTTP method. The actual HTTP method is specified by the client at run time. TheANYmethod allows you to use a single API method setup for all of the supported HTTP methods:DELETE,GET,HEAD,OPTIONS,PATCH,POST, andPUT.To create an
ANYmethodSelect the /helloworld resource, and then choose Create method.
For Method type, select ANY.
For Integration type, select Lambda function.
Turn on Lambda proxy integration.
For Lambda function, select the AWS Region where you created your Lambda function, and then enter the function name.
-
To use the default timeout value of 29 seconds, keep Default timeout turned on. To set a custom timeout, choose Default timeout and enter a timeout value between
50and29000milliseconds. Choose Create method.
Deploy and test the API
- Old REST API console
-
Note
We've redesigned the API Gateway console. The old console experience will no longer be available starting December 2023.
Deploy the API in the API Gateway console
-
Choose Deploy API from the Actions dropdown menu.
-
For Deployment stage, choose [new stage].
-
For Stage name, enter
test. -
If desired, enter a Stage description.
-
If desired, enter a Deployment description.
-
Choose Deploy.
-
Note the API's Invoke URL.
-
- New REST API console
To deploy your API
Choose Deploy API.
For Stage, select New stage.
For Stage name, enter
test.(Optional) For Description, enter a description.
Choose Deploy.
Under Stage details, choose the copy icon to copy your API's invoke URL.
Use browser and cURL to test an API with Lambda proxy integration
You can use a browser or cURL
To test GET requests using only query string parameters, you can type
the URL for the API's helloworld resource into a browser address bar.
For example:
https://r275xc9bmd.execute-api.us-east-1.amazonaws.com/test/helloworld?name=John&city=Seattle
For other methods, you must use more advanced REST API testing utilities, such as
POSTMAN
- Old REST API console
-
Note
We've redesigned the API Gateway console. The old console experience will no longer be available starting December 2023.
To test the deployed API using cURL:
-
Open a terminal window.
-
Copy the following cURL command and paste it into the terminal window, replacing
with your API's API ID andr275xc9bmdwith the region where your API is deployed.us-east-1curl -v -X POST \ 'https://r275xc9bmd.execute-api.us-east-1.amazonaws.com/test/helloworld?name=John&city=Seattle' \ -H 'content-type: application/json' \ -H 'day: Thursday' \ -d '{ "time": "evening" }'Note
If you're running the command on Windows, use this syntax instead:
curl -v -X POST "https://r275xc9bmd.execute-api.us-east-1.amazonaws.com/test/helloworld?name=John&city=Seattle" -H "content-type: application/json" -H "day: Thursday" -d "{ \"time\": \"evening\" }"
You should get a successful response with a payload similar to the following:
{ "message":"Good evening, John of Seattle. Happy Thursday!", "input":{ "resource":"/helloworld", "path":"/helloworld", "httpMethod":"POST", "headers":{"Accept":"*/*", "content-type":"application/json", "day":"Thursday", "Host":"r275xc9bmd.execute-api.us-east-1.amazonaws.com", "User-Agent":"curl/7.64.0", "X-Amzn-Trace-Id":"Root=1-1a2b3c4d-a1b2c3d4e5f6a1b2c3d4e5f6", "X-Forwarded-For":"72.21.198.64", "X-Forwarded-Port":"443", "X-Forwarded-Proto":"https"}, "multiValueHeaders":{"Accept":["*/*"], "content-type":["application/json"], "day":["Thursday"], "Host":["r275xc9bmd.execute-api.us-east-1.amazonaws.com"], "User-Agent":["curl/0.0.0"], "X-Amzn-Trace-Id":["Root=1-1a2b3c4d-a1b2c3d4e5f6a1b2c3d4e5f6"], "X-Forwarded-For":["192.0.2.1"], "X-Forwarded-Port":["443"], "X-Forwarded-Proto":["https"]}, "queryStringParameters":{"city":"Seattle", "name":"John" }, "multiValueQueryStringParameters":{ "city":["Seattle"], "name":["John"] }, "pathParameters":null, "stageVariables":null, "requestContext":{ "resourceId":"3htbry", "resourcePath":"/helloworld", "httpMethod":"POST", "extendedRequestId":"a1b2c3d4e5f6g7h=", "requestTime":"20/Mar/2019:20:38:30 +0000", "path":"/test/helloworld", "accountId":"123456789012", "protocol":"HTTP/1.1", "stage":"test", "domainPrefix":"r275xc9bmd", "requestTimeEpoch":1553114310423, "requestId":"test-invoke-request", "identity":{"cognitoIdentityPoolId":null, "accountId":null, "cognitoIdentityId":null, "caller":null, "sourceIp":"test-invoke-source-ip", "accessKey":null, "cognitoAuthenticationType":null, "cognitoAuthenticationProvider":null, "userArn":null, "userAgent":"curl/0.0.0","user":null }, "domainName":"r275xc9bmd.execute-api.us-east-1.amazonaws.com", "apiId":"r275xc9bmd" }, "body":"{ \"time\": \"evening\" }", "isBase64Encoded":false } }If you change
POSTtoPUTin the preceding method request, you should get the same response.To test the
GETmethod, copy the followingcURLcommand and paste it into the terminal window, replacingwith your API's API ID andr275xc9bmdwith the region where your API is deployed.us-east-1curl -X GET \ 'https://r275xc9bmd.execute-api.us-east-1.amazonaws.com/test/helloworld?name=John&city=Seattle' \ -H 'content-type: application/json' \ -H 'day: Thursday'You should get a response similar to the result from the preceding
POSTrequest, except that theGETrequest does not have any payload. So thebodyparameter will benull. -
- New REST API console
To test your deployed API using cURL:
-
Open a terminal window.
-
Copy the following cURL command and paste it into the terminal window, and replace the invoke URL with the one you copied in the previous step and add
/helloworldto the end of the URL.Note
If you're running the command on Windows, use this syntax instead:
curl -v -X POST "https://r275xc9bmd.execute-api.us-east-1.amazonaws.com/test/helloworld" -H "content-type: application/json" -d "{ \"greeter\": \"John\" }"To call the API with the query string parameter of
?greeter=John:curl -X GET 'https://r275xc9bmd.execute-api.us-east-1.amazonaws.com/test/helloworld?greeter=John'To call the API with a header parameter of
greeter:John:curl -X GET https://r275xc9bmd.execute-api.us-east-1.amazonaws.com/test/helloworld \ -H 'content-type: application/json' \ -H 'greeter: John'To call the API with a body of
{"greeter":"John"}:curl -X POST https://r275xc9bmd.execute-api.us-east-1.amazonaws.com/test/helloworld \ -H 'content-type: application/json' \ -d '{ "greeter": "John" }'
In all the cases, the output is a 200 response with the following response body:
Hello, John!
-