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
- Create a new project
cargo new axum_api
- Enter to your project directory and add needed crates
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
- In your main.rs file add the following code
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(); }
- 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)) }
- 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
use axum::http::StatusCode; pub async fn health_checker() -> StatusCode { StatusCode::OK }
- Run with cargo run dev and make an http request to http://localhost:3000/health and you will get a 200 status code