How to call a rest endpoint using only Java?
Java has some excellent frameworks to help us to create a REST call, for instance RestTemplate and WebClient, both from Spring framework and Resteasy used by Quarkus.
But the focus of this article is to forget the frameworks and focus in the Java language. By the way, ChatGPT helped me with some questions :)
1. What is REST?
REST is an acronym for REpresentational State Transfer and an architectural style for distributed hypermedia systems. Roy Fielding first presented it in 2000 in his famous dissertation. (https://restfulapi.net/)
The key abstraction of information in REST is a resource. Any information that we can name can be a resource. For example, a REST resource can be a document or image, a temporal service, a collection of other resources, or a non-virtual object (e.g., a person). (https://restfulapi.net/)
Let’s dive into the CRUD (Create/Read/Update and Delete) operations for a resource, using the https://jsonplaceholder.typicode.com/ to interact with.
2.1. POST
In this example, the json variable contains the data that you want to send in the request body. The Content-Type header is set to application/json to indicate that the request body is in JSON format. The POST method is used to set the request method to POST, and the ofString method is used to set the request body publisher to the JSON string. (Open AI)
2.2. GET
This get call is an idempotent call, ie, should return the same result unless the resource has been updated in the meantime.
2.3. PUT
In this example, the json variable contains the data that you want to send in the request body. The Content-Type header is set to application/json to indicate that the request body is in JSON format. The PUT method is used to set the request method to PUT, and the ofString method is used to set the request body publisher to the JSON string. The uri is set to the endpoint you want to update. (Open AI)
Be aware that some servers may return a response body for PUT requests, so you should check the response code and handle it accordingly. (Open AI)
2.4. DELETE
In this example, the DELETE method is used to set the request method to DELETE, and uri is set to the endpoint you want to delete from.
You can also use other libraries for making HTTP request like Apache HttpComponents or Spring RestTemplate.
Be aware that some servers may return a response body for DELETE requests, so you should check the response code and handle it accordingly. (Open AI)
3. Tech
OpenJDK 11