About this lesson
REST Assured: POST a JSON request body and validate what the server accepted
Learn REST AssuredIntermediatePOST Requests
How it works
Many APIs have an endpoint whose only job is to check a payload: it reads the JSON you send, applies its rules and tells you whether the input passed. The testkru /validate/json endpoint works that way. It wants a non-empty name and an email in a valid address format, and on success it answers 200 with a top-level boolean valid plus a data object that repeats your payload, including any extra fields you added.
Two REST Assured details decide whether the server even sees your JSON. First, body() with a String sends that text exactly as written, so the quotes must be escaped inside the Java literal. Second, the request needs a JSON content type. Without contentType(ContentType.JSON), REST Assured labels a String body as text/plain with an ISO-8859-1 charset, the server finds no JSON to parse and replies 400 with a plain error message instead of a valid flag.
Reading the answer is a JsonPath job. getBoolean("valid") gives a Java boolean, and dotted paths such as data.name walk into the nested object. If you prefer to assert rather than read, then().body("valid", equalTo(true)) checks the same field with a Hamcrest matcher.
About the assignment
Send a correct name and email to the validation endpoint, confirm the server accepted them, and print the flag and the two values it echoed back inside data.
What you will do
- Start from
given(), set the content type toContentType.JSONand pass the Alice payload from the starter comment tobody(). - Call
post()with the/validate/jsonpath and keep theResponse. - Assert the result through
then(): status 200, andvalidequal totrue. - Print three labelled lines,
Valid:,Name:andEmail:, readingvalidwithgetBoolean()and the nesteddata.nameanddata.emailwithgetString().
Common mistakes
Leaving out the content type
The request still goes out, but as plain text. The endpoint answers 400 with an
errorfield and novalidkey, andgetBoolean("valid")then throws aNullPointerExceptionbecause there is no value to unbox.Reading name at the top level
The echoed values sit under
data. A path of plainnamefinds nothing at the root andgetString()returnsnull, so the label prints with null after it.Testing only the happy path
An email such as
not-an-emailpasses the empty check but fails the format rule, giving 400 and one entry inerrors. A validation endpoint deserves at least one negative case, and the next lesson sends one.
In a real test suite
Real suites usually keep payloads out of string literals: a Map or a POJO passed to body() is serialised for you, which avoids escaping errors. The response check stays the same, often combined into one then() chain with statusCode() and several body() assertions.
Related lessons
- Handle Validation ErrorsSends a broken payload to the same endpoint and walks the
errorsarray. - Echo Request BodyPOSTs JSON to
/echoand reads back the fields the server returns unchanged. - Send POJO as Request BodyReplaces the hand-written JSON string with a POJO that REST Assured serialises.
To try one of these calls on any API endpoint without a task, open the Online Selenium Java Compiler (REST Assured is included).
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class Main {
public static void main(String[] args) {
RestAssured.baseURI = "https://testkru.com/api";
// TODO: POST to /validate/json with body: {"name": "Alice", "email": "alice@test.com"}
// TODO: Validate status 200
// TODO: Print valid, data.name, and data.email
}
}