Sending an HTTP request payload

Course Home | Code Example

For our final lesson we are going to look at how to add a payload or body to an HTTP request by sending this payload

    "username" : "admin",
    "password" : "password"

In a POST request to the endpoint

Create a POJO

In the previous lesson we looked at Deserialisation which parsed Strings into Java Objects. For this example we can flip the process and convert a Java Object into a String, using (yes you guessed it) serialisation.

We start this by creating a class named AuthPayload and adding the variables and constructor into the class:

private String username;
private String password;

public AuthPayload(String username, String password) {
    this.username = username;
    this.password = password;

Once again the variables match the structure of the JSON we want to send. We have also added a constructor so that we can create an AuthPayload with specific variables to send in our HTTP POST request.

Sending a payload

With our Java class created, let’s use AuthPayload to create a payload with valid credentials and send it via a POST request

AuthPayload authPayload = new AuthPayload("admin", "password123");

Response response = given()

String authResponse = response.getBody().print();

assertThat(authResponse, containsString("token"));

So we begin by calling AuthPayload to create a new Java Object with the values we want to send in the HTTP POST request. Next we call the body() method in Rest-Assured and adding our authPayload object as a parameter. Then we call contentType which is a shortcut method that will add Content-type header to our HTTP request, which is required by the Web API. Finally, we call post() which will send an HTTP POST request with a serialised version of our AuthPayload object. Finally we assert that a token value was returned to confirm the credentials were accepted.

That ends our final lesson. You now know the basics to send GET and POST requests with HTTP headers as well as parse the bodies of HTTP responses. You are now ready to explore Rest-Assured with your APIs. Good luck!

Mark Winteringham's photo

Mark Winteringham


Mark Winteringham is a tester, toolsmith and the Ministry of Testing DojoBoss with over 10 years experience providing testing expertise on award-winning projects across a wide range of technology sectors including BBC, Barclays, UK Government and Thomson Reuters. He is an advocate for modern risk-based testing practices and trains teams in Automation in Testing, Behaviour Driven Development and Exploratory testing techniques. He is also the co-founder of Software Testing Clinic a community raising awareness of careers in testing and improving testing education. You can find him on Twitter @2bittester.