TIL: Making Rest Calls with Spring
I got curious today about how you’d go about making rest calls from within a java Spring application. Did some research and found that restTemplate was a thing and generally how you handle your external rest requests from within the application.
I just spent some time tonight going over a few different ways of how you can make these calls and trying to understand what each of the methods gets you.
There’s a set of different request methods available, as outlined in the oficial docs. For my case I wanted to start basic with just a simple get request and see what I could do with it.
My initial searches brought me to using the
getForObject method. After reading up on it more, I found that this could be used if you’re looking to to mapping back to any type of object. So let’s say that you’ve got some time of POJO that you want to map the received payload to. You could tell it to be of that type and create a new object with the returned data that way. OR, you can just set it to return back as a simple string and you’ll just have the string response available to do what you want with.
Here’s what that ended up looking like for me:
But this wasn’t really what I wanted. I wanted to be able to verify stuff like the received headers and response code in addition to the response body. And so more searching led me to find the
getForEntity method. This actually returns back a
ResponseEntity object, which contains all of that stuff within in (status codes, response body, etc).
And here’s what that ended up looking like:
Full test file:
After I had gotten through all of this I started to wonder: So that’s great and all, but is this all synchronous or is it asynchronous?
And it turns out it’s all synchronous. In order for you to make your calls asynchronously, you have to put in quite a bit of extra leg work. I found this stack overflow response which does a pretty good job of outlining how it can be done. But then my problem becomes a matter of how do you then consume this? Since the rest of the java code is going to be blocked waiting for the response, does it really matter? Would you spin up extra threads to make this request? I really don’t know. It’s so different from what I’m used to.
Anyways, tomorrow’s goal is going to be exploring how to consume the JSON response data that comes back from the requests. I already played around with it some today but I don’t want to spend too much more time writing tonight.