Guides
Turso + Axum
Set up Turso in your Axum project in minutes
Prerequisites
Before you start, make sure you:
- Install the Turso CLI
- Sign up or login to Turso
- Have an Axum app — learn more
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
#[tokio::main]
async fn main() {
let app = Router::new()
// framework routes
.route("/", get(root))
.route("/items", get(get_items));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn get_items() -> IntoResponse {
dotenv().expect(".env file not found");
let db_url = env::var("TURSO_DATABASE_URL").unwrap();
let auth_token = env::var("TURSO_AUTH_TOKEN").unwrap();
let db = Database::open_remote(db_url, auth_token).unwrap();
let conn = db.connect().unwrap();
let mut results = conn.query("SELECT * FROM items", ()).await.unwrap();
let mut items: Vec<Item> = Vec::new();
while let Some(row) = results.next().unwrap() {
let item: Item = Item {
task: row.get(0).unwrap(),
};
items.push(item);
}
(StatusCode::OK, Json(items))
}