Managing Payload and Response Without Java POJOs in Rest-Assured
For Developers

February 15, 2024

Managing Payload and Response Without Java POJOs in Rest-Assured

For any API test automation project that uses Java and Rest-Assured, I would like to share how I handle payloads and responses.

The most common way to extract response data is to use POJO classes when developing an API test automation project. However, it is not necessary to write POJO classes if you use Rest-Assured (I will call it RA throughout the rest of this article) to test APIs. Instead, you can make use of RA features. Here are some features that RA can use to accomplish this.
As a first step, let’s discuss payloads

Any of the objects in the following list can be used as the payload in RA.

  • String
  • byte[]
  • File
  • InputStream
  • Object

In other words, we have many options to manage the payloads, and I generally follow this method.

First of all, project resources are a good place to store payloads.

1- Getting JSON as the string from the resource

Here is the code I usually use to get the file content as a string. It works seamlessly on Macs, Linux machines, or Windows machines as well

2- JsonPath can be used to update the JSON as desired

Here’s where it gets tricky. Having received the payload as a String the object, how can we update the JSON fields?

The first step is to read the JSON field with a JSON selector(JSON path), and to do so, we need to convert the string payload to a DocumentContext object of com.jayway.jsonpath.

By using com.jayway.jsonpath.JsonPath.read(), we are now able to use JsonPath with the payload as DocumentContext

Since all JSON fields have a type, we need to update the JSON field with the correct object type when updating JSON, and the read() method returns the value as an object as well.

We can deduce the field value’s type based on the object, then update the JSON field to reflect the valid type once we have the object.

In this case, we now have a String representation of the updated JSON.

Let’s try it with a real scenario:

Now that we have created the methods, we will update the JSON above.

The following code illustrates how we can extract the response without creating a POJO class, so we can convert JSON to map objects to use as we see fit.

But what if response is a JSONArray?

Also we can get response field with the desired type:

To access the git repo please have a look at the following link.

In summary, I would like to say don’t be stuck always the same way. Mostly there is a better way to do anything then the others.

Hopefully, this article would help some of you to add more value to your projects.

Moreover, if you're in search of high-pay, long-term job opportunities in the US and UK, platforms like Index.dev can be your gateway. Sign up today to kickstart your journey →