To install Rust on Amazon Linux in 2023, you can follow these general steps. Note that these instructions should work for most recent versions of Amazon Linux, but be sure to check any specific requirements or updates that might apply to your version.
Update Your System: First, make sure your system is up-to-date.
sudo dnf update -y
sudo dnf groupinstall "Development Tools" -y
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
rustc --version
Creating a REST API in Rust Using Actix-Web
Rust, known for its safety and performance, is increasingly becoming a go-to language for web development. In this blog post, we will walk through creating a basic REST API in Rust using Actix-Web, a powerful and fast web framework. This guide is perfect for those who are familiar with Rust basics and are interested in web development.
Create a new project using Cargo, Rust’s package manager:
cargo new rust_rest_api
cd rust_rest_api
Adding Dependencies
Your Cargo.toml
needs to be updated to include Actix-Web and other dependencies. Here’s what you should add:
[dependencies]
actix-web = "4"
actix-rt = "2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Writing the API Code
Replace the src/main.rs
content with the following code:
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct MyObject {
name: String,
number: i32,
}
async fn index() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
async fn echo(obj: web::Json<MyObject>) -> impl Responder {
HttpResponse::Ok().json(obj.into_inner())
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/", web::get().to(index))
.route("/echo", web::post().to(echo))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
Running the API
Run your project:
cargo run
The API will start on localhost:8080
.
Now you can install nginx and port forward port 8080 to 80. An example is given here.
Conclusion
Rust, combined with Actix-Web, provides a robust platform for building efficient and safe web applications. This guide serves as a starting point for your journey into Rust-based web development. As you expand your API, explore the rich ecosystem of Rust for more features and tools.