Install Rust
curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
rustc --versionCreate a Web Service with Axum
cargo new myapi && cd myapiAdd dependencies to Cargo.toml:
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"Create src/main.rs:
use axum::{routing::get, Json, Router};
use serde::Serialize;
#[derive(Serialize)]
struct Health { status: String }
async fn health() -> Json<Health> {
Json(Health { status: "ok".into() })
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/health", get(health))
.route("/", get(|| async { "Hello from Rust!" }));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}Build and Run
# Development
cargo run
# Production build (optimized)
cargo build --release
./target/release/myapiSystemd Service
[Unit]
Description=Rust API
After=network.target
[Service]
User=www-data
ExecStart=/opt/myapi/myapi
Restart=on-failure
Environment=RUST_LOG=info
[Install]
WantedBy=multi-user.targetWhy Rust for APIs?
- Memory safety without garbage collection
- Exceptional performance (comparable to C/C++)
- Low memory footprint
- No runtime overhead