# Turso + Actix

> Set up Turso in your Actix project in minutes
> Canonical HTML: https://tursodb.cn/docs/sdk/rust/guides/actix/
> Upstream Source (MIT): https://docs.turso.tech/sdk/rust/guides/actix
> Language: en

---
![Actix banner](/images/turso-docs/guides/actix-banner.png)

## Prerequisites

Before you start, make sure you:

* [Install the Turso CLI](/docs/cli/installation/)
* [Sign up or login to Turso](/docs/cli/authentication/#signup)
* Have an Actix app — [learn more](https://actix.rs/docs/getting-started)

**1. Retrieve database credentials**

You will need an existing database to continue. If you don't have one, [create one](/docs/quickstart/).

Get the database URL:

```bash
turso db show --url <database-name>
```

Get the database authentication token:

```bash
turso db tokens create <database-name>
```

Assign credentials to the environment variables inside `.env`.

```bash
TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=
```

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">NOTE</div><div class="doc-callout-body">

You will want to store these as environment variables.

</div></div>


**2. Add the libsql crate to the project**

```bash
cargo add libsql
```

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">NOTE</div><div class="doc-callout-body">

Optionally, you can add a package such as [`dotenvy`](https://docs.rs/dotenvy/latest/dotenvy) to help you work with `.env` files:

```bash
cargo add dotenvy
```

</div></div>


**3. Execute SQL**

```rust
#[tokio::main]
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().route("/", web::get().to(index)).route("/items", web::get().to(get_items)))
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

async fn get_items() -> Result<HttpResponse, Error> {
    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_file = env::var("LOCAL_DB").unwrap();

    let db = Builder::new_remote_replica(db_file, url, auth_token)
    .read_your_writes(true)
    .build()
    .await
    .unwrap();

    let conn = db.connect().unwrap();

    let mut results = conn.query("SELECT * FROM items", ()).await.unwrap();

    let mut items: Vec<T> = Vec::new();

    while let Some(row) = results.next().await.unwrap() {
        let item: Item = Item {
            task: row.get(0).unwrap(),
        };
        items.push(item);
    }

    Ok(HttpResponse::Ok().json(items))
}
```

## Examples

<div class="doc-cards">
<a class="doc-card" href="https://github.com/tursodatabase/examples/tree/master/app-web-traffic-tracker-actix" target="_blank" rel="noopener noreferrer"><div class="doc-card-title"><span>Turso + Actix Web Traffic Tracker</span><span class="doc-card-arrow" aria-hidden="true">↗</span></div><p class="doc-card-desc">See the full source code</p></a>
</div>
