RestAssured getBody after Post Request - java

I'm working on the POST request to get a better understanding of RestAssured on the website https://reqres.in/
#Test
public void postTest() {
Response response = RestAssured.given()
.body("{\"name\": \"morpheus\"}"
+ "{\"job\": \"leader\"}")
.when()
.post(base_URI);
assertEquals(response.statusCode(), 201);
System.out.println(response.asPrettyString());
}
The status code is 201 which is I expected, I want to print out the JSON data that I just POST by using response.asPrettyString()
But the data returned is
{
"id": "302",
"createdAt": "2022-08-23T21:47:44.857Z"
}
instad of
{
"name": "morpheus",
"job": "leader",
"id": "324",
"createdAt": "2022-08-23T21:47:21.176Z"
}
What should I do to get the full JSON data?

Are you sure that isn't the full JSON data? Maybe the issue is your server?
I also noticed an issue in the JSON body. I would assume this is the payload you want to send?
{
"name": "morpheus",
"job": "leader"
}
I don't think there is anything wrong with your test code other than the JSON, but you can get restAssured to log the response payload and do the assertions...
#Test
public void postTest() {
RestAssured.given()
.body("{"
+ "\"name\": \"morpheus\","
+ "\"job\": \"leader\""
+ "}")
.when()
.post(base_URI)
.then().log().body()
.and().assertThat().statusCode(201);
}

The problem is you forgot add content-type=application/json to header. The correct code would be:
Response response = RestAssured.given()
.contentType(ContentType.JSON)
.body("{\n" +
" \"name\": \"morpheus\",\n" +
" \"job\": \"leader\"\n" +
"}")
.when()
.post("https://reqres.in/api/users");
assertEquals(response.statusCode(), 201);
response.prettyPrint();
Result:
{
"name": "morpheus",
"job": "leader",
"id": "257",
"createdAt": "2022-08-24T02:48:40.444Z"
}

Related

2 way ssl using spring boot java

I am new to this concept.
I am using Insomnia for testing my api end points.
I have a .crt file and a .key file added in the collections environment inside insomnia.
when i send in my api, i get a valid response. this is how its code format looks like:
HttpResponse<String> response = Unirest.post("https://covdch-api.cdc.gov/v0/upload/cvrs/batch")
.header("accept", "application/json")
.header("Authorization", "eyJhbGciO")
.header("Content-Type", "text/plain")
.body("VkFYX0VWR")
.asString();
and this is the output i get:
{
"id": "b719a89",
"totalRecords": 1,
"validationErrors": [
],
"validationErrorsCount": 0,
"storageResult": {
"REDACTED_DB": {
"status": "SUCCESS",
"processingErrors": [
],
"processedCount": 0,
"processingErrorsCount": 0
}
}
}
I am trying to use this in my separate spring boot project as a getmapping like this:
#RequestMapping(path = "/validate")
public String hello() throws UnirestException{
HttpResponse<String> response = Unirest.post("https:post-api.com-someexample")
.header("accept", "application/json")
.header("Authorization",
"eyJhbGciOiJIUzU")
.header("Content-Type", "text/plain")
.body("VkFYX0VWRU5")
.asString();
}
ofcourse im not getting the ouptut because I did not configure my .crt file and .key file in the eclipse (which I did inside insmonia).
Probably thats where Im stuck.
Can anyone guide me on how to achieve this?

Adding additional field in Response Object

I am getting below response when I am calling an API.
Response postRequestResponse = ConnectionUtil.getwebTarget()
.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
.path("bots")
.path(ReadSkillID.readSkillId())
.path("dynamicEntities").path(dynamicEntityID)
.path("pushRequests").path(pushRequestID).path(operation)
.request()
.header("Authorization", "Bearer " + ConnectionUtil.getToken())
.get();
Below output I am getting.
{
"createdOn": "2020-08-17T12:19:13.541Z",
"updatedOn": "2020-08-17T12:19:23.421Z",
"id": "C84B058A-C8F9-41F5-A353-EC2CFE7A1BD9",
"status": "TRAINING",
"statusMessage": "Request Pushed into training, on user request"
}
I have to return this output to client with an additional field in the response. How can modify the above response and make it
{
"EntityName": "NewEntity", //New field
"createdOn": "2020-08-17T12:19:13.541Z",
"updatedOn": "2020-08-17T12:19:23.421Z",
"id": "C84B058A-C8F9-41F5-A353-EC2CFE7A1BD9",
"status": "TRAINING",
"statusMessage": "Request Pushed into training, on user request"
}
I am adding this additional field here
"EntityName": "NewEntity"
How can I do that. many things I tried but got exception.
get JSON from postRequestResponse (i have no idea what framework you are using, so you have to figer it out on your own, but the Response datatype will probably have a getResponseBody or similar method returing the JSON)
add EntityName
serialize it again to json.
class YourBean {
#Autowired
private ObjectMapper objectMapper;
public void yourMethod() {
// 1
final InputStream jsonFromResponse = ...
// 2
Map dataFromResponse = objectMapper.readValue(jsonFromResponse, Map.class);
dataFromResponse.put("EntityName", "NewEntity");
// 3
final String enrichedJson = objectMapper.writeValueAsString(dataFromResponse);
}
}
enrichedJson contains EntityName and whatever comes from the API.

