» Rust: Build a REST API with Rocket » 2. Development » 2.2 Health Endpoint

Health Endpoint

A health endpoint refers to a specific endpoint or route provided by the server that is used to determine the health or status of the server or application. This endpoint is typically used for monitoring and management purposes, allowing external systems or monitoring tools to check whether the API server is functioning properly.

Modify src/main.rs:

@@ -3,9 +3,11 @@ extern crate rocket;
 
 use rocket::response::content;
 
-#[get("/ping")]
+// Define a health endpoint handler, use `/health` or `/`
+#[get("/")]
 fn ping() -> content::RawJson<&'static str> {
-    content::RawJson("{\"message\": \"pong\"}")
+    // Return a simple response indicating the server is healthy
+    content::RawJson("{\"status\":\"ok\"}")
 }
 
 #[launch]

The response of endpoint /:

{"status":"ok"}

Optional:
If you want to include CPU or memory data in the health endpoint response, you would need to gather this information from the system where your Rust application is running.

[Optional] CPU and Memory usage

Add sysinfo dependency:

cargo add sysinfo

Modify src/main.rs [optional]:

@@ -2,12 +2,27 @@
 extern crate rocket;
 
 use rocket::response::content;
+use sysinfo::System;
 
 // Define a health endpoint handler, use `/health` or `/`
 #[get("/")]
-fn ping() -> content::RawJson<&'static str> {
-    // Return a simple response indicating the server is healthy
-    content::RawJson("{\"status\":\"ok\"}")
+fn ping() -> content::RawJson<String> {
+    let mut sys = System::new_all();
+    sys.refresh_all();
+    // sys.refresh_cpu();
+
+    let result_json = format!(
+        r#"{{
+    "cpu": "{:.2}%",
+    "used_memory": "{:.2} MB",
+    "total_memory": "{:.2} MB",
+    "status": "ok"
+}}"#,
+        sys.global_cpu_info().cpu_usage(),
+        sys.used_memory() as f32 / 1024.0 / 1024.0,
+        sys.total_memory() as f32 / 1024.0 / 1024.0
+    );
+    content::RawJson(result_json)
 }
 
 #[launch]

r# is a prefix that allows you to create raw string literals. Raw string literals are useful when you need to include special characters, escape sequences, or multiple lines in your string without needing to escape them.

The response is something like this:

{
    "cpu": "70.83%",
    "used_memory": "10655.54 MB",
    "total_memory": "16384.00 MB",
    "status": "ok"
}
PrevNext