Performing a post request using Rest Assured DSL - rest-assured

this is the body of my post request
{
"Type": "Something",
"Authentication": [
{
"Key": "key1",
"Value": "value1"
},
{
"Key": "key2",
"Value": "value2"
},
{
"Key": "key3",
"Value": "value3"
}
]
}
I am not quite sure how to simulate sending the parameters for my post request for the post payload above.
I assumed sending everything as a key value pair but have not accounted for the nesting in the Authentication which is an array. As excepted I get a 400 Bad Request.
I would appreciate understanding how to actually send the post parameters properly for this request. Does sending it in a Map make any difference apart from readability
This is my RestAssured DSL
given().
param("type", "Something").
param("key1", "value1").
param("key2", "value2").
param("key3", "value3").
header("content-type", "application/json").
when().
post("http://someURL/something").
then().
statusCode(200).
log().everything();

Just create a hash map like this:
Map<String, Object> map = new HashMap<>();
map.put("Type", "Something");
map.put("Authentication", asList(new HashMap<String, Object>() {{
put("Key", "key1");
put("Value", "value1");
}}, new HashMap<String, Object>() {{
put("Key", "key2");
put("Value", "value2");
}}, new HashMap<String, Object>() {{
put("Key", "key3");
put("Value", "value3");
}}));
And pass it to the body of REST Assured:
given().
contentType(ContentType.JSON).
body(map).
when().
post("http://someURL/something").
then().
statusCode(200).
log().everything();
You could also create a POJO instead of a map and pass it to the body if you prefer. For this to work you need to have a supported JSON serializer framework in the classpath. For example jackson-databind. See documentation for more info.

String inputPayLaod = "{
"Type": "Something",
"Authentication": [
{
"Key": "key1",
"Value": "value1"
},
{
"Key": "key2",
"Value": "value2"
},
{
"Key": "key3",
"Value": "value3"
}
]
}";
given().contentType(ContentType.JSON)
.body(inputPayLoad)
.when()
.post(url)
.then().statusCode(200);

Related

how to convert nested json payload into for Restassured POST call using Map?

{
"#serviceName": "75MultipleService",
"inputs": [
{
"#name": "inp1",
"value": "8",
"#type": "number"
},
{
"#name": "inp2",
"value": "8",
"#type": "number"
}
]
}
I am trying this but not understating how to pass input2
Map <String, Object> map = new HashMap<> ();
map.put("#serviceName", "75MultipleService");
map.put("inputs", Arrays.asList(new HashMap<String, Object>() {{
put("#name", "inp1");
put("value", "8");
put("#type", "number");
}}));
How to pass nested json to post request?
how to pass input2
It's just another Map, you can do like this.
Map<String, Object> input1 = Map.of("#name", "inp1", "value", "8", "#type", "number");
Map<String, Object> input2 = Map.of("#name", "inp2", "value", "8", "#type", "number");
Map<String, Object> payload = Map.of("#serviceName", "75MultipleService", "inputs", List.of(input1, input2));

Titanium- Post request is not working when I using JSONArray in body content

Hi I am sending POST request using HTTPClient. Here I am passing some JSON data which have some arrays.
{
"pccpId": "11111",
"courseId": "XXXXX",
"employeeId": "XXXXXX",
"userId": "X!##$",
"assignments": [
{
"Id": "XXXX",
"targetDate": "05/30/2018",
"targetNewDate": "04/30/2018"
},
{
"Id": "YYYYY",
"targetDate": "04/22/2018",
"targetNewDate": "04/26/2018"
}
]
}
When I am using this data, I am getting 400 error code. When I am checking with backend is not at all hitting to the server. Same data giving expected result when I run on Postman.
Anyone have any suggestion!!
Thanks
I have this pb with titanium nodeJS api, workaround is to stringify your data and parse it on server
Try to but your keys without double quotation like this
{
pccpId: "11111",
courseId: "XXXXX",
employeeId: "XXXXXX",
userId: "X!##$",
assignments: [{
"Id": "XXXX",
"targetDate": "05/30/2018",
"targetNewDate": "04/30/2018"
},
{
"Id": "YYYYY",
"targetDate": "04/22/2018",
"targetNewDate": "04/26/2018"
}
]
}

