Creating Serverless API using Cloudflare Workers and Rust

Abhinav Yadav
Intelliconnect Engineering
5 min readJul 20, 2022
cloudflare workers with rust
Image from blog.cloudflare.com

This article has been deprecated because of changes to the Cloudflare Workers library. Please check the updated version titled “Create a Serverless REST API using Cloudflare Workers, Rust & MongoDB”

In this article, we will create a serverless API using Cloudflare workers and the Rust Programming Language. You can find the code for this article on GitHub.

We will be connecting with MongoDB using the MongoDB “Data API”. Traditionally our REST APIs connect to databases using a TCP connection. However Cloudflare Serverless APIs cannot connect to a DatabaseBase using TCP. Cloudflare plans to release the Cloudflare D1 which is a serverless SQL Database. Do check more information on the Cloudflare Blog titled “Announcing D1: our first SQL database.

Another option is to use Supabase — The Supabase community provides a crate for querying the database. You can check the connectivity tools provided by them here.

In this article, we are going to usethe Native Rust SDK officially provided by Cloudflare to create API.

Technologies Used:

Rust (Programming language)

Cloudflare Workers (Serverless Platform)

MongoDB (Database)

Setup:

Install wrangler, a CLI tool to build test, and deploy workers. We are using wrangler 2 for this article, you can use wrangler 1 as well. You can find the difference between those here. After installing, login to your account with it.

# for npm users
npm install -g wrangler
# for yarn users
yarn global add wrangler
# for wrangler 1 (if you want)
npm install -g @cloudflare/wrangler
# check if it’s installed correctly
wrangle --version
# login to your account
wrangler login

Clone the workers template from GitHub

# rust starter template for cloudflare workers
git clone https://github.com/cloudflare/rustwasm-worker-template
# or clone this article code
git clone https://github.com/cloudflare/rustwasm-worker-template/ cloudflare_serverless
cd cloudflare_serverless

Store your MongoDB data API secret key or any other secret key (if you are using another database) with the below command, you can use this secret in the workers code with just a function call. {Note: Remember that anyone having access to the secret key can access your database}

# create a secret with name mongo_data_api_key
wrangler secret put mongo_data_api_key
# it will ask for secret key, paste it and press enter

Now first we are going to write a helper function to make HTTP requests to MongoDB, then create GET and POST routes for getting and storing a document in a collection.

Helper Function

In the src/utils.rs add the below code

Helper function to do operations on MongoDB

you can take a look at MongoDB Data API Documents to improve this function or customize it in your on way. You can also take a look at worker-rs docs. Check the code for file utils.rs here.

GET a Document from MongoDB

In the src/lib.rs file, we have got router (similar to express JS if you have used it before). It provides us with the request (contains request body, method, etc.) and context (contains the secrets, durable object, etc.). You can take a look at worker-rs docs for more information.

Create an endpoint /mongo as in the below code.

Endpoint for getting data from MongoDB

There are two types of method functions on router struct, the async ones and without async ones. We are using async functions since we are fetching data from database asynchronously. This function takes the endpoint name as the first argument and closure as the second argument. If you are using an async function, pass in closure with async move key word. The closure takes two argument req (request) and ctx (context). We don’t require request body in GET and using context to get the secret for MongoDB.

POST a document to MongoDB

In the src/lib.rs file, add the below code.

We are using the req argument here to get the JSON body sent to this endpoint. Other than that, there is not much difference here from the get endpoint. Here we are doing the insertone operation on MongoDB collection.

Running the API

From the root of the project, You can run the following command to test locally

wrangler dev

this will start a server locally on port 8787 by default, if you are using wrangler 1 then it sends the request to your Cloudflare worker online but if you are using wrangler 2 then it runs a local worker (it uses miniflare).

For publishing your worker online, you can run the below command

wrangler publish

for more option on publishing the worker and other configuration, you can take a look at wrangler docs.

Testing

For testing, If you want to use command line, I suggest httpie. It’s my favorite tool. For testing GET request, you can run

# using httpie
http localhost:8787/mongo
# using curl
curl localhost:8787/mongo

for a JSON POST request

http POST localhost:8787/mongo_post description=describe\ the\ task completed:=true

now, this is one of the reasons I like httpie, the above is a post request with JSON payload. You can find the httpie docs here.

If you don’t want to use a CLI tool and want to keep record of APIs, you can use the usual suspect Postman.

Conclusion

You can find the complete code in our GitHub repository. I have also added two additional endpoints to get and set key value pair on Cloudflare KV store in the code. If I have any queries, please reach out to us.

Hope this helps you to start your journey in Serverless Programming using Cloudflare workers. Thanks for reading.

--

--