Prerequisites

Before you start, make sure you:

1

Retrieve database credentials

You will need an existing database to continue. If you don’t have one, create one.

Get the database URL:

turso db show --url <database-name>

Get the database authentication token:

turso db tokens create <database-name>

Assign credentials to the environment variables inside .env.

TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=
You will want to store these as environment variables.
2

Add the libsql crate to the project

cargo add libsql

Optionally, you can add a package such as dotenvy to help you work with .env files:

cargo add dotenvy
3

Execute SQL

#[get("/todos")]
async fn get_todos() -> Json<Vec<Todo>> {
    dotenv().expect(".env file not found");

    let url = env::var("TURSO_DATABASE_URL").expect("TURSO_DATABASE_URL not found!");
    let token = env::var("TURSO_AUTH_TOKEN").expect("TURSO_AUTH_TOKEN not found!");

    let db = Database::open_remote(url, token).unwrap();
    let conn = db.connect().unwrap();

    let mut response = conn.query("select * from todos", ()).await.unwrap();

    let mut todos: Vec<Todo> = Vec::new();
    while let Some(row) = response.next().unwrap() {
        let todo: Todo = Todo {
            task: row.get(0).unwrap(),
        };
        todos.push(todo);
    }

    Json(todos)
}

#[launch]
fn rocket() -> _ {
    dotenv().ok();
    rocket::build().mount("/", routes![get_todos])
}

Examples