How to import Swagger APIs into Postman?

Recently I wrote restful APIs with SpringMvc and swagger-ui(v2). I noticed the Import function in Postman:
So my question is how to create the file which Postman needed?
I am not familiar with Swagger.
I work on PHP and have used Swagger 2.0 to document the APIs.
The Swagger Document is created on the fly (at least that is what I use in PHP). The document is generated in the JSON format.
Sample document
{
"swagger": "2.0",
"info": {
"title": "Company Admin Panel",
"description": "Converting the Magento code into core PHP and RESTful APIs for increasing the performance of the website.",
"contact": {
"email": "jaydeep1012#gmail.com"
},
"version": "1.0.0"
},
"host": "localhost/cv_admin/api",
"schemes": [
"http"
],
"paths": {
"/getCustomerByEmail.php": {
"post": {
"summary": "List the details of customer by the email.",
"consumes": [
"string",
"application/json",
"application/x-www-form-urlencoded"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "email",
"in": "body",
"description": "Customer email to ge the data",
"required": true,
"schema": {
"properties": {
"id": {
"properties": {
"abc": {
"properties": {
"inner_abc": {
"type": "number",
"default": 1,
"example": 123
}
},
"type": "object"
},
"xyz": {
"type": "string",
"default": "xyz default value",
"example": "xyz example value"
}
},
"type": "object"
}
}
}
}
],
"responses": {
"200": {
"description": "Details of the customer"
},
"400": {
"description": "Email required"
},
"404": {
"description": "Customer does not exist"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
},
"/getCustomerById.php": {
"get": {
"summary": "List the details of customer by the ID",
"parameters": [
{
"name": "id",
"in": "query",
"description": "Customer ID to get the data",
"required": true,
"type": "integer"
}
],
"responses": {
"200": {
"description": "Details of the customer"
},
"400": {
"description": "ID required"
},
"404": {
"description": "Customer does not exist"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
},
"/getShipmentById.php": {
"get": {
"summary": "List the details of shipment by the ID",
"parameters": [
{
"name": "id",
"in": "query",
"description": "Shipment ID to get the data",
"required": true,
"type": "integer"
}
],
"responses": {
"200": {
"description": "Details of the shipment"
},
"404": {
"description": "Shipment does not exist"
},
"400": {
"description": "ID required"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
}
},
"definitions": {
}
}
This can be imported into Postman as follow.
Click on the 'Import' button in the top left corner of Postman UI.
You will see multiple options to import the API doc. Click on the 'Paste Raw Text'.
Paste the JSON format in the text area and click import.
You will see all your APIs as 'Postman Collection' and can use it from the Postman.
You can also use 'Import From Link'. Here paste the URL which generates the JSON format of the APIs from the Swagger or any other API Document tool.
This is my Document (JSON) generation file. It's in PHP. I have no idea of JAVA along with Swagger.
<?php
require("vendor/autoload.php");
$swagger = \Swagger\scan('path_of_the_directory_to_scan');
header('Content-Type: application/json');
echo $swagger;
With .Net Core it is now very easy:
You go and find JSON URL on your swagger page:
Click that link and copy the URL
Now go to Postman and click Import:
Select what you need and you end up with a nice collection of endpoints:
The accepted answer is correct but I will rewrite complete steps for java.
I am currently using Swagger V2 with Spring Boot 2 and it's straightforward 3 step process.
Step 1: Add required dependencies in pom.xml file. The second dependency is optional use it only if you need Swagger UI.
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Step 2: Add configuration class
#Configuration
#EnableSwagger2
public class SwaggerConfig {
public static final Contact DEFAULT_CONTACT = new Contact("Usama Amjad", "https://stackoverflow.com/users/4704510/usamaamjad", "hello#email.com");
public static final ApiInfo DEFAULT_API_INFO = new ApiInfo("Article API", "Article API documentation sample", "1.0", "urn:tos",
DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<VendorExtension>());
#Bean
public Docket api() {
Set<String> producesAndConsumes = new HashSet<>();
producesAndConsumes.add("application/json");
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(DEFAULT_API_INFO)
.produces(producesAndConsumes)
.consumes(producesAndConsumes);
}
}
Step 3: Setup complete and now you need to document APIs in controllers
#ApiOperation(value = "Returns a list Articles for a given Author", response = Article.class, responseContainer = "List")
#ApiResponses(value = { #ApiResponse(code = 200, message = "Success"),
#ApiResponse(code = 404, message = "The resource you were trying to reach is not found") })
#GetMapping(path = "/articles/users/{userId}")
public List<Article> getArticlesByUser() {
// Do your code
}
Usage:
You can access your Documentation from http://localhost:8080/v2/api-docs just copy it and paste in Postman to import collection.
Optional Swagger UI: You can also use standalone UI without any other rest client via http://localhost:8080/swagger-ui.html and it's pretty good, you can host your documentation without any hassle.
Recommend you to read this answer
https://stackoverflow.com/a/51072071/4712855
Refer to the https://stackoverflow.com/posts/39072519 answer, and then partially delete the returned content. Finally, it is found that swagger lacks some configuration and postmat cannot be imported.
You need to add the following configuration in swagger
#Bean
public Docket api(SwaggerProperties swaggerProperties) {
swaggerProperties.setTitle("my-project");
swaggerProperties.setDescription("my project");
swaggerProperties.setVersion("v1");
swaggerProperties.getContact().setUrl("http");
//I overlooked other configurations. Note that my swagger configuration lacks these.
}
In short, the attributes in the ApiInfoBuilder class are assigned values as much as possible
spring-boot version:2.3.10.RELEASE
springfox-swagger version: 2.9.2
You can do that: Postman -> Import -> Link -> {root_url}/v2/api-docs
This is what worked for me from the Swagger editor interface:
Method 1
Copy the YAML file contents into the Raw Text area:
Method 2 (more steps)
Step 1: Export the file as JSON
Step 2: Import the JSON file with Postman "Import"
Click on the orange button ("choose files")
Browse to the Swagger doc (swagger.yaml)
After selecting the file, a new collection gets created in POSTMAN. It will contain folders based on your endpoints.
You can also get some sample swagger files online to verify this(if you have errors in your swagger doc).

Rest-Assured Get jsonPath when JSON key starts with number

How do i get name=status using json path ... problem here is key=2 is random number,,, is their any way to skip these random and read name
Am using rest assured ,,this is sample response on GET request
Response
{
"error": false,
"message": "",
"data": {
"2": {
"name": "No Status",
"protected": "1",
"id": "1",
"temporal_start": "0",
"temporal_end": "2147483647"
},
"3": {
"name": "Started",
"protected": "1",
"id": "2",
"temporal_start": "0",
"temporal_end": "2147483647"
},
}
}
my request code is
given()
.param("error", "false")
.when()
.get(URI)
.then()
.body("data.2.name", startsWith(No))
I've found a solution but it's not very elegant:
when().
get(URI).
then().
body("data.collect { it.value }.reverse()[0].name", equalTo("No Status")).
body("data.collect { it.value }.reverse()[1].name", equalTo("Status"));
Which can be simplified using root paths:
when().
get(URI).
then().
root("data.collect { it.value }.reverse()[%d].name").
body(withArgs("0"), equalTo("No Status")).
body(withArgs("1"), equalTo("Status"));
Explanation:
Since data is a JsonObject represented as a HashMap we run the collect method to return only the values of the Map as a List. Then we reverse the list since it seems like the last when running collect the resulting list will have the last value first. Then we get the first value from this list (data.2 in your example) and finally get the name.

How do I generically access this Groovy JSON object?

I'm using Grails 1.3.6. I read the following JSON into a variable ...
{
"abc": {
"attr1": "value1",
"attr2": "value2"
},
"def": {
"attr1": "value1",
"attr2": "value2"
},
"ghi": {
"attr1": "value1",
"attr2": "value2"
},
...
}
If, in my controller, I'm passed a parameter referring to one part of the JSON object ...
def section = params.section; // could be "abc", "def", 'ghi", ...e
How do I access that part of the JSON assuming the above gets stored into a Groovy variable named "myJSONObject"? Thanks, - Dave
If you used JSON.parse() to create your myJSONObject, you can just do:
def value = myJsonObject[section]

Resources