Create and host a Serverless API for your Python Lambda function

·

4 min read

Let's setup a simple API Gateway that calls a simple Python Lambda function in AWS. For this demo, I'm going to piggy-back off of a previous post in which I deploy a Python function to AWS Lambda. Validate that your function is working properly. Once finished, you can begin using the API Gateway.

Login to the AWS Console and navigate to the API Gateway. Click APIs on the left menu, then click Build on REST API (not the private one).

image.png

Ignore the example API and click on "New API". Let's call this "greeting". Add an optional description and an Endpoint Type of Regional.

image.png

Now we need to create a Resource. Under Actions | Create Resource.

image.png Call this resource greeting

Make sure that proxy resource is NOT selected and Enable API Gateway CORS IS selected

image.png

Click Create Resource.

With your newly created resource "greeting" selected, click Actions | Create Method

Select the Method type as POST and click the Checkbox next to POST.

image.png

This next page is where you link your API Gateway to your Lambda function. CHECK the Use Lambda Proxy Integration box. Make sure Lambda Function is selected (default), select the region in which your function exists (us-east-1 is default). If you don't see your function in pop-up in the list under Lambda Function, you probably have the wrong region. Your final screen should look something like this:

image.png Click Save. You will be prompted to allow permissions for the API to use the Lambda function. Click OK.

Deploy the API

Once you've completed the API gateway creation, you'll need to deploy it. With POST selected under your "nameandage" resource, click Actions | Deploy API

image.png

You'll be prompted for a stage and description. If you don't have a stage, you will be able to create a new one. We'll call this "sandbox".

image.png

Click Deploy

Congrats! You've successfully deployed your API. Now we can test it. Grab the "Invoke URL" from the top of the page:

image.png

Create a payload file called event.json and include this contents:

{
    "name": "Joe",
    "city": "Nashville"
}

Now, from a client of your choice, post your data to your API

Use this sample curl command

curl -X POST 'https://<your-api-endpoint>.execute-api.us-east-2.amazonaws.com/sandbox/greeting' -d @event.json

You should receive a json return of your function.

{"statusCode": 200, "body": "\"Greetings Joe from Nashville. !\"", "headers": {"Content-Type": "application/json"}}

This is a baby version of a very powerful set of tools. We'll expand on them more in the coming weeks.

AJ