Creating a web service in Rust and running it in WebAssembly

In this blog post, I will show you how to create a simple web service in Rust and compile it to Wasm. Then, I will show you how to run the Wasm service on the server using a Wasm runtime.

Creating a web service

To create a web service in Rust, we will use the hyper crate, which is a fast and low-level HTTP library. Hyper provides both server and client APIs for working with HTTP requests and responses. To use hyper, we need to add it as a dependency in our Cargo.toml file:

[dependencies]
hyper = "0.14"

Then, we can write our web service code in the src/main.rs file. The code below creates a simple web service that responds with “Hello, World!” to any GET request:

use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
use std::convert::Infallible;
// A function that handles an incoming request and returns a response
async fn hello_world(_req: Request) -> Result, Infallible> {
Ok(Response::new(Body::from("Hello, World!")))
}
#[tokyo::main]
async fn main() {
// Bind the server to an address
let addr = ([127, 0, 0, 1], 3000).into();
// Create a service function that maps each connection to a hello_world function
let make_service = make_service_fn(|conn| async { Ok::<, Infallible>(service_fn(hello_world))
});
// Create a server with the service function
let server = Server::bind(&addr).serve(make_service);
// Run the server and handle any error
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}

To run the web service locally, we can use the cargo run command in the terminal. This will compile and execute our Rust code. We can then test our web service by sending a GET request using curl or a web browser:

$ curl http://localhost:3000
Hello, World!

Creating a web service client

To demonstrate how to use hyper as a web service client, we can write another Rust program that sends a GET request to our web service and prints the response body. The code below shows how to do this using the hyper::Client struct:

use hyper::{Body, Client};
use hyper::body::HttpBody as _;
#[tokyo::main]
async fn main() {
// Create a client
let client = Client::new();
// Send a GET request to the web service
let uri = "http://localhost:3000".parse().unwrap();
let mut resp = client.get(uri).await.unwrap();
// Print the status code and headers
println!("Response: {}", resp.status());
println!("Headers: {:#?}\n", resp.headers());
// Print the response body
while let Some(chunk) = resp.body_mut().data().await {
let chunk = chunk.unwrap();
println!("{}", std::str::from_utf8(&chunk).unwrap());
}
}

To run the web service client locally, we can use the cargo run command in another terminal. This will compile and execute our Rust code. We should see something like this:

$ cargo run
Response: 200 OK
Headers: {
"content-length": "13",
}
Hello, World!

Creating a database client


To make our web service more useful, we can add some database functionality to it. For example, we can store and retrieve some data from a MySQL database using the mysql_async crate, which is an asynchronous MySQL driver based on tokio. To use mysql_async, we need to add it as a dependency in our Cargo.toml file:

[dependencies]
mysql_async = "0.28"

Then, we can modify our web service code in the src/main.rs file to connect to a MySQL database and execute some queries. The code below assumes that we have a MySQL database running on localhost with the default port (3306), username (root), password (password), and database name (test). The code also assumes that we have a table called users with two columns: id (int) and name (varchar).

use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
use mysql_async::{Pool, Row};
use std::convert::Infallible;
// A function that handles an incoming request and returns a response
async fn hello_world(_req: Request) -> Result, Infallible> {
// Create a pool of connections to the MySQL database
let pool = Pool::new("mysql://root:password@localhost:3306/test");
// Get a connection from the pool
let mut conn = pool.get_conn().await.unwrap();
// Execute a query to insert a new user
conn.exec_drop("INSERT INTO users (name) VALUES (?)", ("Alice",)).await.unwrap();
// Execute a query to select all users
let users: Vec = conn.query("SELECT id, name FROM users").await.unwrap();
// Drop the connection and return it to the pool
drop(conn);
// Format the users as a string
let mut output = String::new();
for user in users {
let (id, name) = mysql_async::from_row(user);
output.push_str(&format!("User {}: {}\n", id, name));
}
// Return the output as the response body
Ok(Response::new(Body::from(output)))
}
#[tokyo::main]
async fn main() {
// Bind the server to an address
let addr = ([127, 0, 0, 1], 3000).into();
// Create a service function that maps each connection to a hello_world function
let make_service = make_service_fn(|conn| async { Ok::<, Infallible>(service_fn(hello_world))
});
// Create a server with the service function
let server = Server::bind(&addr).serve(make_service);
// Run the server and handle any error
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}

To run the web service locally, we can use the cargo run command in the terminal. This will compile and execute our Rust code. We can then test our web service by sending a GET request using curl or a web browser:

$ curl http://localhost:3000
User 1: Alice
User 2: Alice
User 3: Alice

Building and running the web service

To build our web service as a Wasm binary, we need to use the cargo-wasi crate, which is a Cargo subcommand for building Rust code for Wasm using the WebAssembly System Interface (WASI). WASI is a standard interface for Wasm programs to access system resources such as files, network, and environment variables. To install cargo-wasi, we can use the cargo install command:

$ cargo install cargo-wasi

Then, we can use the cargo wasi build command to build our web service as a Wasm binary. This will create a target/wasm32-wasi/debug directory with our Wasm binary file:

$ cargo wasi build
Compiling hyper v0.14.15
Compiling mysql_async v0.28.0
Compiling wasm-service v0.1.0 (/home/user/wasm-service)
Finished dev [unoptimized + debuginfo] target(s) in 1m 23s

To run our web service as a Wasm binary on the server, we must use a Wasm runtime that supports WASI and network features. There are several Wasm runtimes available, such as Wasmtime, Wasmer, and WasmEdge. In this blog post, I will use WasmEdge as an example.

To install WasmEdge follow the instructions on its website.

Then, we use the wasmedge command to run our web service as a Wasm binary. We need to pass some arguments to enable WASI and network features and to bind our web service to an address:

$ wasmedge --dir .:. --dir /tmp:/tmp --net 127.0.0.1:3000 target/wasm32-wasi/debug/wasm_service.wasm --addr 127.0.0.1:3000

We can then test our web service by sending a GET request using curl or a web browser:

$ curl http://localhost:3000
User 1: Alice
User 2: Alice
User 3: Alice

Conclusion

Here we’ve created a simple web service in Rust and compiled it to Wasm. I have also shown you how to run the Wasm service on the server using a Wasm runtime. I hope you have enjoyed this tutorial and learned something new.