Building an API with AWS Lambda and API gateway

Create a Serverless API with AWS Lambda and API Gateway tutorial

Posted on September 4, 2020

Why use Lambda/API gateway

Create a Lambda function

Login to your AWS account and navigate to the Lambda console
Click Create function, select ‘Author from scratch‘, give your function a name and click ‘Create Function

When you create the function, AWS will create role which we can update at a later date to give it access to other services such as DynamoDB.

Now update your function code with the following so we can separate out GET and POSTS requests. Don’t forget to click ‘Save’ in the top right.

exports.handler = async (event) => {
    
    const method = event.httpMethod;
    let response;
    
    if (method === 'GET') {
        response = {
            statusCode: 200,
            body: JSON.stringify('GET success!'),
        };
    } else if(method === 'POST') {
        response = {
            statusCode: 200,
            body: JSON.stringify('POST success!'),
        };
    }
    
    return response;
};

There seems to a bit of a discussion at the moment on whether it’s better to create separate functions for each endpoint or keep it all in one function. I personally think this depends on the size of your application.

The main thing is ensuring your code is easy to find and update.

This is a very small API with just the one endpoint, so we’ll just be creating the one function. 

Create an API gateway (REST API)

Next we need to create the API gateway.

Click ‘Add Trigger‘ in the designer block of the lambda function.
Select API Gateway wit the following settings and click ‘ADD’

We’ve now created a API gateway to trigger your lambda function.

The next thing to do is create a GET and POST method and publish the API.

Repeat this but for the POST method.

We now need to deploy the API by clicking on Actions > Deploy API > deployment stage = default > deploy.

If you navigate back to your Lambda function and click on API Gateway trigger block, you’ll see your methods appear with with the relevant endpoints.

Test your API with postman

I use Postman for testing my APIs which can be downloaded here:
https://www.postman.com/

Copy the API endpoint from the relevant method in the ‘API Gateway’ block on the Lambda function screen, add it postman and click send. You should see ‘GET success!’ or ‘ ‘POST success!’ in the response depending on which method you’ve called.

And there you have it – your first Serverless API built with AWS Lambda and API gateway

Roundup

This is obviously a very simple API, but it gives you the gist of how quick and easy they are to create and deploy.

I’ll cover versioning, CORS, database integration and securing your API with Cognito in a future article.