Not A Mzter


Rust - Axum Identity API Chapter : 1

In this chapter we are going to create from zero a Rust Axum API with a health checker

Create a new project and install dependencies

 

  1. Create a new project
command to create new project
cargo new axum_api
  1. Enter to your project directory and add needed crates
command to add crate libraries with some needed features
cargo cargo add tokio tokio-util serde serde_json axum axum-extra chrono -F tokio/full -F axum/tokio -F axum-extra/typed-header -F chrono/serde -F serde/derive  -F tokio-util/compat
  1. In your main.rs file add the following code
src/main.rs
mod route;
mod api_handler;
 
use crate::route::create_router;
 
#[tokio::main]
async fn main() {
    // Get app_router
    let app = create_router();
    // Read the port from env or use the port default port(3000)
    let port = std::env::var("PORT").unwrap_or(String::from("3000"));
    let listener = tokio::net::TcpListener::bind(&format!("0.0.0.0:{}", port))
        .await
        .unwrap();
    println!("Running server on {}", &format!("0.0.0.0:{}", port));
    // Run server
    axum::serve(listener, app).await.unwrap();
}
  1. Create a route.rs file with your routes, this file will be used to create all endpoints
use axum::{routing::get, Router};
 
use crate::api_handler::health_checker;
 
pub fn create_router() -> Router {
    Router::new().route("/health", get(health_checker))
}
  1. Create api_handler.rs file with function that returns info for specific routes. We are going to create health_checker function that returns StatusCode 202
src/api_handler.rs
use axum::http::StatusCode;
 
pub async fn health_checker() -> StatusCode {
    StatusCode::OK
}
  1. Run with cargo run dev and make an http request to http://localhost:3000/health and you will get a 200 status code