How to send the post request for the below json in Restassured - rest-assured

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")

Related

MockMVC test throws io.jsonwebtoken.MalformedJwtException when reading JSON

I am using MockMVC to test the JWT Token/authentication and I am having some trouble understanding why the JSON cannot be read.
This is the test that Ive written:
#SpringBootTest
#AutoConfigureMockMvc
public class JwtSecurityTest {
#Autowired
private MockMvc mockMvc;
#Test
public void existentUserCanGetTokenAndAuthentication() throws Exception {
String username = "user";
String password = "pass";
String body = "{"username":"" + username + "","password":"" + password + ""}";
MvcResult result = mockMvc.perform(post("http://localhost:8080/login/authenticate")
.contentType(MediaType.APPLICATION_JSON)
.content(body))
.andDo(MockMvcResultHandlers.print())
.andReturn();
String token = result.getResponse().getContentAsString();
mockMvc.perform(MockMvcRequestBuilders.get("http://localhost:8080/kund")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + token))
.andExpect(status().isOk());
}
And the error I get is:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = application/json
Body = {"jwt":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzbHkiLCJleHAiOjE2NTMwODM5NDMsImlhdCI6MTY1MzA0Nzk0M30.V5qqIRzlAtkXEK_OcFbiIlEaOdej3oyGFMy6Aw57ZB8"}
Forwarded URL = null
Redirected URL = null
Cookies = []
io.jsonwebtoken.MalformedJwtException: Unable to read JSON value: ?^?[????M
I find it weird because in the body, we can clearly see that the token looks good.

F# making a API request to a graphql endpoint

I try to get some data from a grqphql endpoint with F#.
I use Fsharp.Data
let apiQuery = """query findData {
apiData(Model:{
PageNumber: 1,
PageSize: 100
})
{
ErrorMessage Success ValidationResult TotalCount
Data{
ItemId
}
}
}"""
let queryGraphQl () =
Http.RequestString
( apiUrl,
headers = [ ContentType HttpContentTypes.Json;
Authorization ("bearer " + token)
],
body =
TextRequest apiQuery
)
But I get (500) Internal Server Error
The same in Python works fine:
query_headers = {
"Authorization": 'bearer %s' % token,
'Content-Type': 'application/json'
}
response = requests.post(url, json={'query': apiQuery}, headers=query_headers)
Any suggestions what I am missing?
In Postman I have to add
Content-Length and Host like to be calculated when request is sent.
It appears that the F# and Python code is not equivalent. The Python code contains additional query keyword in the payload.
I don't know the specifics of your particular endpoint, but I wrote similar code using one of the public interfaces.
open System.Net
open FSharp.Data
open FSharp.Data.HttpRequestHeaders
let key = "********-****-****-****-*************"
let uri k = $"https://api.everbase.co/graphql?apikey={k}"
let gurl = uri key
let apiQuery = """{ "query" :
"{ client { ipAddress { country { name } city { name } } } }"
}"""
let connectToGraph apiUrl apiQuery =
try
let res = Http.RequestString( url = apiUrl, httpMethod="POST", body = TextRequest apiQuery, headers = [ ContentType HttpContentTypes.Json; UserAgent "mozilla" ])
res
with
| _ as ex -> ex.Message
[<EntryPoint>]
let main argv =
let res = connectToGraph gurl apiQuery
printf "Response: %A" res
0
I suppose you should separate the query in your F# code from the rest of the definition with a ':'. Also the actual payload should be wrapped in quotes/double quotes to form a valid Json value.

C# WebClient.UploadData in Rails

I have a c# method that I'm trying to convert to ruby on rails . I'm using unirest but I think something is not working correctly. This is my C# method :
private static string HTTPPoster(string url, string prmSendData)
{
try
{
WebClient wUpload = new WebClient();
wUpload.Proxy = null;
Byte[] bPostArray = Encoding.UTF8.GetBytes(prmSendData);
Byte[] bResponse = wUpload.UploadData(url, "POST", bPostArray);
Char[] sReturnChars = Encoding.UTF8.GetChars(bResponse);
string sWebPage = new string(sReturnChars);
return sWebPage;
}
catch
{
return "-1";
}
}
And This is what I tried so far in rails with unirest :
def HTTPPoster(url)
xml = "My XML Goes Here"
byte_array = xml.bytes
headers = {}
headers['Content-Type'] = "application/json"
headers['Accept'] = "application/json"
response = Unirest.post(url,
headers: headers,
parameters: {
body: byte_array
})
puts "response #{response.body}"
if ![200,201].include?(response.code)
raise "Mblox Error: #{response.code}, #{response.body}"
end
end
If you also know other libraries that can achieve what I need please let me know.
I used Faraday gem and sent the data as xml and not as byte array. And now I am achieving want I wanted.
response = Faraday.post(url) do |req|
req.headers['Content-Type'] = "application/xml"
req.headers['Accept'] = "*/*"
req.headers['Accept-Encoding'] = "gzip, deflate, br"
req.body = xml
end

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

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);

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

Resources