POST request is used for submitting data into the server. Suppose you sign up for Gmail or Facebook application you submit your details into their server. Data is sent in JSON format.
How to write POST request in Rest Assured
- import io.restassured.RestAssured;
- import io.restassured.path.json.JsonPath;
- import static io.restassured.RestAssured.*;
- import static org.hamcrest.Matchers.*;
- public class POSTRequest{
- public static void main(String [] args){
- RestAssured.baseURI="https://rahulshettyacademy.com";
- String response = given().queryParam("key", "qaclick123")
- .header("Content-Type","application/json")
- .body(
- "{\r\n" +
- " \"location\": {\r\n" +
- " \"lat\": -38.383494,\r\n" +
- " \"lng\": 33.427362\r\n" +
- " },\r\n" +
- " \"accuracy\": 50,\r\n" +
- " \"name\": \"Frontline house\",\r\n" +
- " \"phone_number\": \"(+91) 983 893 3937\",\r\n" +
- " \"address\": \"29, side layout, cohen 09\",\r\n" +
- " \"types\": [\r\n" +
- " \"shoe park\",\r\n" +
- " \"shop\"\r\n" +
- " ],\r\n" +
- " \"website\": \"http://google.com\",\r\n" +
- " \"language\": \"French-IN\"\r\n" +
- "}";).
- when().log().all().post("/maps/api/place/add/json").then()
- .assertThat().statusCode(200).body("scope",equalTo("APP")).
- header("Server","Apache/2.4.18 (Ubuntu)")
- .extract().response().asString();
- System.out.println(response);
- JsonPath jsonPath = ReusableMethods.jsonParser(response);
- String PlaceId = jsonPath.getString("place_id");
- System.out.println(PlaceId);
- }
- }
Explanation
1. Set baseURI using RestAssured class to send request to the server.
2. Chained all the precondition methods using given() method i.e. query parameters and body. body() method accepts data in form of JSON String. Eclipse or Intellij editors convert JSON data into JSON String automatically. In header() method we tell the request that we are sending request in form of JSON.
3. Chained the post() method using using when() method and post() method accept path parameter as argument.
4. Chained all validation method using then() method.
5. Extracted the response in form of String.
6. Object of JsonPath class is instantiated to parse String into JSON.
0 comments:
Post a Comment