Skip to content

Frameworks

Actix, Axum and Rocket

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.

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 needs one more crate: actix-web.

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.

mod error {
    use actix_web::{HttpResponse, ResponseError};
    use thiserror::Error;

    #[derive(Error, Debug)]
    pub enum Error {
        #[error("database error")]
        Db(String),
    }

    impl ResponseError for Error {
        fn error_response(&self) -> HttpResponse {
            match self {
                Error::Db(e) => HttpResponse::InternalServerError().body(e.to_string()),
            }
        }
    }

    impl From<surrealdb::Error> for Error {
        fn from(error: surrealdb::Error) -> Self {
            eprintln!("{error}");
            Self::Db(error.to_string())
        }
    }
}

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:

use std::sync::LazyLock;
static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);

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.

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 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.

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?;

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.

#[derive(SurrealValue, Deserialize)]
pub struct PersonData {
    name: String,
}

#[derive(SurrealValue, Deserialize, Serialize)]
pub struct Person {
    name: String,
    id: RecordId,
}

const PERSON: &str = "person";

#[post("/person/{id}")]
pub async fn create_person(
    id: Path<String>,
    person: Json<PersonData>,
) -> Result<Json<Option<Person>>, Error> {
    let person = DB
        .create((PERSON, id.into_inner()))
        .content(person.into_inner())
        .await?;
    Ok(Json(person))
}

#[get("/person/{id}")]
pub async fn read_person(id: Path<String>) -> Result<Json<Option<Person>>, Error> {
    let person = DB.select((PERSON, id.into_inner())).await?;
    Ok(Json(person))
}

#[put("/person/{id}")]
pub async fn update_person(
    id: Path<String>,
    person: Json<PersonData>,
) -> Result<Json<Option<Person>>, Error> {
    let person = DB
        .update((PERSON, id.into_inner()))
        .content(person.into_inner())
        .await?;
    Ok(Json(person))
}

#[delete("/person/{id}")]
pub async fn delete_person(id: Path<String>) -> Result<Json<Option<Person>>, Error> {
    let person = DB.delete((PERSON, id.into_inner())).await?;
    Ok(Json(person))
}

#[get("/people")]
pub async fn list_people() -> Result<Json<Vec<Person>>, Error> {
    let people = DB.select(PERSON).await?;
    Ok(Json(people))
}

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.

The complete code for each framework looks like this:

Run the Actix app with cargo run.

use actix_web::{App, HttpServer};
use std::sync::LazyLock;
use surrealdb::Surreal;
use surrealdb::engine::remote::ws::Client;
use surrealdb::engine::remote::ws::Ws;
use surrealdb::opt::auth::Root;

static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);

mod error {
    use actix_web::{HttpResponse, ResponseError};
    use thiserror::Error;

    #[derive(Error, Debug)]
    pub enum Error {
        #[error("database error")]
        Db(String),
    }

    impl ResponseError for Error {
        fn error_response(&self) -> HttpResponse {
            match self {
                Error::Db(e) => HttpResponse::InternalServerError().body(e.to_string()),
            }
        }
    }

    impl From<surrealdb::Error> for Error {
        fn from(error: surrealdb::Error) -> Self {
            eprintln!("{error}");
            Self::Db(error.to_string())
        }
    }
}

mod routes {

    use fake::Fake;
    use fake::faker::name::en::FirstName;
    use surrealdb::opt::auth::Record;

    use crate::DB;
    use crate::error::Error;
    use actix_web::web::{Json, Path};
    use actix_web::{delete, get, post, put};
    use serde::{Deserialize, Serialize};
    use surrealdb::types::{RecordId, SurrealValue};
    const PERSON: &str = "person";

    #[derive(SurrealValue, Deserialize)]
    pub struct PersonData {
        name: String,
    }

    #[derive(SurrealValue, Deserialize, Serialize)]
    pub struct Person {
        name: String,
        id: RecordId,
    }

    #[get("/")]
    pub async fn paths() -> &'static str {
        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")]
    pub async fn session() -> Result<Json<String>, Error> {
        let res: Option<String> = DB.query("<string>$session").await?.take(0)?;

        Ok(Json(res.unwrap_or("No session data found!".into())))
    }

    #[post("/person/{id}")]
    pub async fn create_person(
        id: Path<String>,
        person: Json<PersonData>,
    ) -> Result<Json<Option<Person>>, Error> {
        let person = DB
            .create((PERSON, id.into_inner()))
            .content(person.into_inner())
            .await?;
        Ok(Json(person))
    }

    #[get("/person/{id}")]
    pub async fn read_person(id: Path<String>) -> Result<Json<Option<Person>>, Error> {
        let person = DB.select((PERSON, id.into_inner())).await?;
        Ok(Json(person))
    }

    #[put("/person/{id}")]
    pub async fn update_person(
        id: Path<String>,
        person: Json<PersonData>,
    ) -> Result<Json<Option<Person>>, Error> {
        let person = DB
            .update((PERSON, id.into_inner()))
            .content(person.into_inner())
            .await?;
        Ok(Json(person))
    }

    #[delete("/person/{id}")]
    pub async fn delete_person(id: Path<String>) -> Result<Json<Option<Person>>, Error> {
        let person = DB.delete((PERSON, id.into_inner())).await?;
        Ok(Json(person))
    }

    #[get("/people")]
    pub async fn list_people() -> Result<Json<Vec<Person>>, Error> {
        let people = DB.select(PERSON).await?;
        Ok(Json(people))
    }

    #[derive(SurrealValue)]
    struct Params {
        name: String,
        pass: String,
    }

    #[get("/new_user")]
    pub async fn make_new_user() -> Result<String, Error> {
        let name: String = FirstName().fake();
        let pass: String = FirstName().fake();
        let jwt = 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")]
    pub async fn get_new_token() -> String {
        let command = 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]
async fn main() -> Result<(), Box<dyn std::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(())
}

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.

Was this page helpful?

Last updated