About this lesson
REST Assured: verify the request body you sent with an echo endpoint
Learn REST AssuredIntermediatePOST Requests
How it works
When a POST misbehaves, the first question is what actually went over the wire. An echo endpoint answers that: it parses the JSON you sent and returns it unchanged. The practice API's /echo replies 200 with the same keys, values and nesting, numbers stay numbers, and null stays null.
The endpoint has rules of its own. It only accepts POST, so a GET receives 405 Method Not Allowed with an Allow header naming POST. It only reads bodies sent as JSON, so a missing content type or malformed JSON both lead to 400 with a message asking for a JSON payload.
About the assignment
You send a two-field JSON document to the echo endpoint and print both fields from the reply, proving that what REST Assured sent is exactly what you wrote.
What you will do
- Build a request with
given()andcontentType()set toContentType.JSON. - Put the two-field JSON from the starter comment in
body(). - Send it with
post()to/echoand keep theResponse. - Read
messageandframeworkwithgetString()and print them after the labels from the task.
Common mistakes
Expecting 201 from the echo
Nothing is created, so the status is 200. A copied
statusCode(201)check from a create test fails here.Forgetting the content type
Without
contentType()the body is sent as plain text and the reply is 400, even though the string itself is valid JSON. The error message spells out the header it needs.Calling it with GET
The route exists only for POST, so
get()returns 405 rather than 404. Read theAllowheader when an endpoint rejects the method.
In a real test suite
Echo services are a debugging aid more than a test target. When a serialised POJO or a Map body is rejected by a real API, sending it to an echo endpoint, or adding log().body() to the request, shows exactly which keys and types were produced.
Related lessons
- Create a User with POSTPOST a four-field user and read values from the created record.
- Echo Request HeadersThe header counterpart: send custom headers and read them echoed back.
- Conditional Request LoggingLog the request details, body included, whenever a check in the chain fails.
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.*;
public class Main {
public static void main(String[] args) {
RestAssured.baseURI = "https://testkru.com/api";
// TODO: POST to /echo with ContentType.JSON
// Body: {"message": "Hello REST Assured", "framework": "REST Assured"}
// TODO: Extract and print "message" and "framework" from the echoed response
}
}