okHTTP POST request body with many childs

I am using a charging API from a carrier, and the following JSON format has to be passed with the API call. I am using okHTTP library.
String telNum = "+941234567";
String pbody = "{\"amountTransaction\": {\"clientCorrelator\": \"7659\",\"endUserId\": \"tel:"+telNum+"\",\"paymentAmount\": {\"chargingInformation\": {\"amount\": 1,\"currency\": \"LKR\",\"description\": \"Test Charge\"},\"chargingMetaData\": {\"onBehalfOf\": \"IdeaBiz Test\",\"purchaseCategoryCode\": \"Service\",\"channel\": \"WAP\",\"taxAmount\": \"0\",\"serviceID\": \"theserviceid\"}},\"referenceCode\": \"REF-12345\",\"transactionOperationStatus\": \"Charged\"}}";```
The following is how the JSON needs to be formatted.
{
"amountTransaction": {
"clientCorrelator": "54321",
"endUserId": "tel:+94761234567",
"paymentAmount": {
"chargingInformation": {
"amount": 1,
"currency": "LKR",
"description": "Test Charge"
},
"chargingMetaData": {
"onBehalfOf": "IdeaBiz Test",
"purchaseCategoryCode": "Service",
"channel": "WAP",
"taxAmount": "0",
"serviceID": "null"
}
},
"referenceCode": "REF-12345",
"transactionOperationStatus": "Charged"
}
}
I get Error 400 Bad Request
Try this will format your body according to your need
try {
JSONObject jsonObject = new JSONObject(pbody);
pbody=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
OkHTTP requires RequestBody object for POST, so try this:
RequestBody body = RequestBody.create(MediaType.APPLICATION_JSON, pbody);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();

consume Rest api with two different responses

I am trying to consume api with two different responses. when providing proper input and headers, it gives one json object. That is working fine with code given below.
but when one of the inputs or headers are missing then api is returning other json which states error details while hitting through Postman but same is not getting achieved by client code. It throws exception but api should return json with error details.
first I tried with postForobject(), then changed to exchange() assuming postForObject returning object and api is not getting expected object format. so tried with String.clas instead of particular class
what can be done to get two different json object by hitting same url?
when success:
{
"contacts": [
{
"input": "98########",
"status": "valid"
}
]
}
when input or header missing:
"errors": [
{
"code": 1###,
"title": "Access denied",
"details": "invalid deatils"
}
]
below is my code:
public static void main(String[] args) throws Exception {
RestTemplate restTemplate = new RestTemplate();
String check_Contact_Async = "https://port/contacts/";
sslByPass();
//headers = setHeaders();
contactsDTO = getInput();
final HttpEntity<ContactsDTO> entity = new HttpEntity<ContactsDTO>(contactsDTO, headers);
try {
//WsResponse res = restTemplate.postForObject(check_Contact_Async, entity, WsResponse.class);
ResponseEntity<String> responseEntity = restTemplate.exchange(
check_Contact_Async, HttpMethod.POST, entity,
String.class);
System.out.println(responseEntity);
} catch (Exception exception) {
System.out.println(exception);
}
}
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:667)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:620)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:580)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:498)
at com.websystique.springmvc.apitest.Example.main(Example.java:120)
any clue will be helpful
Thanks

Can't get json response with Retrofit

I'm using retrofit 1.9.0 and I had tried the following code to get a response in json format:
public void Execute(String email, String password, Callback<User> callback) {
final Callback<User> cb = callback;
RestAdapter restAdapter = buildRestAdapter();
System.out.println("Email " + email + " passowrd " + password);
User user = new User();
user.setEmail(email);
user.setPassword(password);
restAdapter.create(YutonAPI.class).postLogin(
user,
new Callback<User>() {
#Override
public void success(User user, Response response) {
System.out.println("succes");
System.out.println(response.getBody());
}
#Override
public void failure(RetrofitError error) {
System.out.println("error "+ error);
}
});
}
So this line of code:
System.out.println(response.getBody());
Should give me a response in json format however it didn't work because I'm getting the following output:
Link: http://i.imgur.com/mBQs1LL.png
So this is how my response in json format should look like:
{
"user": {
"image": "https://www.gravatar.com/avatar/e0a190604dc3dd2ee7b66bb95c20ef7f?d=identicon&s=512"
"email": "a#hotmail.com"
"name": "a"
"id": "566dfac21043a31820bf1ae6"
} -
}
I had already tested it on my server where I was making a post request. Below you can see a screenshot of it:
Link: http://i.imgur.com/PtEMR12.png
The issue here is that response.getBody() returns a TypedInputStream object, which you can't directly output because it isn't a String.
To read a TypedInputStream there are several options, as posted in: Retrofit callback get response body, the easiest being:
String body = new String(((TypedByteArray) response.getBody()).getBytes());
If the following error is thrown:
java.lang.ClassCastException: retrofit.client.UrlConnectionClient$TypedInputStream cannot be cast to retrofit.mime.TypedByteArray
Then make sure that you set .setLogLevel(RestAdapter.LogLevel.FULL) on the RestAdapter that you use to create the service.

Categories

Resources