---
title: "Actix, Axum and Rocket"
description: "Build a web server with SurrealDB as its storage backend in Actix Web, Axum or Rocket with the Rust SDK: dependencies, an error type, a global client, routes for a person table, and record user sign-up."
canonical_url: "https://surrealdb.com/docs/reference/rust/frameworks/web-servers"
sdk: "Rust SDK"
sdk_version: "4.0.1"
surrealdb_version: "4.x"
last_modified: "2026-11-19T00:34:52Z"
---

> Full SurrealDB documentation index: https://surrealdb.com/docs/llms.txt

# Actix, Axum and Rocket

Build a web server with SurrealDB as its storage backend in Actix Web, Axum or Rocket with the Rust SDK: dependencies, an error type, a global client, routes for a person table, and record user sign-up.

This tutorial builds the same web server with SurrealDB as its storage backend in each of three Rust web frameworks: [Actix Web](https://actix.rs/), [Axum](https://docs.rs/axum/latest/axum/) and [Rocket](https://rocket.rs/). 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](/docs/reference/query-language/statements/define/access/record.md).

## Getting started

Start SurrealDB and open an interactive shell as described in [Starting SurrealDB](/docs/reference/rust/frameworks.md#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

Actix needs one more crate: `actix-web`.

**Axum**

### 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:

```text
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

Rocket needs one more crate: `rocket`, with its `json` feature enabled. Your `Cargo.toml` dependencies should look like this:

```text
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**

Actix's response trait is `ResponseError`. This version keeps the database error's message and returns it in the body of a `500` response.

```rust
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())
        }
    }
}
```

**Axum**

Axum's response trait is `IntoResponse`. This version returns a `500` response with a JSON body.

```rust
mod error {
    use axum::http::StatusCode;
    use axum::response::IntoResponse;
    use axum::response::Response;
    use axum::Json;
    use thiserror::Error;

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

    impl IntoResponse for Error {
        fn into_response(self) -> Response {
            (StatusCode::INTERNAL_SERVER_ERROR, Json(self.to_string())).into_response()
        }
    }

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

**Rocket**

Rocket's response trait is `Responder`. This version builds a `500` response with a JSON body by hand.

```rust
mod error {
    use rocket::http::Status;
    use rocket::response::{self, Responder, Response};
    use rocket::Request;
    use thiserror::Error;

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

    impl<'r> Responder<'r, 'static> for Error {
        fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
            let error_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()
        }
    }

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

## The database client

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:

```rust
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](/docs/reference/rust/concepts/multi-tenancy.md) rather than making a cheap copy of the handle, which matters when the framework clones its state:

**Actix**

Actix provides an [`.app_data()`](https://actix.rs/docs/application/#state) 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**

Axum provides a [`.with_state()`](https://docs.rs/axum/latest/axum/routing/struct.Router.html#method.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**

Rocket provides a [`.manage()`](https://rocket.rs/guide/v0.5/state/) 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](/docs/reference/rust/frameworks.md#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**

Actix registers each handler with `.service()` inside `main()`, and each handler's attribute names its method and path.

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

**Axum**

Axum builds a `Router` inside `main()`, with one `.route()` for each path and the method handlers chained on it.

```rust
let listener = TcpListener::bind("localhost:8080").await?;
let router = 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?;
```

**Rocket**

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.

```rust
#[launch]
pub async fn rocket() -> _ {
    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.

**Actix**

In Actix, the key comes from the `Path` extractor and the body from the `Json` extractor.

```rust
#[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))
}
```

**Axum**

In Axum, the key comes from the `Path` extractor and the body from the `Json` extractor, destructured in the function's arguments.

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

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

const PERSON: &str = "person";

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

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

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

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

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

**Rocket**

In Rocket, the key is a `String` argument named in the route's path, and the body comes from the `data` guard.

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

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

const PERSON: &str = "person";

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

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

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

#[delete("/person/<id>")]
pub async fn delete_person(id: String) -> Result<Json<Option<Person>>, Error> {
    let person = DB.delete((PERSON, &*id)).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](/docs/reference/rust/concepts/working-with-types.md#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](/docs/reference/rust/frameworks.md#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:

**Actix**

Run the Actix app with `cargo run`.

```rust
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(())
}
```

**Axum**

Run the Axum app with `cargo run`.

```rust
use axum::{
    Router,
    routing::{get, post},
};
use std::sync::LazyLock;
use surrealdb::{
    Surreal,
    engine::remote::ws::{Client, Ws},
    opt::auth::Root,
};
use tokio::net::TcpListener;

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

mod error {
    use axum::Json;
    use axum::http::StatusCode;
    use axum::response::IntoResponse;
    use axum::response::Response;
    use thiserror::Error;

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

    impl IntoResponse for Error {
        fn into_response(self) -> Response {
            (StatusCode::INTERNAL_SERVER_ERROR, Json(self.to_string())).into_response()
        }
    }

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

mod routes {
    use crate::DB;
    use crate::error::Error;
    use fake::faker::name::en::FirstName;

    use axum::{Json, extract::Path};
    use fake::Fake;
    use serde::{Deserialize, Serialize};
    use surrealdb::opt::auth::Record;
    use surrealdb::types::{RecordId, SurrealValue};

    const PERSON: &str = "person";

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

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

    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"}' 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"#
    }

    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())))
    }

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

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

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

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

    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,
    }

    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}\""
        ))
    }

    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"
        )
    }
}

#[tokio::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?;

    let listener = TcpListener::bind("localhost:8080").await?;
    let router = 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**

Rocket listens on port 8000 by default, which SurrealDB already uses, so run the Rocket app with `ROCKET_PORT=8080 cargo run`.

```rust
#[macro_use]
extern crate rocket;

use std::sync::LazyLock;
use surrealdb::engine::remote::ws::Client;
use surrealdb::engine::remote::ws::Ws;
use surrealdb::opt::auth::Root;
use surrealdb::Surreal;

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

mod error {
    use rocket::http::Status;
    use rocket::response::{self, Responder, Response};
    use rocket::Request;
    use thiserror::Error;

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

    impl<'r> Responder<'r, 'static> for Error {
        fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
            let error_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()
        }
    }

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

mod routes {

    use fake::Fake;
    use fake::faker::name::en::FirstName;
    use surrealdb::opt::auth::Record;
    use surrealdb::types::{RecordId, SurrealValue};

    use crate::error::Error;
    use crate::DB;
    use rocket::serde::json::Json;
    use rocket::{delete, get, post, put};
    use serde::{Deserialize, Serialize};
    const PERSON: &str = "person";

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

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

    #[derive(SurrealValue, Serialize, Deserialize)]
    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>", data = "<person>")]
    pub async fn create_person(
        id: String,
        person: Json<PersonData>,
    ) -> Result<Json<Option<Person>>, Error> {
        let person = DB
            .create((PERSON, &*id))
            .content(person.into_inner())
            .await?;
        Ok(Json(person))
    }

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

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

    #[delete("/person/<id>")]
    pub async fn delete_person(id: String) -> Result<Json<Option<Person>>, Error> {
        let person = DB.delete((PERSON, &*id)).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))
    }

    #[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")
    }
}

async fn init() -> 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]
pub async fn rocket() -> _ {
    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](/docs/reference/rust/frameworks.md#comparing-a-root-user-and-a-record-user), which is followed by some further steps to try.
