Writing key values from Java to Consul

How to write key values to Consul

In the first example we are going to use the HTTP API directly, in the second one we are going to use the Java Consul API ecwid. On Github you’ll find all the examples. So, let’s start.

In this example we store the value „buon giorno“ with the key „message“. And all you have to do is a REST PUT operation with v1/kv as a path. Here, Consul is reachable at That’s it.

var value = "buon giorno";
var keyValuePath = "/config/consul-example/greetings/message";
var resourceUrl = "" + keyValuePath;

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI(resourceUrl))

  .send(request, HttpResponse.BodyHandlers.ofString());

Java Consul API
The library is quite easy. First you have to create a ConsulClient with an URL. You use that ConsulClient for reading and writing. It’s just set* (with key and value) and get* methods. With the getKVValue() you get a Response<GetValue> instance. And for the real value you have to call getDecodedValue(). 🙂

ConsulClient consulClient = new ConsulClient("");

consulClient.setKVValue("/config/blueprint/greetings/note", "hello");

Response<GetValue> response = consulClient.getKVValue("/config/blueprint/greetings/note");

System.out.println("value: " + response.getValue().getDecodedValue());