» Rust: Building Full-Text Search API with ElasticSearch » 2. Index Documents » 2.1 Axum Server

Axum Server

Create a package

Run the cargo new command:

cargo new lr_fulltext_search_rust --bin

We’re passing --bin because we’re making a binary program: if we were making a library, we’d pass --lib.

Or, if you want to create a binary Cargo package in an existing directory:

cargo init

This command creates start files, including the Cargo.toml file, where you can list the dependencies you add for tracking.

Add dependencies

Install Axum and Tokio frameworks.

Run the cargo add command:

cargo add axum
cargo add tokio --features full

Or, add axum and tokio frameworks in Cargo.toml:

@@ -6,3 +6,5 @@ edition = "2021"
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
 [dependencies]
+axum = "0.7.5"
+tokio = { version = "1.37.0", features = ["full"] }

Update src/main.rs:

Install serde_json to serialize string literals to json:

cargo add serde_json
use axum::{routing::get, Json, Router};
use serde_json::json;

async fn welcome() -> Json<serde_json::Value> {
    Json(json!({
        "status": "ok"
    }))
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(welcome));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Run the program like this:

cargo run

Output:

Finished dev [unoptimized + debuginfo] target(s) in 0.07s
 Running `target/debug/lr_fulltext_search_rust`

Your server is runnong on port 3000 now.

Try visiting the URL http://localhost:3000/ in your browser or curl. It should display the json:

{
  "status": "ok"
}

Data model: Book

Data models represent the structure of the data that the API deals with.

Install serde for serializing/deserializing:

cargo add serde --features derive

Create src/domain/model/book.rs:

Folder structures like domain/model/... is using 4 Layers Architecture Pattern, read more here.

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Book {
    pub title: String,
    pub author: String,
    pub published_at: String,
    pub content: String,
}

Create a sibling file mod.rs to re-export symbols:

mod book;

pub use book::Book;