Before you build web applications with Actix Web, you'll need to set up a Rust development environment. If you need to, follow the official Rust installation instructions at https://www.rust-lang.org/learn/get-started.
Once Rust is installed, you can create a new Rust project and add Actix web as a dependency in your Cargo.toml
file:
[dependencies]
actix-web = "4.4.0"
Now, let's create a simple Actix web application step by step.
Creating a Basic Actix Web Application
Create a new Rust project with the following command:
cargo new actix_web_demo
cd actix_web_demo
Next, open your project's Cargo.toml
file and add Actix web as a dependency, as mentioned earlier. Then, your Cargo.toml
should look like this:
[dependencies]
actix-web = "4.4.0"
Creating the Application Entry Point
In Rust, the entry point of your application is the main
function. Create a main.rs
file in your project's root directory and define the main
function:
use actix_web::{get, App, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
"Hello, Actix web!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().service(hello)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
In this code:
We import necessary items from Actix web.
We define a simple asynchronous function
hello
that responds with the string "Hello, Actix web!" when the root URL ("/") is accessed.We create the
main
function which sets up an Actix web server. It usesHttpServer::new
to configure the server andApp::new
to create an application with thehello
route.Finally, we bind the server to the address "127.0.0.1:8080" and run it asynchronously.
Running the Application
To run your Actix web application, use the following command from your project's root directory:
cargo run
This will start the Actix web server, and you'll see an output indicating that the server is running on 127.0.0.1:8080
.
Accessing the Application
Open your web browser and navigate to http://localhost:8080. You should see the message "Hello, Actix web!" displayed in your browser. Alternatively, you can use the cURL
tool to access the route from the terminal:
Congratulations! You've created a basic Actix web application.