Pass a JSON Array for POST request using Rest Assured based on the following JSON - rest-assured

I am new to Rest Assured, Please can someone help me to create the body request from the following output:
{
"CustomerID": "539177",
"ReminderTitle": "Demo Reminder Tds",
"ReminderDescription": "xyz Reminder",
"ReminderLocation": "New Delhi",
"ReminderDate": "2020-03-27",
"ReminderTime": "15:33",
"attendees": [{
"CustomerContactID": "122"
}]
}
Example :
Map <String, String> body = new HashMap <String, String> ();
body.put("CustomerID", CustomerID);
body.put("ReminderTitle", "Demo Reminder Tds");
body.put("ReminderDescription", "xyz Reminder");
body.put("ReminderLocation", "New Delhi");
body.put("ReminderDate", "2020-03-27");
body.put("ReminderTime", "15:33");

Map<String, Object> map = new LinkedHashMap<>();
map.put("CustomerID", "539177");
map.put("ReminderTitle", "Demo Reminder Tds");
map.put("ReminderDescription", "xyz Reminder");
map.put("ReminderLocation", "New Delhi");
map.put("ReminderDate", "2020-03-27");
map.put("ReminderTime", "15:33");
map.put("attendees", Arrays.asList(new LinkedHashMap<String, Object>() {
{
put("CustomerContactID", "122");
}
}));
Use the below to just print out the output ( you don't have to necessarily )
String abc = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(map);
System.out.println(abc);
And to use it with Rest Assured
given().body(map).when().post()

Rest Assured accepts String objects in .body(String body) method. But for POST and PUT methods only. Check the documentation
Therefore you can just pass the output you received.
String requestBody = "{ \"CustomerID\" : \"539177\", " +
"\"ReminderTitle\" : \"Demo Reminder Tds\", " +
"\"ReminderDescription\" : \"xyz Reminder\", " +
"\"ReminderLocation\" : \"New Delhi\", " +
"\"ReminderDate\" : \"2020-03-27\", " +
"\"ReminderTime\" : \"15:33\", " +
"\"attendees\" : [{\"CustomerContactID\" : \"122\"}] }";
BUT you have to use escape characters in the output String.
Then just pass the requestBody;
given()
.body(requestBody)
.when()
.post(URL);

Related

Gatling - print the POST request URI

I would like to print the URI and want to verify the POST URI request is formed correctly, Can you please advise how to verify the POST URI request if URI is substituted/formed correctly?
object BidSubmission extends HttpUtil {
val orders_feeder = csv("data/Round-1.csv").circular
def orderSubmission: ChainBuilder =
pause(pauseBy(5) seconds)
.repeat(1) {
feed(orders_feeder)
.exec(postToUri(s"${Constants.orderSubmission_URL}/#{$AuctionId}/base-orders/proxy-bid", "")
.queryParam("employeeId", "#{empNo}")
.body(StringBody(session => {
println(session)
println(session.attributes("empNo"))
val empNo = session.attributes("empNo").asInstanceOf[String]
val orderNo = session.attributes("orderNo").asInstanceOf[String]
println(s"\n\n\n $orderNo \n\n\n")
var slotNos = orderNo.replace("[", "").replace("]", "").split(" +")
println(s"\n\n\n ${generatePayload(empNo, slotNos)} \n\n\n")
generatePayload(empNo, slotNos)
" "
}))
)
}
You have to tune the logback configuration file. Please have a look at the documentation: https://gatling.io/docs/gatling/reference/current/core/configuration/#logbackxml

How to send the post request for the below json in Restassured

i am new to rest assured. how to send the POST resquest for the below JSON?
{
"customer_id":"001",
"appointment_id":"001",
"appointment_time":"2022-10-04 00:00:00",
"submitted_time":"2022-10-04 00:00:00",
"first_name":"ethinic",
"last_name":"one",
"date_of_birth":"1910-10-10",
"email_address":"test#gmail.com",
"address_1":"24",
"address_2":"testtwo",
"postcode":"abc123",
"phone":"1234567890",
"questions":[
{
"ethnicity":"Other Ethnic Groups - Chinese"
},
{
"do_you_or_anyone_in_your_household_have_a_fever_a_new_persistent_cough_loss_of_taste_or_smell_or_any_other_symptoms_of_covid_19":"No"
},
{
"what_is_the_main_reason_for_your_appointment_with_us":"Eye health concern"
},
]
}
There are two possible ways to send POST request with the above JSON.
Create POJO/DTO object that represents the same json structure and serialize it to json using library like GSON
Send it like it is by escaping all the quotes with slash.
1
private static MyObject obj = MyObject.builder()
.title("Title")
.userId("1234")
.build();
Response response = RestAssured.given()
.header("Content-type", "application/json")
.and()
.body(Gson.toJson(obj))
.when()
.post("/posts")
2
private static String requestBody = "{\n" +
" \"title\": \"foo\",\n" +
" \"body\": \"bar\",\n" +
" \"userId\": \"1\" \n}";
Response response = RestAssured.given()
.header("Content-type", "application/json")
.and()
.body(requestBody)
.when()
.post("/posts")

How to pass JSON string to another api using RESTSharp?

Problem Specification:
Resource URI : address/index.php?r=api/employee
Request Header : Content- Type: application/json
HTTP Method: POST
Request Body: { "employeeName" : "ABC","age":"20","ContactNumber": "12341234"}
The above parameters should be passed to the system as a row HTTP POST in a JSON string.
I am trying to solve this problem using RESTSharp. But I am having some problem Like after executing the request my code return a Null response and I am not sure my JSON string is passing properly or not.
Here is my Code:
public ActionResult EmployeeInfo(Employee employee)
{
//string empName = unSubscription.employeeName.ToString();
var client = new RestClient("http://localhost:21779/");
var request = new RestRequest("api/employee ", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Employee
{
employeeName = "ABC",
age = "20",
ContactNumber = "12341234"
});
request.AddHeader("Content-Type", #"application/json");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return View();
}
Is there anything wrong with my code??
And I am little bit confused about
request.AddUrlSegment("username", "Admin") and request.AddParameter("name", "value").
Basically I want to know how to utilize AdduUrlSegment() and AddParameter().
Thanks in advance.
For using request.AddUrlSegment("username", "Admin") you should define your url template properly: var request = new RestRequest("api/employee/{username} ", Method.POST);
Also you should set Content-Type
request.AddHeader("Content-Type", #"application/json");
befor adding a Body

Quick blox - Signature generation issue

I am trying to use this link to get described response:
{
"session": {
"application_id": 2,
"created_at": "2012-04-03T07:34:48Z",
"device_id": null,
"id": 743,
"nonce": 1308205278,
"token": "0e7bc95d85c0eb2bf052be3d29d3df523081e87f",
"ts": 1333438438,
"updated_at": "2012-04-03T07:34:48Z",
"user_id": null
}
}
But now it say application not found:
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>No application found</error>
</errors>
Can't go ahead to test another requests. This is a shell script I used for getting curl request:
timestamp=`date +%s`
body="application_id=HIDDENAPPLICATIONIDHERE&auth_key=HIDDENAUTHKEYHERE&nonce=2342546&timestamp=$timestamp"
signature=`echo -n $body | openssl sha -hmac HIDDENSECRETHERE`
body=$body"&signature="$signature
#echo $body
#echo $signature
#exit 0
curl -X POST \
-H "QuickBlox-REST-API-Version: 0.1.0" \
-d $body \
https://api.quickblox.com/session.xml
So there some info regrding this maybe I've created shell script to a wrong way:
HMAC-SHA function of the body of the request, with a key auth_secret.
Request body is formed as the sorted (sorting alphabetically, as
symbols, not as bytes) by increase the string array 'parameter=value',
separated with the symbol "&". For the parameters passed as a
user[id]=123 is used just such a line of user[id]=123
Also I've prepped a Swift project how to generate signature and get session, but still has the same error with no application found.
Any recommendation? Thanks
Please verify Application ID parameter because server return:
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>No application found</error>
</errors>
For example generate signature (Java):
Random random = new Random();
String nonce = Integer.toString(random.nextInt());
long time = System.currentTimeMillis() / 1000;
String timestamp = Long.toString(time);
String signature;
String str = "application_id=" + applicationId + "&" + "auth_key=" + authKey + "&" + "nonce="
+ nonce + "&" + "timestamp=" + timestamp + "&" + "user[login]=" + adminLogin + "&" + "user[password]="
+ adminPassword;
signature = UtilsMethods.calculateHMAC_SHA(str, authSecret);
calculateHMAC_SHA:
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public static String calculateHMAC_SHA(String data, String key) throws SignatureException {
String result = null;
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
byte[] digest = mac.doFinal(data.getBytes());
StringBuilder sb = new StringBuilder(digest.length * 2);
String s;
for (byte b : digest) {
s = Integer.toHexString(0xFF & b);
if (s.length() == 1) {
sb.append('0');
}
sb.append(s);
}
result = sb.toString();
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}

Oauth not working CX api

I'm trying to use the oauth for CX exposed api, I followed their documentation, still I'm getting HTTP "BAD REQUEST" error, Here is the code -
String method = "POST";
String code = "";
NameValuePair[] data = {
new NameValuePair("grant_type", "authorization_code"),
new NameValuePair("code", code),
new NameValuePair("redirect_uri",URLEncoder.encode(CALLBACK_URL, "UTF-8"))
};
String secret = CONSUMER_KEY+":"+CONSUMER_SECRET;
String encodedSecret = Base64.encodeBase64String(secret.getBytes("UTF-8"));
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
PostMethod httpMethod = new PostMethod(ACCESS_TOKEN_ENDPOINT_URL);
httpMethod.addRequestHeader("Authorization","Basic "+encodedSecret);
httpMethod.setRequestBody(data);
System.out.println("HTTP call -- " + method + " " + ACCESS_TOKEN_ENDPOINT_URL);
httpClient.executeMethod(httpMethod);
Thanks,
Hemant
I've tested the following slight modification of your code and it works. You might double check that
Your key has been approved (this shouldn't be the problem given the
error you are seeing).
You are using the correct ACCESS_TOKEN_ENDPOINT_URL
Try having the redirect_uri be the same for both the auth_code response and the token request
String method = "POST";
String authCode = "[AUTH-CODE-HERE]";
String CONSUMER_KEY="[YOUR-KEY-HERE]";
String CONSUMER_SECRET="[YOUR-SECRET-HERE]";
String ACCESS_TOKEN_ENDPOINT_URL="https://api.cx.com/1/oauth/token";
String REDIRECT_URI="[YOUR-REDIRECT-HERE]";
NameValuePair[] data = {
new NameValuePair("grant_type", "authorization_code"),
new NameValuePair("code", authCode),
new NameValuePair("redirect_uri", REDIRECT_URI)
};
String secret = CONSUMER_KEY+":"+CONSUMER_SECRET;
String encodedSecret = Base64.encodeBase64String(secret.getBytes("UTF-8"));
PostMethod httpMethod = new PostMethod(ACCESS_TOKEN_ENDPOINT_URL);
httpMethod.addRequestHeader("Authorization","Basic "+encodedSecret);
httpMethod.setRequestBody(data);
System.out.println("HTTP call -- " + method + " " + ACCESS_TOKEN_ENDPOINT_URL);
int responseCode = httpClient.executeMethod(httpMethod);
System.out.println(responseCode);
System.out.println(httpMethod.getResponseBodyAsString());
If you are still running into issues, can you post the result of the following line: System.out.println(httpMethod.getResponseBodyAsString());
The CX developer API has been discontinued.
Sorry for the inconvenience.

Resources