ARTICLE AD BOX
Introduction
In this tutorial, you’ll study really to build a web server pinch Rust and nan Actix-web exemplary connected a DigitalOcean Droplet. You’ll group up a basal server and create routes to negociate a elemental database of Todo items, supporting communal RESTful operations for illustration retrieving and creating Todos.
Prerequisites
Before you begin, guarantee you personification nan following:
- A DigitalOcean Cloud relationship to rotation up a Droplet.
- An Ubuntu Droplet up and running.
- Rust installed connected nan Droplet.
- Familiarity pinch Rust basics, including variables, functions, and traits.
Step 1 - Setting up nan Ubuntu Droplet
-
SSH into your DigitalOcean Droplet: Open your terminal and usage nan pursuing bid to SSH into your Droplet. Replace your_username pinch your existent username and your_droplet_ip pinch nan IP reside of your Droplet:
ssh your_username@your_droplet_ip -
Update nan package list: Once logged in, update nan package database to guarantee you personification nan latest accusation connected disposable packages:
sudo apt update -
Install Rust: To instal Rust, usage nan pursuing command, which downloads and runs nan Rust installation script:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shFollow nan on-screen instructions to complete nan installation. After installation, you whitethorn petition to restart your terminal aliases run:
source $HOME/.cargo/env -
Install basal libraries: Install nan required libraries for building Rust applications. You tin instal build-essential and libssl-dev using:
sudo apt install build-essential libssl-dev -
Verify Rust installation: To corroborate that Rust has been installed correctly, cheque nan version:
rustc --version -
Install Cargo (Rust package manager): Cargo is installed automatically pinch Rust. You tin verify its installation by checking nan version:
cargo --version
Step 2 - Setting Up nan Project
Let’s create a caller rust task sammy_todos utilizing cargo
cargo caller sammy_todos
Next, find nan Cargo.toml file. Navigate to nan guidelines directory of your Rust project. The Cargo.toml grounds is located successful nan aforesaid directory wherever you created your task (e.g., sammy_todos). You tin usage nan pursuing bid to alteration to your task directory:
cd sammy_todos/ ls
Below are nan Rust task files files which are automatically generated:
Output
Cargo.toml src
Add actix-web and serde arsenic limitations successful Cargo.toml. Here, serde is needed for Serialization and Deserialization.
vi Cargo.toml
And adhd nan pursuing lines nether nan dependencies.
[dependencies] actix-web = "4.0" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0"
Now to download and compile limitations usage nan beneath command:
cargo build
Step 3 - Creating a Basic Server
In main.rs, adhd nan pursuing lines of codification to group up a basal server. You must navigate to nan src directory incorrect your Project.
main.rs
use actix_web::{get, App, HttpServer, HttpResponse, Responder,web}; #[get("/")] async fn index() -> impl Responder { HttpResponse::Ok().body("Welcome to nan Sammy Todo API!") } #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .service(index) }) .bind("127.0.0.1:8080")? .run() .await }
Run nan server:
cargo run
To proceedings nan server, unfastened a caller terminal normal and tally nan pursuing command:
curl http://127.0.0.1:8080
You should get nan pursuing response:
Output
Welcome to nan Sammy Todo API!
Step 4 - Adding a Todo Model
Todo exemplary is needed to serialize and deserialize nan petition and response. Add nan pursuing lines of codification incorrect nan main.rs file.
main.rs
use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] struct Todo { id: i32, title: String, completed: bool, }
Step 5 - Implement Create todo
This API creates todo, and this is simply a dummy API that returns your todo only, but you tin instrumentality it pinch databases to make it persistent
main.rs
#[get("/todos")] async fn create_todo(todo: web::Json<Todo>) -> impl Responder { HttpResponse::Ok().body(serde_json::to_string(&todo).unwrap()) }
Step 6 - Implement Get todo
This API returns todo by id:
main.rs
#[get("/todos/{id}")] async fn get_todo(id: web::Path<i32>) -> impl Responder { let todo = Todo { id: id.into_inner(), title: "Learn Actix-Web".to_string(), completed: false, }; HttpResponse::Ok().body(serde_json::to_string(&todo).unwrap()) }
Bind nan services pinch our server
This is really nan rust server main.rs would look like:
main.rs
use actix_web::{get, App, HttpServer, HttpResponse, Responder, web}; #[get("/")] async fn index() -> impl Responder { HttpResponse::Ok().body("Welcome to nan Sammy Todo API!") } #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .service(index) .service(get_todo) .service(create_todo) }) .bind("127.0.0.1:8080")? .run() .await } use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] struct Todo { id: i32, title: String, completed: bool, } #[get("/todos")] async fn create_todo(todo: web::Json<Todo>) -> impl Responder { HttpResponse::Ok().body(serde_json::to_string(&todo).unwrap()) } #[get("/todos/{id}")] async fn get_todo(id: web::Path<i32>) -> impl Responder { let todo = Todo { id: id.into_inner(), title: "Learn Actix-Web".to_string(), completed: false, }; HttpResponse::Ok().body(serde_json::to_string(&todo).unwrap()) }
Now, you tin proceedings it by sending a POST petition pinch curl:
curl -X POST -H "Content-Type: application/json" -d '{"title": "Buy groceries"}' http://127.0.0.1:8080/todos
Conclusion
Congratulations! You personification successfully group up a basal web server utilizing Rust and Actix. This tutorial taught you to create endpoints to retrieve and create Todo items, providing a coagulated instauration for building overmuch analyzable applications. To heighten your app further, spot integrating a database solution for accusation persistence, allowing you to shop and negociate your Todo items effectively. Keep exploring, and happy coding!