This tutorial builds the same web server with SurrealDB as its storage backend in each of three Rust web frameworks: Actix Web, Axum and Rocket. The explanation is the same for all three, and the code for each framework is in tabs. Choosing a framework in one tab group selects it in every group on the page.
The server has these endpoints:
•
Some endpoints to demonstrate how the HTTP endpoints work to create, select, modify etc. a person table in a database,
•
Other endpoints to display some helpful info for the user,
•
Two endpoints to allow signing up and signing in as a record user.
Getting started
Start SurrealDB and open an interactive shell as described in Starting SurrealDB. The tutorials for every framework use this database, so that page describes it once.
Next, create a new Rust project with the command cargo new your_project_name, go into the newly created directory, and use cargo add to add the dependencies. Every framework needs these four:
•
surrealdb,
•
serde with its derive feature, for the Serialize and Deserialize macros that the framework's JSON types use,
•
thiserror, to make it easy to convert between SurrealDB's error type, other errors and the framework's response types,
•
fake, to create random user names that can be used to sign in to the database as a record user.
Actix
Actix needs one more crate: actix-web.
Axum
Axum needs two more crates: axum, and tokio for the async runtime that both Axum and SurrealDB use. Your Cargo.toml dependencies should look like this:
axum = "0.8.8"
fake = "4.4.0"
serde = { version = "1.0.228", features = ["derive"] }
surrealdb = "4.0.0"
thiserror = "2.0.18"
tokio = "1.49.0"
Rocket
Rocket needs one more crate: rocket, with its json feature enabled. Your Cargo.toml dependencies should look like this:
fake = "4.4.0"
rocket = { version = "0.5.1", features = ["json"] }
serde = { version = "1.0.228", features = ["derive"] }
surrealdb = "4.0.0"
thiserror = "2.0.18"
The error type
The first thing to do is a bit of groundwork to convert database errors into an error type of our own. Implementing From<surrealdb::Error> for this type will let it be used with the ? operator when handling results. It also needs to implement the framework's response trait so that it can be used as output for the server. All of this can be done manually if you prefer, but the thiserror crate saves a certain amount of typing.
Actix's response trait is ResponseError. This version keeps the database error's message and returns it in the body of a 500 response.
Next, we will put the database client together. For simplicity, the client goes inside a LazyLock to make it into a global static, which every handler can use:
Each framework also has a way to hand shared state to its handlers. Cloning a Surreal<C> opens a new session rather than making a cheap copy of the handle, which matters when the framework clones its state:
Actix provides an .app_data() method. The closure given to HttpServer::new runs once per worker thread, so a Surreal<C> cloned into it opens a new session per worker. Registering web::Data::new(db) avoids that, because web::Data is itself a reference count around the value.
Axum provides a .with_state() method. A router clones its state into every route and the State extractor clones it again on each request, so each of those clones would open a new session. Where .with_state() is the better fit, give it an Arc<Surreal<Client>> so that only the Arc is cloned.
Rocket provides a .manage() method. Either approach works here, but if the same client is cloned elsewhere in the application to hand to .manage(), wrap it in an Arc so that the clone does not open a new session.
The app then connects to the database, signs in as the root user and defines the person table and the account access method. This code is the same for every framework: Connecting from Rust shows it, and the sections after it explain each definition. In Actix and Axum it goes at the start of main(). In Rocket it goes in an init() function, which Rocket's rocket() function calls before it starts the server. The complete code below shows it in place.
The routes
The last step is where most of the work takes place: setting up the paths for the framework to handle, and writing the functions that handle the endpoints and (usually) access the database. Each of these functions goes into a module called routes, and the server registers them when it starts:
Actix registers each handler with .service() inside main(), and each handler's attribute names its method and path.
Rocket mounts the handlers with the routes! macro inside its rocket() function, its equivalent of main(), and each handler's attribute names its method and path.
#[launch]pubasyncfnrocket()->_{init().await.expect("Something went wrong, shutting down");rocket::build().mount("/",routes![routes::create_person,routes::read_person,routes::update_person,routes::delete_person,routes::list_people,routes::paths,routes::make_new_user,routes::get_new_token,routes::session],)}
Many functions require some JSON data from the user, which is deserialised into a PersonData struct. The database can then use it in methods such as .create().content(). The output returned has a name and an id, which the Person struct holds. These structs would normally only need to implement SurrealValue, but they also implement Serialize and Deserialize because the frameworks' JSON types require them.
Each handler is short: it takes the record key from the path and the user input from the body, passes them to a query, and returns the result as JSON.
In Actix, the key comes from the Path extractor and the body from the Json extractor.
When a handler returns a Person as JSON, it serialises the id as an object of the table and the key, such as {"table":"person","key":{"String":"one"}}, rather than as "one". To return the key on its own, see Record IDs in a JSON response.
The remaining four handlers call the database in the same way in every framework, so the complete code below shows them with each framework's attributes:
•
paths(), at /, returns a table of the paths, with a sample curl command for each.
•
session(), at /session, returns the current session data.
•
make_new_user(), at /new_user, signs up a record user with a random name and password and returns its token. Signing up a record user from Rust explains this code and the session query.
•
get_new_token(), at /new_token, returns a curl command for the /signin endpoint, which a record user with an expired token can use to get a new one.
Experimenting with the app
The complete code for each framework looks like this:
Run the Actix app with cargo run.
useactix_web::{App,HttpServer};usestd::sync::LazyLock;usesurrealdb::Surreal;usesurrealdb::engine::remote::ws::Client;usesurrealdb::engine::remote::ws::Ws;usesurrealdb::opt::auth::Root;staticDB: LazyLock<Surreal<Client>> =LazyLock::new(Surreal::init);moderror{useactix_web::{HttpResponse,ResponseError};usethiserror::Error; #[derive(Error,Debug)]pubenumError{ #[error("database error")]Db(String),}implResponseErrorforError{fnerror_response(&self)->HttpResponse{matchself{Error::Db(e)=>HttpResponse::InternalServerError().body(e.to_string()),}}}implFrom<surrealdb::Error> forError{fnfrom(error: surrealdb::Error)->Self{eprintln!("{error}");Self::Db(error.to_string())}}}modroutes{usefake::Fake;usefake::faker::name::en::FirstName;usesurrealdb::opt::auth::Record;usecrate::DB;usecrate::error::Error;useactix_web::web::{Json,Path};useactix_web::{delete,get,post,put};useserde::{Deserialize,Serialize};usesurrealdb::types::{RecordId,SurrealValue};constPERSON: &str="person"; #[derive(SurrealValue,Deserialize)]pubstructPersonData{name: String,} #[derive(SurrealValue,Deserialize,Serialize)]pubstructPerson{name: String,id: RecordId,} #[get("/")]pubasyncfnpaths()->&'staticstr{r#"----------------------------------------------------------------------------------------------------------------------------------------- PATH | SAMPLE COMMAND -----------------------------------------------------------------------------------------------------------------------------------------/session: See session data | curl -X GET -H "Content-Type: application/json" http://localhost:8080/session |/person/{id}: | Create a person | curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe"}' http://localhost:8080/person/one Get a person | curl -X GET -H "Content-Type: application/json" http://localhost:8080/person/one Update a person | curl -X PUT -H "Content-Type: application/json" -d '{"name":"Jane Doe"}' http://localhost:8080/person/one Delete a person | curl -X DELETE -H "Content-Type: application/json" http://localhost:8080/person/one |/people: List all people | curl -X GET -H "Content-Type: application/json" http://localhost:8080/people/new_user: Create a new record user/new_token: Get instructions for a new token if yours has expired"#} #[get("/session")]pubasyncfnsession()->Result<Json<String>,Error> {letres: Option<String> =DB.query("<string>$session").await?.take(0)?;Ok(Json(res.unwrap_or("No session data found!".into())))} #[post("/person/{id}")]pubasyncfncreate_person(id: Path<String>,person: Json<PersonData>,)->Result<Json<Option<Person>>,Error> {letperson=DB .create((PERSON,id.into_inner())) .content(person.into_inner()) .await?;Ok(Json(person))} #[get("/person/{id}")]pubasyncfnread_person(id: Path<String>)->Result<Json<Option<Person>>,Error> {letperson=DB.select((PERSON,id.into_inner())).await?;Ok(Json(person))} #[put("/person/{id}")]pubasyncfnupdate_person(id: Path<String>,person: Json<PersonData>,)->Result<Json<Option<Person>>,Error> {letperson=DB .update((PERSON,id.into_inner())) .content(person.into_inner()) .await?;Ok(Json(person))} #[delete("/person/{id}")]pubasyncfndelete_person(id: Path<String>)->Result<Json<Option<Person>>,Error> {letperson=DB.delete((PERSON,id.into_inner())).await?;Ok(Json(person))} #[get("/people")]pubasyncfnlist_people()->Result<Json<Vec<Person>>,Error> {letpeople=DB.select(PERSON).await?;Ok(Json(people))} #[derive(SurrealValue)]structParams{name: String,pass: String,} #[get("/new_user")]pubasyncfnmake_new_user()->Result<String,Error> {letname: String=FirstName().fake();letpass: String=FirstName().fake();letjwt=DB .signup(Record{access: "account".to_string(),namespace: "main".to_string(),database: "main".to_string(),params: Params{name: name.clone(),pass: pass.clone(),},}) .await? .access .into_insecure_token();Ok(format!("New user created!\n\nName: {name}\nPassword: {pass}\nToken: {jwt}\n\nTo log in, use this command:\n\nsurreal sql --pretty --token \"{jwt}\""))} #[get("/new_token")]pubasyncfnget_new_token()->String{letcommand=r#"curl -X POST -H "Accept: application/json" -d '{"ns":"main","db":"main","ac":"account","user":"your_username","pass":"your_password"}' http://localhost:8000/signin"#;format!("Need a new token? Use this command:\n\n{command}\n\nThen log in with surreal db sql --pretty --token YOUR_TOKEN_HERE")}}#[actix_web::main]asyncfnmain()->Result<(),Box<dynstd::error::Error>> {DB.connect::<Ws>("localhost:8000").await?;DB.signin(Root{username: "root".to_string(),password: "secret".to_string(),}) .await?;DB.use_ns("main").use_db("main").await?;DB.query(" DEFINE TABLE IF NOT EXISTS person SCHEMALESS PERMISSIONS FOR CREATE, SELECT WHERE $auth, FOR UPDATE, DELETE WHERE created_by = $auth; DEFINE FIELD IF NOT EXISTS name ON TABLE person TYPE string; DEFINE FIELD IF NOT EXISTS created_by ON TABLE person VALUE $auth READONLY; DEFINE INDEX IF NOT EXISTS unique_name ON TABLE user FIELDS name UNIQUE; DEFINE ACCESS IF NOT EXISTS account ON DATABASE TYPE RECORD SIGNUP ( CREATE user SET name = $name, pass = crypto::argon2::generate($pass) ) SIGNIN ( SELECT * FROM user WHERE name = $name AND crypto::argon2::compare(pass, $pass) ) DURATION FOR TOKEN 15m, FOR SESSION 12h;",) .await?;HttpServer::new(|| {App::new() .service(routes::create_person) .service(routes::read_person) .service(routes::update_person) .service(routes::delete_person) .service(routes::list_people) .service(routes::paths) .service(routes::session) .service(routes::make_new_user) .service(routes::get_new_token)}) .bind(("localhost",8080))? .run() .await?;Ok(())}
Run the Axum app with cargo run.
useaxum::{Router,routing::{get,post},};usestd::sync::LazyLock;usesurrealdb::{Surreal,engine::remote::ws::{Client,Ws},opt::auth::Root,};usetokio::net::TcpListener;staticDB: LazyLock<Surreal<Client>> =LazyLock::new(Surreal::init);moderror{useaxum::Json;useaxum::http::StatusCode;useaxum::response::IntoResponse;useaxum::response::Response;usethiserror::Error; #[derive(Error,Debug)]pubenumError{ #[error("database error")]Db,}implIntoResponseforError{fninto_response(self)->Response{(StatusCode::INTERNAL_SERVER_ERROR,Json(self.to_string())).into_response()}}implFrom<surrealdb::Error> forError{fnfrom(error: surrealdb::Error)->Self{eprintln!("{error}");Self::Db}}}modroutes{usecrate::DB;usecrate::error::Error;usefake::faker::name::en::FirstName;useaxum::{Json,extract::Path};usefake::Fake;useserde::{Deserialize,Serialize};usesurrealdb::opt::auth::Record;usesurrealdb::types::{RecordId,SurrealValue};constPERSON: &str="person"; #[derive(SurrealValue,Deserialize,Clone)]pubstructPersonData{name: String,} #[derive(SurrealValue,Serialize,Deserialize)]pubstructPerson{name: String,id: RecordId,}pubasyncfnpaths()->&'staticstr{r#"----------------------------------------------------------------------------------------------------------------------------------------- PATH | SAMPLE COMMAND -----------------------------------------------------------------------------------------------------------------------------------------/session: See session data | curl -X GET -H "Content-Type: application/json" http://localhost:8080/session |/person/{id}: | Create a person | curl -X POST -H "Content-Type: application/json" -d '{"name":"John"}' http://localhost:8080/person/one Update a person | curl -X PUT -H "Content-Type: application/json" -d '{"name":"Jane"}' http://localhost:8080/person/one Get a person | curl -X GET -H "Content-Type: application/json" http://localhost:8080/person/one Delete a person | curl -X DELETE -H "Content-Type: application/json" http://localhost:8080/person/one |/people: List all people | curl -X GET -H "Content-Type: application/json" http://localhost:8080/people/new_user: Create a new record user/new_token: Get instructions for a new token if yours has expired"#}pubasyncfnsession()->Result<Json<String>,Error> {letres: Option<String> =DB.query("<string>$session").await?.take(0)?;Ok(Json(res.unwrap_or("No session data found!".into())))}pubasyncfncreate_person(id: Path<String>,Json(person): Json<PersonData>,)->Result<Json<Option<Person>>,Error> {letperson=DB.create((PERSON,id.0)).content(person).await?;Ok(Json(person))}pubasyncfnread_person(id: Path<String>)->Result<Json<Option<Person>>,Error> {letperson=DB.select((PERSON,id.0)).await?;Ok(Json(person))}pubasyncfnupdate_person(id: Path<String>,Json(person): Json<PersonData>,)->Result<Json<Option<Person>>,Error> {letperson=DB.update((PERSON,id.0)).content(person).await?;Ok(Json(person))}pubasyncfndelete_person(id: Path<String>)->Result<Json<Option<Person>>,Error> {letperson=DB.delete((PERSON,id.0)).await?;Ok(Json(person))}pubasyncfnlist_people()->Result<Json<Vec<Person>>,Error> {letpeople=DB.select(PERSON).await?;Ok(Json(people))} #[derive(SurrealValue)]structParams{name: String,pass: String,}pubasyncfnmake_new_user()->Result<String,Error> {letname: String=FirstName().fake();letpass: String=FirstName().fake();letjwt=DB .signup(Record{access: "account".to_string(),namespace: "main".to_string(),database: "main".to_string(),params: Params{name: name.clone(),pass: pass.clone(),},}) .await? .access .into_insecure_token();Ok(format!("New user created!\n\nName: {name}\nPassword: {pass}\nToken: {jwt}\n\nTo log in, use this command:\n\nsurreal sql --pretty --token \"{jwt}\""))}pubasyncfnget_new_token()->String{letcommand=r#"curl -X POST -H "Accept: application/json" -d '{"ns":"main","db":"main","ac":"account","user":"your_username","pass":"your_password"}' http://localhost:8000/signin"#;format!("Need a new token? Use this command:\n\n{command}\n\nThen log in with surreal db sql --pretty --token YOUR_TOKEN_HERE")}}#[tokio::main]asyncfnmain()->Result<(),Box<dynstd::error::Error>> {DB.connect::<Ws>("localhost:8000").await?;DB.signin(Root{username: "root".to_string(),password: "secret".to_string(),}) .await?;DB.use_ns("main").use_db("main").await?;DB.query(" DEFINE TABLE IF NOT EXISTS person SCHEMALESS PERMISSIONS FOR CREATE, SELECT WHERE $auth, FOR UPDATE, DELETE WHERE created_by = $auth; DEFINE FIELD IF NOT EXISTS name ON TABLE person TYPE string; DEFINE FIELD IF NOT EXISTS created_by ON TABLE person VALUE $auth READONLY; DEFINE INDEX IF NOT EXISTS unique_name ON TABLE user FIELDS name UNIQUE; DEFINE ACCESS IF NOT EXISTS account ON DATABASE TYPE RECORD SIGNUP ( CREATE user SET name = $name, pass = crypto::argon2::generate($pass) ) SIGNIN ( SELECT * FROM user WHERE name = $name AND crypto::argon2::compare(pass, $pass) ) DURATION FOR TOKEN 15m, FOR SESSION 12h;",) .await?;letlistener=TcpListener::bind("localhost:8080").await?;letrouter=Router::new() .route("/",get(routes::paths)) .route("/person/{*id}",post(routes::create_person) .get(routes::read_person) .put(routes::update_person) .delete(routes::delete_person),) .route("/people",get(routes::list_people)) .route("/session",get(routes::session)) .route("/new_user",get(routes::make_new_user)) .route("/new_token",get(routes::get_new_token));axum::serve(listener,router).await?;Ok(())}
Rocket listens on port 8000 by default, which SurrealDB already uses, so run the Rocket app with ROCKET_PORT=8080 cargo run.
#[macro_use]externcraterocket;usestd::sync::LazyLock;usesurrealdb::engine::remote::ws::Client;usesurrealdb::engine::remote::ws::Ws;usesurrealdb::opt::auth::Root;usesurrealdb::Surreal;staticDB: LazyLock<Surreal<Client>> =LazyLock::new(Surreal::init);moderror{userocket::http::Status;userocket::response::{self,Responder,Response};userocket::Request;usethiserror::Error; #[derive(Error,Debug)]pubenumError{ #[error("database error")]Db,}impl<'r> Responder<'r,'static> forError{fnrespond_to(self,_: &'rRequest<'_>)->response::Result<'static> {leterror_message=format!(r#"{{ "error": "{self}" }}"#);Response::build() .status(Status::InternalServerError) .header(rocket::http::ContentType::JSON) .sized_body(error_message.len(),std::io::Cursor::new(error_message)) .ok()}}implFrom<surrealdb::Error> forError{fnfrom(error: surrealdb::Error)->Self{eprintln!("{error}");Self::Db}}}modroutes{usefake::Fake;usefake::faker::name::en::FirstName;usesurrealdb::opt::auth::Record;usesurrealdb::types::{RecordId,SurrealValue};usecrate::error::Error;usecrate::DB;userocket::serde::json::Json;userocket::{delete,get,post,put};useserde::{Deserialize,Serialize};constPERSON: &str="person"; #[derive(SurrealValue)]structParams{name: String,pass: String,} #[derive(SurrealValue,Serialize,Deserialize,Clone)]pubstructPersonData{name: String,} #[derive(SurrealValue,Serialize,Deserialize)]pubstructPerson{name: String,id: RecordId,} #[get("/")]pubasyncfnpaths()->&'staticstr{r#"----------------------------------------------------------------------------------------------------------------------------------------- PATH | SAMPLE COMMAND -----------------------------------------------------------------------------------------------------------------------------------------/session: See session data | curl -X GET -H "Content-Type: application/json" http://localhost:8080/session |/person/{id}: | Create a person | curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe"}' http://localhost:8080/person/one Get a person | curl -X GET -H "Content-Type: application/json" http://localhost:8080/person/one Update a person | curl -X PUT -H "Content-Type: application/json" -d '{"name":"Jane Doe"}' http://localhost:8080/person/one Delete a person | curl -X DELETE -H "Content-Type: application/json" http://localhost:8080/person/one |/people: List all people | curl -X GET -H "Content-Type: application/json" http://localhost:8080/people/new_user: Create a new record user/new_token: Get instructions for a new token if yours has expired"#} #[get("/session")]pubasyncfnsession()->Result<Json<String>,Error> {letres: Option<String> =DB.query("<string>$session").await?.take(0)?;Ok(Json(res.unwrap_or("No session data found!".into())))} #[post("/person/<id>",data="<person>")]pubasyncfncreate_person(id: String,person: Json<PersonData>,)->Result<Json<Option<Person>>,Error> {letperson=DB .create((PERSON,&*id)) .content(person.into_inner()) .await?;Ok(Json(person))} #[get("/person/<id>")]pubasyncfnread_person(id: String)->Result<Json<Option<Person>>,Error> {letperson=DB.select((PERSON,&*id)).await?;Ok(Json(person))} #[put("/person/<id>",data="<person>")]pubasyncfnupdate_person(id: String,person: Json<PersonData>,)->Result<Json<Option<Person>>,Error> {letperson=DB .update((PERSON,&*id)) .content(person.into_inner()) .await?;Ok(Json(person))} #[delete("/person/<id>")]pubasyncfndelete_person(id: String)->Result<Json<Option<Person>>,Error> {letperson=DB.delete((PERSON,&*id)).await?;Ok(Json(person))} #[get("/people")]pubasyncfnlist_people()->Result<Json<Vec<Person>>,Error> {letpeople=DB.select(PERSON).await?;Ok(Json(people))} #[get("/new_user")]pubasyncfnmake_new_user()->Result<String,Error> {letname: String=FirstName().fake();letpass: String=FirstName().fake();letjwt=DB .signup(Record{access: "account".to_string(),namespace: "main".to_string(),database: "main".to_string(),params: Params{name: name.clone(),pass: pass.clone(),},}) .await? .access .into_insecure_token();Ok(format!("New user created!\n\nName: {name}\nPassword: {pass}\nToken: {jwt}\n\nTo log in, use this command:\n\nsurreal sql --pretty --token \"{jwt}\""))} #[get("/new_token")]pubasyncfnget_new_token()->String{letcommand=r#"curl -X POST -H "Accept: application/json" -d '{"ns":"main","db":"main","ac":"account","user":"your_username","pass":"your_password"}' http://localhost:8000/signin"#;format!("Need a new token? Use this command:\n\n{command}\n\nThen log in with surreal db sql --pretty --token YOUR_TOKEN_HERE")}}asyncfninit()->Result<(),surrealdb::Error> {DB.connect::<Ws>("localhost:8000").await?;DB.signin(Root{username: "root".to_string(),password: "secret".to_string(),}) .await?;DB.use_ns("main").use_db("main").await?;DB.query(" DEFINE TABLE IF NOT EXISTS person SCHEMALESS PERMISSIONS FOR CREATE, SELECT WHERE $auth, FOR UPDATE, DELETE WHERE created_by = $auth; DEFINE FIELD IF NOT EXISTS name ON TABLE person TYPE string; DEFINE FIELD IF NOT EXISTS created_by ON TABLE person VALUE $auth READONLY; DEFINE INDEX IF NOT EXISTS unique_name ON TABLE user FIELDS name UNIQUE; DEFINE ACCESS IF NOT EXISTS account ON DATABASE TYPE RECORD SIGNUP ( CREATE user SET name = $name, pass = crypto::argon2::generate($pass) ) SIGNIN ( SELECT * FROM user WHERE name = $name AND crypto::argon2::compare(pass, $pass) ) DURATION FOR TOKEN 15m, FOR SESSION 12h;",) .await?;Ok(())}#[launch]pubasyncfnrocket()->_{init().await.expect("Something went wrong, shutting down");rocket::build().mount("/",routes![routes::create_person,routes::read_person,routes::update_person,routes::delete_person,routes::list_people,routes::paths,routes::make_new_user,routes::get_new_token,routes::session],)}
Open http://localhost:8080 to see the paths. The app is signed in as the root user, so the /person routes can perform any operation on the person records. To see how the permissions limit a record user, create one with /new_user and follow Comparing a root user and a record user, which is followed by some further steps to try.