Skip to content

Instantly share code, notes, and snippets.

@irfanbaigse
Created January 23, 2024 11:28
Show Gist options
  • Save irfanbaigse/34ded4361ca88424933de7d695eb9f21 to your computer and use it in GitHub Desktop.
Save irfanbaigse/34ded4361ca88424933de7d695eb9f21 to your computer and use it in GitHub Desktop.
Spring Boot Health Check Api Controller
package com.example.irfan.rest;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/api/health-check", produces = {MediaType.APPLICATION_JSON_VALUE})
public class HealthCheckController {
private final HealthEndpoint healthEndpoint;
public HealthCheckController(HealthEndpoint healthEndpoint) {
this.healthEndpoint = healthEndpoint;
}
@GetMapping(value = "/ping")
public ResponseEntity<String> ping() {
return ResponseEntity.ok("{\"status\":\"OK\"}");
}
@GetMapping(value = {"", "/"})
public ResponseEntity<String> check() {
String health = healthEndpoint.health().getStatus().getCode();
return ResponseEntity.ok("{\"status\":\"" + health + "\"}");
}
}

Endpoint:

/api/health-check

Request:

curl --location 'http://127.0.0.1:8080/api/v1/health-check'

Success Response:

{
   "status": "UP"
}

Error Response:

{
    "status": "DOWN"
}
package com.example.irfan.health;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class ThirdPartyHealthCheck implements HealthIndicator {
@Override
public Health health() {
Map<String, Object> details = new HashMap<>();
details.put("chance", "something");
// return Health.down().withDetails(details).build(); // in case of failure
return Health.up().withDetails(details).build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment