Slack Webhook Message from Spring Boot

Carvia Tech | 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 Webhook API with Spring Boot
  2. SendGrid emails in Spring Boot
  3. Sendgrid Dynamic Templates with Spring Boot
  4. Basic Auth Security in Spring Boot 2
  5. Redis rate limiter in Spring Boot
  6. Setting a Random Port in Spring Boot Application at startup
  7. Feign RequestInterceptor in Spring Boot


Find more on this topic:
Spring Framework image
Spring Framework

Spring Framework - MVC, Dependency Injection, Spring Hibernate, Spring Data JPA, Spring Boot and Spring Cloud for Microservices Architecture.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info