Introduction
Creating a CRUD (Create, Read, Update, Delete) application is a fundamental skill for any web developer. In this tutorial, we'll explore how to build a CRUD app using Rust with the Actix web framework and HTMX for dynamic user interfaces without writing JavaScript.
Setting Up Your Environment
Before we begin, ensure you have Rust and Cargo installed on your system. You'll also need to set up HTMX, which you can include in your HTML files directly from a CDN or by installing it via npm.
Creating a New Rust Project
Start by creating a new Rust project using Cargo:
cargo new rust_actix_htmx_crud
cd rust_actix_htmx_crud
Adding Dependencies Add the following dependencies to your Cargo.toml file:
[dependencies]
actix-web = "4.0"
actix-rt = "2.0"
serde = { version = "1.0", features = ["derive"] }
sqlx = { version = "0.5", features = ["postgres"] }
dotenv = "0.15"
Defining Your Data Model Define your data model in a new file src/model.rs. For this example, we’ll create a simple Todo struct:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Todo {
pub id: i32,
pub title: String,
pub completed: bool,
}
// Add SQLX data interaction code here
Creating Actix Handlers In src/main.rs, set up your Actix handlers for each CRUD operation:
mod model;
use model::Todo;
use actix_web::{web, App, HttpServer, Responder};
// Handlers go here
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
// Routes will be defined here
})
.bind("127.0.0.1:8080")?
.run()
.await
}
ntegrating HTMX Integrate HTMX into your HTML templates to handle the CRUD operations dynamically. Here’s an example of how you might use HTMX to delete a Todo item:
<button hx-delete="/delete_todo" hx-target="#todo-list" hx-swap="outerHTML">
Delete
</button>
Conclusion By following these steps, you’ll have a basic CRUD app running with Rust, Actix, and HTMX. This combination allows you to write safe and efficient server-side code while keeping your front-end dynamic and interactive with minimal JavaScript.