Skip to main content

Day 4: Understanding HTTP methods

Day 3: Writing your first test with Rest Assured

Day 4 of Rest Assured training focuses on understanding the HTTP methods and how to use them in Rest Assured. HTTP methods are a set of rules that determine how data is transferred between a client and server.


The most commonly used HTTP methods are:

  • GET: used to retrieve information from a server
  • POST: used to submit data to a server
  • PUT: used to update an existing resource on a server
  • DELETE: used to delete a resource from a server

To use these HTTP methods in Rest Assured, we can simply call the corresponding method from the RestAssured library. For example, to make a GET request, we can use:

     
Response response = RestAssured.get("https://myapi.com/getData");
	
	

Similarly, we can use the post(), put(), and delete() methods to make POST, PUT, and DELETE requests respectively.

In addition to the HTTP methods, we can also set request headers and query parameters in Rest Assured. Request headers provide additional information about the request being made, such as the content type or the authentication token. Query parameters are used to filter or sort the data returned by the server.

To set request headers in Rest Assured, we can use the header() method. For example:

     
     Response response = RestAssured.given()
                        .header("Authorization", "Bearer myToken")
                        .get("https://myapi.com/getData");

     
	

To set query parameters, we can use the queryParam() method. For example:

     
     Response response = RestAssured.given()
                        .queryParam("sort", "name")
                        .get("https://myapi.com/getData");
	
	

Understanding the HTTP methods and how to use them with request headers and query parameters is essential for writing effective tests with Rest Assured.



Example 1: GET method
     
       given()
    .header("Authorization", "Bearer abcdef123456")
    .param("q", "rest assured tutorial")
.when()
    .get("https://api.example.com/search")
.then()
    .statusCode(200)
    .body("results.size()", equalTo(10));

     
	

In this example, we are sending a GET request to the "https://api.example.com/search" endpoint with an "Authorization" header and a "q" query parameter. We then validate that the response has a status code of 200 and that the "results" array in the response body has a size of 10.



Example 2: POST method

Let's say we want to create a new user in our system. We can use the POST method to send a request to the API endpoint with the necessary information in the request body. Here's an example code snippet:

     
     
// Base URL of the API
String baseURL = "https://myapi.com";

// Request body
Map requestBody = new HashMap<>();
requestBody.put("name", "John Doe");
requestBody.put("email", "johndoe@example.com");
requestBody.put("password", "mypassword");

// Send the POST request
given()
    .contentType(ContentType.JSON)
    .body(requestBody)
.when()
    .post(baseURL + "/users")
.then()
    .statusCode(201);

     
	

In this example, we're sending a request to the /users endpoint with the user information in the request body. We're setting the content type to JSON, and using the given(), when(), and then() syntax to structure the request and response assertions. If the user is successfully created, we expect a status code of 201.


Example 3: DELETE method

Let's say we want to delete a user from our system. We can use the DELETE method to send a request to the API endpoint with the user ID in the URL. Here's an example code snippet:

     
// Base URL of the API
String baseURL = "https://myapi.com";

// ID of the user to be deleted
int userId = 123;

// Send the DELETE request
given()
    .contentType(ContentType.JSON)
.when()
    .delete(baseURL + "/users/" + userId)
.then()
    .statusCode(204);

   
	

In this example, we're sending a request to the /users/{id} endpoint with the user ID in the URL. We're setting the content type to JSON, and using the given(), when(), and then() syntax to structure the request and response assertions. If the user is successfully deleted, we expect a status code of 204.


Understanding HTTP methods is important in Rest Assured as it allows us to perform various types of requests and interact with RESTful web services in different ways. By understanding how to use HTTP methods, we can write more complex and comprehensive tests that cover different scenarios.

Comments

Popular posts from this blog

How to integrate Autoit with selenium

For handling Dialog boxes which are not web based, Then Autoit is the best Tool to handle this These are the following code should written in Selenium Selenium Code: try { String[] commands = new String[] {}; commands = new String[] { "Path" }; // location of Autoit EXE file Runtime.getRuntime().exec(commands); } catch (IOException e) { } Autoit code: if WinWaitActive("File Upload") Then ;MsgBox(2,"window found","Found the window") WinActivate("File upload") Send("!n") Sleep(5000) Send("File path") SEND("{ENTER}") ;location of the file you want to a to the form and submit ;Send("!O") Else MsgBox(1,"TimeOut","Timed out") EndIf Here we need to create a Exe file for the Autoit script and that path should be mentioned in selenium code.

Reflection API

The Reflection API allows Java code to examine classes and objects at run time.The new reflection classes allow you to call another class's methods dynamically at run time. With the reflection classes, you can also examine an instance's fields and change the fields' contents. The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method, Constructor, Array, and Modifier. Example program: import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; // calling method whose name we store in a variable public class ReflectionAPI { public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { String x="sampleTest"; //String meth=read name from xls file Method method= ReflectionAPI.class.getMethod(x, String.class); method.invoke(method, "welcome"); System.out.

Collection API

CollectionAPI: The Java Collections API's provide Java developers with a set of classes and interfaces that makes it easier to handle collections of objects. In a sense Collection's works a bit like arrays, except their size can change dynamically, and they have more advanced behaviour than arrays. Example program: import java.util.ArrayList; import java.util.Hashtable; public class CollectionAPI { /** * @param args */ public static void main(String[] args) { int names[] = new int[5]; ArrayList list = new ArrayList (); list.add("Ramu");//0 list.add("Venu");//1 list.add("Raju");//2 System.out.println(list.size()); for(int i =0; i<=list.size(); i++) { System.out.println(list.get(i)); } // key - value // key - unique Hashtable table = new Hashtable (); table.put("name", "Hyderabad"); table.put("place", "Mumbai"); table.put("na