Building a Serverless REST API with Function Compute and MongoDB

Share this article

We received a lot of great entries in our recent competition to find the best tip for making the most out of Alibaba Cloud services. It was a fun but challenging task for our judges to pick the winners amongst so many helpful and interesting entries. But alas after fiery deliberations and heated debates they’ve decided that the second prize of the competition goes to Nhi Nam Ha. His winning tip is a part of a series on serverless app architecture on Alibaba Cloud, and it covers several Alibaba products.

This tutorial will show you how to deploy a MongoDB database on Alibaba Cloud and use Function Compute to develop a back-end API system to interact with the database.

Overview of NoSQL and MongoDB

Relational databases have been selected as the primary system to manage data in software development for a long time. Its ACID principals promote the data persistency, transaction integrity and concurrency control. Over the last few years, NoSQL (Not only SQL) has become popular. This model solves the impedance mismatch between the relational data structures (tables, rows, fields) and the in-memory data structures of the application (objects). Most importantly, NoSQL is designed to scale horizontally which makes it an excellent choice for modern web applications.

NoSQL could be categorized into 4 groups:

  • Key-Value
  • Document
  • Column family
  • Graph

MongoDB is the most popular system within the document database group. As defined on mongodb.com,

A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.

Alibaba Cloud ApsaraDB for MongoDB

MongoDB databases can be deployed on Alibaba Cloud via its ApsaraDB for MongoDB service. Users can select among 3 pricing schemes:

  • Subscription (Replica Set)
  • PAYG (Pay-As-You-Go) (Replica Set)
  • PAYG (Sharding)

Replication and sharding refers to the data distribution models:

  • Replication copies data across multiple servers. The same piece of data is stored in different places. ApsaraDB for MongoDB uses a 3-server replica set. Replication may help with horizontal scaling of reads.
  • Sharding distributes data across multiple machines so different machine contains different subset of data. This model allows for horizontal scaling of writes.

Create an Instance

In the Alibaba Cloud console, click on Products and you will see ApsaraDB for MongoDB under the ApsaraDB group. Alternatively, you can use the search box to filter the desired service.

Select the pricing scheme, the region, the server specification, and set a password for your database. Alibaba Cloud will tell you how much the service cost you based on what you chose.

More info about the instance parameters is here.

Note: if you are using a free trial account, remember to select a subscription instance. PAYG instances do not include in the trial program.

Set IP Whitelists

To ensure database security Alibaba Cloud automatically block all access to the database. You have to specify IP addresses in the whitelist to gain access to the target instance.

ip

Connection String

After you set your IP whitelist, click on “Database Connection” to see the connection parameters

connection

Use this connection string to connect to the database in your Node.js code.

Function Compute

Function Compute lets you run code without provisioning or managing servers. This service prepares computing resources for you and runs your codes on your behalf elastically and reliably. You only pay for resources actually consumed when running the codes. If your code isn’t executed, you don’t pay.

Function Compute runs your code in response to events. When the event source service triggers an event, the associated function is automatically called to process the event.

From the Alibaba Cloud console, select Function Compute and click on the “+” icon to create a new service

1

In the newly created service, click on the “+” icon to create a new function. You will go through a multi-step wizard to select options for your function.

For Function Template, select “Empty Function”

2

In the “Configure Triggers” step, select “HTTP Trigger” and give it a name. Other settings are as the image below

trigger

In the “Configure Function Settings” step, set a name for your function and select “nodejs6” as runtime

4

Click “Next” in the last two steps to finish the wizard and create the fucntion.

Program Your Function

Click on the function you have just created and click on the “Code” tab. This is where you provide your code for the function to run

code

Use the connection string from your MongoDB server.

Also in this screen you can view the HTTP trigger that will invoke your function. You can also run the trigger to test you function here.

run

Summary

