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 https://restful-booker.herokuapp.com/auth
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:
@JsonProperty
private String username;
@JsonProperty
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.
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()
.body(authPayload)
.contentType("application/json")
.post("https://restful-booker.herokuapp.com/auth");
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!
Comments