Free public REST API

Real REST API which is ready to handle your HTTP requests 24/7 for free. Can be used for your demo projects, testing, learning or even educating someone else. This REST API supports main HTTP methods such as GET, POST, PUT, DELETE and PATCH.


Send a PUT request in Java


What is a PUT Request?

A PUT request is one of the HTTP methods which is used when you want to update an existing resource.

The request body that you send as part of a PUT request should contain a complete representation of a resource because the PUT request replaces the existing resource and cannot do a partial update of a resource. If you want to do a partial update, you need to use a PATCH request method instead.


1. How to send a PUT request in Java?

1.1. Preparing a request

Imagine that we have an online shop that sells some phones and our website is using REST API to fetch and store some data about the phones. Now also imagine that we sell an iPhone 11 for 389.99 as in the example below but we want to increase the price of it from 389.99 to 400. How can we do it using a PUT request?

{ "id": "4", "name": "Apple iPhone 11, 64GB", "data": { "price": 389.99, "color": "Purple" } }


Let's prepare our PUT request for that. Since a request body of a PUT request should contain a complete representation of a resource, we need to pass the whole resource. In the example below we are passing the whole resource with an updated price attribute as a String which represents a JSON since this REST API accepts a request body of a type of JSON.

String requestBody = "{\"name\": \"Apple iPhone 11, 64GB\", \"data\": {\"price\": 400, \"color\": \"Purple\"}}"; HttpRequest request = HttpRequest.newBuilder() .PUT(HttpRequest.BodyPublishers.ofString(requestBody)) .uri(URI.create("https://api.restful-api.dev/objects/4")) .header("Content-Type", "application/json") .build();


After that, we are creating a request using an HttpRequest class (P.S. Java 11+). As part of this request, we are specifying a request type as PUT. Also, we are passing the request URL of a PUT request where number 4 represents a unique ID of a resource that we want to update (P.S. ID 4 is a reserved ID and is used here only for an example purpose, so if you want to properly update a resource using our REST API, please create your own resource using a POST request first).

In the end, we are specifying the content type of our request body. One important thing is that the Content-Type header should match the content type which the REST API expects to receive as part of your request and your request body should obviously be of the same type as well.


API Dog

1.2. Sending a request

HttpResponse<String> response = HttpClient.newHttpClient() .send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); System.out.println(response.body());


To send a request we can just use the HttpClient class and the send method from it, simply as that. This method returns a response of type HttpResponse. Once the send method is executed, we can use the HttpResponse variable which was created to print the response code and the response body. The response body should contain a complete representation of an updated resource in case if the request was successful.


2. How to send a Java Object as request body?

2.1. Creating an Object

In section 1. we did a decent job and sent a PUT request and yes, it worked but there is one issue with that approach. The issue is that we have constructed the request body manually by creating a String which represents a JSON. This is not very convenient, is it? Most probably you would want to send some real Java Objects which would represent the resource, right? For that, let's start with creating one first.

import java.util.HashMap; public class Product { private String name; private HashMap<String, Object> data; public Product(String name, HashMap<String, Object> data) { this.name = name; this.data = data; } public String getName() { return name; } public void setName(String name) { this.name = name; } public HashMap<String, Object> getData() { return data; } public void setData(HashMap<String, Object> data) { this.data = data; } }


2.2. Jackson library

Since Java Objects are not JSONs but our REST API expects a request body to be of type JSON, we would need to convert our Object to JSON and for that, we are going to use an ObjectMapper class which comes from an external library called Jackson. This is a very popular Java library that is extremely powerful when it comes to any work related to JSON processing and this library needs to be imported, that's why let's add a dependency to our project (P.S. add it in "pom.xml" if you are using Maven or in "build.gradle" if you are using Gradle).

<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.1</version> </dependency>


2.3. Object Mapper

HashMap<String, Object> phoneAttributes = new HashMap<>(); phoneAttributes.put("price", 400); phoneAttributes.put("colour", "Purple"); Product product = new Product("Apple iPhone 11, 64GB", phoneAttributes); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(product);


Now we can simply create a new product using our custom Java Object that represents our resource and we can populate it with the same data to as in section 1.1. If after that we would create an instance of ObjectMapper class and would call a writeValueAsString method where the parameter is our Object, this would convert our Object to a String which represents a JSON. Very simple and is exactly what we need to send a proper PUT request!


3. Putting everything together

import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; public class Main { public static void main(String[] args) throws Exception { HashMap<String, Object> phoneAttributes = new HashMap<>(); phoneAttributes.put("price", 400); phoneAttributes.put("colour", "Purple"); Product product = new Product("Apple iPhone 11, 64GB", phoneAttributes); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(product); HttpRequest request = HttpRequest.newBuilder() .PUT(HttpRequest.BodyPublishers.ofString(requestBody)) .uri(URI.create("https://api.restful-api.dev/objects/4")) .header("Content-Type", "application/json") .build(); HttpResponse<String> response = HttpClient.newHttpClient() .send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); System.out.println(response.body()); } }