> ## Documentation Index
> Fetch the complete documentation index at: https://getfloo.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Deploy a Rust Axum API with SQLx and Postgres

> Serve a shop’s pickup count from Postgres. Build an Axum API without database credentials, run its migration on floo, and verify the live response.

Two orders are ready for pickup and a third is still being packed. This Axum endpoint reads the count from Postgres using SQLx. On floo, the Rust binary runs in a Docker image and the database connection string arrives at runtime.

[Open the pickup API](https://seo-demo-rust-workload.getfloo.app/).

To deploy your own copy with a coding agent, paste this from an empty project directory:

```text theme={null}
Read https://getfloo.com/docs/build/rust-axum.md and create the files shown there.
Use an available app name starting with axum-pickup- and deploy my copy to floo.
Read the dev URL and confirm that two orders are ready for pickup.
```

## Query Postgres from Axum

In an empty directory, create `src` and save these two files. The handler uses a runtime SQL query, so the image builds without a database. Each running instance shares one pool of up to four connections.

```toml Cargo.toml theme={null}
[package]
name = "pickup-api"
version = "0.1.0"
edition = "2024"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net"] }
sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "postgres"] }
```

```rust src/main.rs theme={null}
use axum::{Router, extract::State, http::StatusCode, routing::get};
use sqlx::{PgPool, postgres::PgPoolOptions};
use std::{env, error::Error};

async fn ready(State(pool): State<PgPool>) -> Result<String, StatusCode> {
    let count: i64 = sqlx::query_scalar("SELECT count(*) FROM pickups WHERE ready")
        .fetch_one(&pool)
        .await
        .map_err(|error| {
            eprintln!("{error}");
            StatusCode::SERVICE_UNAVAILABLE
        })?;
    Ok(format!("{count} orders ready for pickup\n"))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let pool = PgPoolOptions::new()
        .max_connections(4)
        .connect_lazy(&env::var("DATABASE_URL")?)?;
    match env::args().nth(1).as_deref() {
        Some("migrate") => {
            sqlx::raw_sql(
                "CREATE TABLE IF NOT EXISTS pickups (id integer PRIMARY KEY, ready boolean NOT NULL);
                 INSERT INTO pickups VALUES (1, true), (2, true), (3, false)
                 ON CONFLICT (id) DO NOTHING;",
            )
            .execute(&pool)
            .await?;
        }
        None => {
            let port = env::var("PORT").unwrap_or_else(|_| "8080".into());
            let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}")).await?;
            let app = Router::new().route("/", get(ready)).with_state(pool);
            axum::serve(listener, app).await?;
        }
        Some(other) => return Err(format!("unknown command: {other}").into()),
    }
    Ok(())
}
```

## Build the image and run the migration

```dockerfile Dockerfile theme={null}
FROM rust:1.97-bookworm AS build
WORKDIR /src
COPY Cargo.toml Cargo.lock ./
COPY src ./src
RUN cargo build --locked --release

FROM debian:bookworm-slim
COPY --from=build /src/target/release/pickup-api /axum-pickup-api
USER 65532:65532
CMD ["/axum-pickup-api"]
```

```toml floo.app.toml theme={null}
[app]
name = "axum-pickup-api"
access_mode = "public"

[services.web]
type = "web"
path = "."
port = 8080
ingress = "public"
migrate_command = "/axum-pickup-api migrate"

[managed.default]
type = "postgres"
```

Choose an available app name starting with `axum-pickup-` in `floo.app.toml`. floo runs `/axum-pickup-api migrate` with the new image before it receives traffic. On later deploys, existing order statuses survive the migration. Dev and prod have separate databases.

From the example directory with Rust 1.97, the [floo CLI](https://getfloo.com/docs/introduction.md), and a floo sign-in:

```bash theme={null}
cargo generate-lockfile
git init -b main
git add Cargo.toml Cargo.lock src/main.rs Dockerfile floo.app.toml
git commit -m "Deploy the pickup API"
floo deploy --preflight
floo deploy --hosted
```

## Check the first response

Open the dev URL printed by the deploy. The root path returns HTTP 200 with:

```text theme={null}
2 orders ready for pickup
```

A 503 means the handler could not read Postgres. Check the service logs for the SQLx error and confirm that the migration completed. The sample exposes only a count of fixture orders. For a staff-only API, [configure App sign-in](https://getfloo.com/docs/guides/app-auth.md).

If your existing app uses SQLx’s `query!` macros, generate SQLx offline metadata against your development schema and commit it before building the image. See [SQLx offline builds](https://docs.rs/sqlx/latest/sqlx/macro.query.html#offline-mode) and [connecting to managed Postgres](https://getfloo.com/docs/guides/postgres.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.