APIs and HTTP Client: POST Call
I this article, we will call the POST API request using the HTTP Client java library.
Here are the Rest APIs which we will be using for the POST call
👇 Make sure you check out the GET call using HTTP Client if you haven’t 👇
The payload we will be sending along with the request:
{
"name": "morpheus",
"job": "leader"
}
Automating POST API request in the Rest Client class 📄
Let’s open the Rest Client class to create the POST call method
We need to pass the endpoint URL, JSON payload, and Headers in the form of an argument.
public void post(String url, String entityString, HashMap<String, String> headerMap)
{}
Now, similar to the GET call, we will initialize the HTTP Client in the method.
public void post(String url, String entityString, HashMap<String, String> headerMap) {CloseableHttpClient httpClient = HttpClients.createDefault();}
Create an object for the HTTP POST class.
public void post(String url, String entityString, HashMap<String, String> headerMap) {CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);}
Now, to pass the payload, we will use the set Entity method.
public void post(String url, String entityString, HashMap<String, String> headerMap) throws UnsupportedEncodingException {CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);httpPost.setEntity(new StringEntity(entityString));}
Note: Make sure to add throws declaration for the Entity method
We will now pass the headers like how we did in the GET call request
public void post(String url, String entityString, HashMap<String, String> headerMap) throws UnsupportedEncodingException {CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);httpPost.setEntity(new StringEntity(entityString));// headers
for (Map.Entry<String, String> entry : headerMap.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());}}
Let’s hit the URL using the execute method and store the response in the Closeable HTTP Response object.
public CloseableHttpResponse post(String url, String entityString, HashMap<String, String> headerMap) throws ClientProtocolException, IOException {CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url); // post requesthttpPost.setEntity(new StringEntity(entityString)); // payload// headers
for (Map.Entry<String, String> entry : headerMap.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());}CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost); // hit the urlreturn closeableHttpResponse;}
Creating the first Test case for POST call
We will create one POST Test class under the Tests package 📦
We will inherit the Test Base class using extends keyword to use all its functions.
package Tests;import base.TestBase;public class PostAPITest extends TestBase {}
We will define one Setup method to call the constructor of the Base class (TestBase.java) and to fetch the endpoint URL
public class PostAPITest extends TestBase{TestBase testBase;
String mainURL;
String apiURL;
String URL;
RestClient restClient;
CloseableHttpResponse closeableHttpResponse;@BeforeMethod
public void setUp() {testBase = new TestBase();mainURL = prop.getProperty("URL");apiURL = prop.getProperty("serviceURL");URL = mainURL + apiURL;}}
Let’s create the Test case and object of the Rest Client class to call the post method.
@Test
public void postAPITest()
{
restClient = new RestClient();
}
We will pass the headers using the HashMap object.
@Test
public void postAPITest() {restClient = new RestClient();HashMap<String, String> headerMap = new HashMap<String, String>();headerMap.put("Content-Type", "application/json");}
To prepare the payload, we need to create one Users class under the data package 📦
And, we will define the attributes based on the payload we need to send and the response we will get
package data;public class Users {private String name;
private String job;
private String id;
private String createdAt;public Users() {}public Users(String name, String job) {this.name = name;this.job = job;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getJob() {return job;}public void setJob(String job) {this.job = job;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getCreatedAt() {return createdAt;}public void setCreatedAt(String createdAt) {this.createdAt = createdAt;}}
Note: This is famously called POJO classes(Plain Old Java Object) for converting an object into JSON and vice versa
We need to define one Jackson dependency in the pom.xml file to convert the java object class(Users.java) into the JSON payload, aka Marshalling
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.4</version>
</dependency>
Once you paste it inside the pom.xml file and if you don’t see the relevant jars under the Maven dependencies
Make sure you go to the Project option and click on clean
And, clean it
Note: After the cleaning is done, you will see all the relevant jars which you’ve defined in the pom.xml file under Maven Dependencies.
Now, go back to the Test class and create one object of the Mapper class.
@Test
public void postAPITest() {restClient = new RestClient();HashMap<String, String> headerMap = new HashMap<String, String>();headerMap.put("Content-Type", "application/json");//Jackson API:
ObjectMapper mapper = new ObjectMapper();}
And, one object of the User class, pass the name and the job argument.
@Test
public void postAPITest() {restClient = new RestClient();HashMap<String, String> headerMap = new HashMap<String, String>();headerMap.put("Content-Type", "application/json");//Jackson API:
ObjectMapper mapper = new ObjectMapper();Users users = new Users("morpheus", "leader");}
Implementing Marshalling concept
We will convert the Users object to one JSON file
@Testpublic void postAPITest() {restClient = new RestClient();HashMap<String, String> headerMap = new HashMap<String, String>();headerMap.put("Content-Type", "application/json");//Jackson API:
ObjectMapper mapper = new ObjectMapper();Users users = new Users();//Obj to Json file:
mapper.writeValue(new File(""), users);}
We will create one Java class to store the JSON output.
Get the path of this file and provide it in the File class
Copy and paste the path inside the mapper object File
@Test
public void postAPITest() throws JsonGenerationException, JsonMappingException, IOException {restClient = new RestClient();HashMap<String, String> headerMap = new HashMap<String, String>();headerMap.put("Content-Type", "application/json");//Jackson API:
ObjectMapper mapper = new ObjectMapper();Users users = new Users();//Obj to Json file:mapper.writeValue(new File("C:\\Users\\prem.rathore\\eclipse-workspace\\HTTPClient\\src\\main\\java\\data\\users.json"), users);}
Note: After the file path, you need to give the Users class object in place of value
Let’s run the Test and see if the conversion is happening or not in the users.json file
{"name":"morpheus","job":"leader"}
Awesome!
Here is the Git repo for you to download the code.
Thanks for reading.
Declaration: This article is based on one of the videos by Naveen AutomationLabs and, the video link is below.
https://www.youtube.com/watch?v=kV8UKPh-HBM&list=PLFGoYjJG_fqp891lruz5fCRPWsDtEXJky&index=7