Fork us on GitHub

Terse REST API

The other feature that slipped under the radar
Terse REST API

Terse REST API

When discussing the features Chen slipped in just in the last minute of 3.7 I mentioned there were two such features but only discussed the desktop skin. The second one is a more terse/logical API for calling REST web services using the builder pattern.

I actually discussed this briefly in the how do i video for networking & web services near the end. But that’s one of those details that might have easily been missed in that video…​

Easy Approach to Rest

The important class of note is Rest. You can use it to define the HTTP method and start building based on that. So if I want to get a parsed JSON result from a URL I could do:

Map<String, Object> jsonData = Rest.get(myUrl).getAsJsonMap();

For a lot of REST requests this will fail because we need to add an HTTP header indicating that we accept JSON results. We have a special case support for that:

Map<String, Object> jsonData = Rest.get(myUrl).acceptJson().getAsJsonMap();

We can also do POST requests just as easily:

Map<String, Object> jsonData = Rest.post(myUrl).body(bodyValueAsString).getAsJsonMap();

Notice the usage of post and the body builder method. There are MANY methods in the builder class that cover pretty much everything you would expect and then some when it comes to the needs of rest services.

I changed the code in the kitchen sink webservice sample to use this API. I was able to make it shorter and more readable without sacrificing anything.

Future

There is a lot of additional work that we can put into this API and we’ll invest the time based on interest from you. It has an async API too which I didn’t mention because I think it needs some additional work and there are probably good ways to better map this into properties to make the code more fluent and easy.

Share this Post:

Posted by Shai Almog

Shai is the co-founder of Codename One. He's been a professional programmer for over 25 years. During that time he has worked with dozens of companies including Sun Microsystems.
For more follow Shai on Twitter & github.