Getting Started with Axum: A Rust Web Framework

·

axum is a web application framework that focuses on ergonomics and modularity.

Axum is one of the best framework web server framework for rust language. If you are familiar with express nodejs, this will be like home for you. Axum focus on ergonomics and modularity. In my opinion, this is low level abstraction to create web application framework.

Get started

Let see how to use axum as basic web application, this is example axum code from their repository. Create web application by create new the Router.

Rust
#[tokio::main]
async fn main() {
    // initialize tracing
    tracing_subscriber::fmt::init();

    // build our application with a route
    let app = Router::new()
        // `GET /` goes to `root`
        .route("/", get(root))
        // `POST /users` goes to `create_user`
        .route("/users", post(create_user));

    // run our app with hyper, listening globally on port 3000
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Each route have function service, and below example service for those router. Axum will automatically add Content-type based of type response function.

Rust
// basic handler that responds with a static string
async fn root() -> &'static str {
    "Hello, World!"
}

async fn create_user(
    // this argument tells axum to parse the request body
    // as JSON into a `CreateUser` type
    Json(payload): Json<CreateUser>,
) -> (StatusCode, Json<User>) {
    // insert your application logic here
    let user = User {
        id: 1337,
        username: payload.username,
    };

    // this will be converted into a JSON response
    // with a status code of `201 Created`
    (StatusCode::CREATED, Json(user))
}

We can create web application just one file, but it will be tidious if more services added. We need to split those code into several file and folder.

Shared State

Usually web application live long enough with other service, for example database. Other service will use database single connection to communicate to database. Axum offer an API called Sharing State to share state across services. This is example of how to share state in axum.

Rust
use axum::{
    extract::State,
    routing::get,
    Router,
};
use std::sync::Arc;

struct AppState {
    // ...
}

let shared_state = Arc::new(AppState { /* ... */ });

let app = Router::new()
    .route("/", get(handler))
    .with_state(shared_state);

async fn handler(
    State(state): State<Arc<AppState>>,
) {
    // ...
}

By doing this, you can create a big struct to share state across services.

Folder Structure

Axum have no standard folder structure to manage big project, so I create one for easy to get started. I will split the code by their purposes, for example routes, database, and shared state. So, this is my folder structure to get started axum Web Application.

ShellScript
.
├── Cargo.lock
├── Cargo.toml
└── src
    ├── app.rs
    ├── database.rs
    ├── main.rs
    ├── routes
       ├── about.rs
       ├── root.rs
       └── users.rs
    ├── routes.rs
    └── state.rs

I got inspiration from laravel and ruby on rails. Splitting those file require understanding of how module work in rust, you can read more at Rust documentation.

file: app.rs

App file will be used as starting point of application, for example Axum router, listen port service, database connection.

file: database.rs

database.rs only contain database service, manage connection like start and close the connection. It’s not limited to spesific database like SQL or no-SQL. All kind of database are stored here.

Routes

routes.rs is starting point for all routes, and routes folder to store other services.

States

States is important to make all route services using the same states. My example is using database connection, you need to know how Arc Works before create shared states because it’s core feature Rust offer to make safety-memory.

Example Repository

Axum example repository

It’s tidious and more content I need to write to cover them up, so I create example axum folder structure at this repository for you. Hopeful this could help you to understand how axum works.

Conclusion

Axum is web application framework for Rust programming language. Basic function of web application are covered by axum, like handle request, middleware, and state. We can create big project from this starting point. I have create example of project structure to understand how axum and module-rust works, please visit my repository. Thank you for your reading!

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Discover more from Rio Chandra Notes

    Subscribe now to keep reading and get access to the full archive.

    Continue reading