Build high-performance web applications with Rust and Actix framework
# Rust Web Development with Actix
Build blazing-fast web applications with Rust and Actix using Google Antigravity IDE. This comprehensive guide covers routing, middleware, and async patterns for production-ready APIs.
## Why Rust for Web?
Rust provides memory safety without garbage collection, enabling high-performance web services. Google Antigravity IDE's Gemini 3 engine offers intelligent Rust patterns and performance suggestions.
## Project Setup
```rust
// Cargo.toml
[package]
name = "antigravity-api"
version = "0.1.0"
edition = "2021"
[dependencies]
actix-web = "4"
actix-rt = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
sqlx = { version = "0.7", features = ["runtime-tokio", "postgres"] }
dotenv = "0.15"
env_logger = "0.10"
```
## Application Structure
```rust
// src/main.rs
use actix_web::{web, App, HttpServer, middleware};
use sqlx::postgres::PgPoolOptions;
use std::env;
mod handlers;
mod models;
mod error;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
dotenv::dotenv().ok();
env_logger::init();
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await
.expect("Failed to create pool");
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone()))
.wrap(middleware::Logger::default())
.wrap(middleware::Compress::default())
.configure(handlers::configure_routes)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
```
## Request Handlers
```rust
// src/handlers/user.rs
use actix_web::{web, HttpResponse, Result};
use sqlx::PgPool;
use crate::models::{User, CreateUser, UpdateUser};
use crate::error::ApiError;
pub async fn get_users(
pool: web::Data<PgPool>,
query: web::Query<PaginationParams>,
) -> Result<HttpResponse, ApiError> {
let users = sqlx::query_as!(
User,
r#"
SELECT id, email, name, created_at, updated_at
FROM users
ORDER BY created_at DESC
LIMIT $1 OFFSET $2
"#,
query.limit.unwrap_or(20) as i64,
query.offset.unwrap_or(0) as i64
)
.fetch_all(pool.get_ref())
.await?;
Ok(HttpResponse::Ok().json(users))
}
pub async fn create_user(
pool: web::Data<PgPool>,
body: web::Json<CreateUser>,
) -> Result<HttpResponse, ApiError> {
let user = sqlx::query_as!(
User,
r#"
INSERT INTO users (email, name, password_hash)
VALUES ($1, $2, $3)
RETURNING id, email, name, created_at, updated_at
"#,
body.email,
body.name,
hash_password(&body.password)?
)
.fetch_one(pool.get_ref())
.await?;
Ok(HttpResponse::Created().json(user))
}
pub async fn get_user(
pool: web::Data<PgPool>,
path: web::Path<i32>,
) -> Result<HttpResponse, ApiError> {
let user_id = path.into_inner();
let user = sqlx::query_as!(
User,
"SELECT id, email, name, created_at, updated_at FROM users WHERE id = $1",
user_id
)
.fetch_optional(pool.get_ref())
.await?
.ok_or(ApiError::NotFound)?;
Ok(HttpResponse::Ok().json(user))
}
```
## Error Handling
```rust
// src/error.rs
use actix_web::{HttpResponse, ResponseError};
use std::fmt;
#[derive(Debug)]
pub enum ApiError {
NotFound,
BadRequest(String),
InternalError,
Unauthorized,
DatabaseError(sqlx::Error),
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ApiError::NotFound => write!(f, "Resource not found"),
ApiError::BadRequest(msg) => write!(f, "Bad request: {}", msg),
ApiError::InternalError => write!(f, "Internal server error"),
ApiError::Unauthorized => write!(f, "Unauthorized"),
ApiError::DatabaseError(e) => write!(f, "Database error: {}", e),
}
}
}
impl ResponseError for ApiError {
fn error_response(&self) -> HttpResponse {
match self {
ApiError::NotFound => HttpResponse::NotFound().json(json!({"error": "Not found"})),
ApiError::BadRequest(msg) => HttpResponse::BadRequest().json(json!({"error": msg})),
ApiError::InternalError => HttpResponse::InternalServerError().json(json!({"error": "Internal error"})),
ApiError::Unauthorized => HttpResponse::Unauthorized().json(json!({"error": "Unauthorized"})),
ApiError::DatabaseError(_) => HttpResponse::InternalServerError().json(json!({"error": "Database error"})),
}
}
}
impl From<sqlx::Error> for ApiError {
fn from(error: sqlx::Error) -> Self {
ApiError::DatabaseError(error)
}
}
```
## Middleware
```rust
// src/middleware/auth.rs
use actix_web::{dev::ServiceRequest, Error, HttpMessage};
use actix_web_httpauth::extractors::bearer::BearerAuth;
pub async fn validator(
req: ServiceRequest,
credentials: BearerAuth,
) -> Result<ServiceRequest, (Error, ServiceRequest)> {
let token = credentials.token();
match validate_token(token).await {
Ok(claims) => {
req.extensions_mut().insert(claims);
Ok(req)
}
Err(_) => Err((ApiError::Unauthorized.into(), req)),
}
}
```
## Best Practices
- Use async/await for non-blocking I/O
- Implement proper error handling with custom types
- Apply connection pooling for databases
- Use extractors for request parsing
- Add middleware for cross-cutting concerns
- Profile with cargo flamegraph
Google Antigravity IDE provides Rust web patterns and automatically suggests performance optimizations for your Actix applications.This Rust prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their rust implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Rust projects, consider mentioning your framework version, coding style, and any specific libraries you're using.