Use Workers KV directly from Rust
This tutorial will teach you how to read and write to KV directly from Rust using workers-rs ↗.
Before you start
All of the tutorials assume you have already completed the Get started guide, which gets you set up with a Cloudflare Workers account, C3 ↗, and Wrangler.
Prerequisites
To complete this tutorial, you will need:
1. Create your Worker project in Rust
Open a terminal window, and run the following command to generate a Worker project template in Rust:
Then select template/hello-world-http
template, give your project a descriptive name and select enter. A new project should be created in your directory. Open the project in your editor and run npx wrangler dev
to compile and run your project.
In this tutorial, you will use Workers KV from Rust to build an app to store and retrieve cities by a given country name.
2. Create a KV namespace
In the terminal, use Wrangler to create a KV namespace for cities
. This generates a configuration to be added to the project:
To add this configuration to your project, open the wrangler.toml
file and create an entry for kv_namespaces
above the build command:
With this configured, you can access the KV namespace with the binding "cities"
from Rust.
3. Write data to KV
For this app, you will create two routes: A POST
route to receive and store the city in KV, and a GET
route to retrieve the city of a given country. For example, a POST
request to /France
with a body of {"city": "Paris"}
should create an entry of Paris as a city in France. A GET
request to /France
should retrieve from KV and respond with Paris.
Install Serde ↗ as a project dependency to handle JSON cargo add serde
. Then create an app router and a struct for Country
in src/lib.rs
:
For the post handler, you will retrieve the country name from the path and the city name from the request body. Then, you will save this in KV with the country as key and the city as value. Finally, the app will respond with the city name:
Save the file and make a POST
request to test this endpoint:
4. Read data from KV
To retrieve cities stored in KV, write a GET
route that pulls the country name from the path and searches KV. You also need some error handling if the country is not found:
Save and make a curl request to test the endpoint:
5. Deploy your project
The source code for the completed app should include the following:
To deploy your Worker, run the following command: