How to call a rest endpoint using only Java?

Luiz Gustavo De O. Costa
3 min readJan 23, 2023

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.

RESTFul API

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

Post code

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

Get code

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

Put code

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

Delete code

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

4. References

https://chat.openai.com/chat#

--

--

Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices