Sobhit Sharma
Sobhit Sharma

Reputation: 713

How to send queryParam with hashmap object

I trying to hit this api in post with java and restassured. But api has alot of queryParam with contentype- application/x-www-form-urlencoded, which cannot be send manual changing it.

Sample code is as follows-

RequestSpecification request=given();
        Response responseSample = request
                .queryParam("lastName","Sharma")
                .queryParam("firstName","Sobhit")
                .queryParam("street","523-E-BROADWAY")
                .post(url);

I have multiple parameters for sample added 3. I want read it from hashmap object and send it.

Upvotes: 2

Views: 11280

Answers (3)

bhusak
bhusak

Reputation: 1390

RestAssured API provides multiple methods to send parameters using java.util.Map. Create new map and put there parameters you need:

Map<String, String> params = new HashMap<>();
params.put("param1", "value1");
params.put("param2", "value2");

Then add this map to your request specification as:

  1. Form parameters:

    RestAssured.given()
        .formParams(params)
        .when()
        .post("http://www.example.com");
    
  2. Query parameters:

    RestAssured.given()
        .queryParams(params)
        .when()
        .post("http://www.example.com");
    
  3. Path parameters:

    RestAssured.given()
        .pathParams(params)
        .when()
        .post("http://www.example.com/{param1}/{param2}");
    

Also there's a generalized method params(parametersMap: Map): RequestSpecification, but it adds parameters as query or form params depending on request specification.

Upvotes: 2

jacobcs
jacobcs

Reputation: 569

Using rest-assured v3.0.3 we can do this:

// Put the query params in a map.
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("lastName","Sharma");
queryParams.put("firstName","Sobhit");
queryParams.put("street","523-E-BROADWAY");

// Pass the map while creating the request object.
RequestSpecification request=RestAssured.given().queryParams(queryParams);
Response responseSample = request.post(url);

Maven dependency:

<dependency>
  <groupId>io.rest-assured</groupId>
  <artifactId>rest-assured</artifactId>
  <version>3.0.3</version>
</dependency>

Upvotes: 1

Margon
Margon

Reputation: 511

You need to change your code with:

RequestSpecification request=given();

// add the request query param
map.forEach((k, v) -> {request.queryParam(k,v);});

// send the request
Response responseSample = request.post(url);

Upvotes: 1

Related Questions