How to create HTTP/REST APIs using AWS Serverless framework?

Photo by ThisIsEngineering on Pexels.com

HTTP/REST APIs have become the defacto standard of communication between most web applications.

You can create an API and deploy it on a server or on the cloud or go serverless .

To go serverless you can use a tool like AWS lambda.

And to ease the development and deployment of AWS lambda you can use a framework like serverless.

Here are the steps on how to create a HTTP API on AWS Lambda using serverless framework:

Prior to creating the APIs make sure serverless is set up in your machine:

Once the set up is done you can follow the below steps:

  1. Create a new serverless application:

As mentioned in the set up article, If you don’t already have a serverless application set up, you can create one using the following command:

serverless create --template aws-nodejs

This will create a new Node.js-based serverless application in the current directory.

  1. Define your API in the serverless.yml file:

The serverless.yml file is the main configuration file for your serverless application.

It defines all of the AWS resources that your application uses, including the functions and the API Gateway resources.

To define your API, you will need to add a new http event to the function definition for each endpoint you want to create.

Here’s an example of what a simple API definition might look like:

functions:
  createTodo:
    handler: handler.createTodo
    events:
      - http:
          path: /todos
          method: post
          cors: true
  getTodos:
    handler: handler.getTodos
    events:
      - http:
          path: /todos
          method: get
          cors: true
  updateTodo:
    handler: handler.updateTodo
    events:
      - http:
          path: /todos/{id}
          method: put
          cors: true
  deleteTodo:
    handler: handler.deleteTodo
    events:
      - http:
          path: /todos/{id}
          method: delete
          cors: true

This API definition creates four endpoints:

  • POST /todos: Creates a new todo item
  • GET /todos: Gets a list of todo items
  • PUT /todos/{id}: Updates an existing todo item
  • DELETE /todos/{id}: Deletes an existing todo item

Each endpoint is associated with a function that implements the endpoint’s logic.

The cors attribute enables Cross-Origin Resource Sharing (CORS) for the endpoint, which allows web browsers to make requests to the API from a different origin.

  1. Implement your functions:

To implement your functions, you will need to create a new Node.js module that exports the functions.

The name of the module should match the handler value you specified in the serverless.yml file.

For example, if you defined a function named createTodo, the corresponding module would be created in a file named handler.js and it would contain a function named createTodo.

Here’s an example of what the handler.js file might look like:

const todos = [];

exports.createTodo = (event, context, callback) => {
  const todo = JSON.parse(event.body);
  todo.id = todos.length + 1;
  todos.push(todo);
  const response = {
    statusCode: 201,
    body: JSON.stringify(todo),
  };
  callback(null, response);
};

exports.getTodos = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify(todos),
  };
  callback(null, response);
};

exports.updateTodo = (event, context, callback) => {
  const todoId = event.pathParameters.id;
  const todoIndex = todos.findIndex((t) => t.id === parseInt(todoId, 10));
  if (todoIndex === -1) {
    callback(null, {
      statusCode: 404,
      body: JSON.stringify({ error: 'Todo not found' }),
    });
    return;
  }
  const updatedTodo = JSON.parse(event.body);
  todos[todoIndex] = { ...todos[todoIndex], ...updatedTodo };
  const response = {
    statusCode: 200,
    body: JSON.stringify(todos[todoIndex]),
  };
  callback(null, response);
};

exports.deleteTodo = (event, context, callback) => {
  const todoId = event.pathParameters.id;
  const todoIndex = todos.findIndex((t) => t.id === parseInt(todoId, 10));
  if (todoIndex === -1) {
    callback(null, {
      statusCode: 404,
      body: JSON.stringify({ error: 'Todo not found' }),
    });
    return;
  }
  todos.splice(todoIndex, 1);
  callback(null, {
    statusCode: 204,
  });
};

Each function implements the logic for one of the API endpoints.

For example, the createTodo function parses the request body, creates a new todo item, and returns a 201 response with the new item.

  1. Deploy your API:

To deploy your API to AWS, navigate to the root directory of your serverless application and enter the following command:

serverless deploy

This will package and deploy your API to AWS. You should then be able to access it using the API Gateway endpoint that is printed to the console.

That’s it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s