Rust Overview
Rust is a systems programming language focused on safety, speed, and concurrency, perfect for building high-performance APIs.
Setting Up Rust API
# Install Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Create new project
cargo new my-api
cd my-api
Basic Actix-Web Server
use actix_web::{web, App, HttpResponse, HttpServer};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct User {
id: u32,
name: String,
email: String,
}
async fn get_users() -> Result<HttpResponse> {
let users = vec![
User {
id: 1,
name: "John".to_string(),
email: "john@example.com".to_string(),
}
];
Ok(HttpResponse::Ok().json(users))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/api/users", web::get().to(get_users))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
Best Practices
- Leverage Rust's memory safety
- Use async/await for I/O
- Implement proper error handling
- Use serde for serialization
- Take advantage of Rust's performance