In this tutorial we have learnt about NoSQL database with MongoDB as a popular example. Alibaba Cloud provides its ApsaraDB for MongoDB service to those who want to run MongoDB servers on its cloud. The tutorial then moves to discuss the Function Compute service as a new way to build your application following the emerging Serverless architecture. It shows an example of a Node.js function triggered by an HTTP request to connect to the MongoDB database and perform an “insert” command.

Frequently Asked Questions about Building a Serverless REST API with Function Compute and MongoDB

What is Function Compute and how does it work with MongoDB?

Function Compute is a service provided by Alibaba Cloud that allows you to run your code without provisioning or managing servers. It works seamlessly with MongoDB, a popular NoSQL database, to create serverless applications. When you use Function Compute with MongoDB, you can focus on your code and data, without worrying about server management, capacity planning, and patching. Function Compute automatically scales up and down based on the demand, making it a cost-effective solution for building applications.

How do I set up Function Compute and MongoDB for my serverless application?

Setting up Function Compute and MongoDB involves several steps. First, you need to create a MongoDB instance and a Function Compute service on Alibaba Cloud. Then, you need to configure the Function Compute service to connect to the MongoDB instance. This involves setting up the connection string and the credentials for the MongoDB instance. Once the setup is complete, you can start writing your serverless functions that interact with the MongoDB database.

What are the benefits of using a serverless architecture for my REST API?

A serverless architecture offers several benefits for building a REST API. It eliminates the need for server management, which can significantly reduce operational costs and complexity. It also provides automatic scaling, which means your API can handle any amount of traffic without any manual intervention. Moreover, you only pay for the compute time you consume, making it a cost-effective solution for building APIs.

How do I secure my serverless REST API with Function Compute and MongoDB?

Securing your serverless REST API involves several best practices. You should always use secure connections (HTTPS) to protect data in transit. You should also implement authentication and authorization to control access to your API. With Function Compute and MongoDB, you can use Alibaba Cloud’s built-in security features, such as Identity and Access Management (IAM), to manage access to your resources.

Can I use other databases with Function Compute?

Yes, Function Compute is not limited to MongoDB. You can use any database that can be accessed over the network. This includes other NoSQL databases like DynamoDB and CouchDB, as well as SQL databases like MySQL and PostgreSQL. The choice of database depends on your application’s requirements and your personal preference.

How do I handle errors in my serverless functions?

Error handling is an important aspect of writing serverless functions. You should always write your functions to handle errors gracefully. This includes catching exceptions, logging errors for debugging, and returning meaningful error messages to the client. Function Compute provides built-in error handling features that you can use to manage errors in your functions.

How do I test my serverless functions?

Testing serverless functions can be done in several ways. You can write unit tests for your functions using testing frameworks like Jest or Mocha. You can also use tools like Postman to test your REST API endpoints. Additionally, Alibaba Cloud provides a Function Compute emulator that you can use to test your functions locally before deploying them.

How do I monitor my serverless application?

Monitoring is crucial for maintaining the health and performance of your serverless application. You can use Alibaba Cloud’s monitoring tools to track the performance of your Function Compute service and MongoDB instance. These tools provide metrics like CPU usage, memory usage, and request count, which can help you identify and troubleshoot performance issues.

How do I optimize the performance of my serverless application?

Optimizing the performance of a serverless application involves several strategies. You should write efficient code that minimizes the use of resources. You should also design your application to take advantage of the automatic scaling provided by Function Compute. Additionally, you can use Alibaba Cloud’s performance optimization features, such as provisioned concurrency, to improve the performance of your functions.

How do I migrate my existing REST API to a serverless architecture?

Migrating an existing REST API to a serverless architecture involves several steps. First, you need to refactor your API into serverless functions. Then, you need to set up your Function Compute service and MongoDB instance. Finally, you need to deploy your functions and test your API to ensure it works as expected. The migration process requires careful planning and testing to ensure a smooth transition.

Nhi Nam HaNhi Nam Ha
View Author

I am a Solution Architect focusing on web applications and cloud computing. Currently I am working at Fujitsu Australia as a Senior IT Consultant.

alibabacloudsponsored
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week