Slack Webhook Message from Spring Boot

Upasana | September 13, 2020 | 2 min read | 0 views


In this tutorial we will learn how to send slack messages using webhook from a Spring Boot 2 application.

Gradle setup

We will create a Spring Boot 2 project with the following Gradle configuration.

build.gradle
plugins {
    id 'org.springframework.boot' version '2.3.3.RELEASE'
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'
    id 'java'
}

group = 'com.carvia'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    testImplementation 'io.projectreactor:reactor-test'
}

test {
    useJUnitPlatform()
}

Slack Setup

You need to create a slack app and create a webhook credentials, we need the webhook URL to proceed with the rest of example.

Calling Slack Webhook API

Slack WebHook needs the following payload:

SlackPayload.java
public class SlackPayload {
    private String text;

    //Getter, Setter and Constructor left for brevity
}

Now we will use RestTemplate (or WebClient preferably) for calling the webhook endpoint with required payload:

SlackClient.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;

@Component
public class SlackClient {

    private final WebClient webClient;
    private final RestTemplate restTemplate;

    @Autowired
    public SlackClient(WebClient.Builder webClientBuilder, RestTemplateBuilder restTemplateBuilder) {
        this.webClient = webClientBuilder.build();
        this.restTemplate = restTemplateBuilder.build();
    }

    public String sendMessage(String text) {
        return webClient.post()
                .uri("https://hooks.slack.com/services/aaa/bbb/ccc")
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(new SlackPayload(text))
                .retrieve()
                .bodyToMono(String.class)
                .block();
    }

    public String sendMessageOld(String text) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
    //        JsonObject obj = new JsonObject();
    //        obj.addProperty("text", text);
        SlackPayload payload = new SlackPayload(text);
        HttpEntity<SlackPayload> request = new HttpEntity<>(payload, headers);
        final ResponseEntity<String> entity = restTemplate.exchange("https://hooks.slack.com/services/aaa/bbb/ccc", HttpMethod.POST, request, String.class);
        if(entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        }
        return null;
    }
}

That’s all for now.


Top articles in this category:
  1. Dialoglfow fulfillment with Spring Boot
  2. Testing web layer in Spring Boot using WebMvcTest
  3. Spring Boot 2.0 Reactive Web Performance Metrics
  4. Sendgrid Dynamic Templates with Spring Boot
  5. SendGrid emails in Spring Boot
  6. Basic Auth Security in Spring Boot 2
  7. Redis rate limiter in Spring Boot

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.