What Is Rest Assure API Testing ?

 


Introduction:

API stands for Application Programming Interface. It's a hard and fast of policies, protocols, and tools that permit exclusive software packages to talk with each other. APIs define the techniques and data formats that developers can use to engage with a gadget, service, or software, abstracting away the underlying implementation details. APIs play a vital function in contemporary software improvement by means of allowing interoperability, abstraction, and extensibility. They permit developers to construct complex systems by way of integrating current services and functionalities, accelerating improvement and fostering innovation.

A URL (Uniform Resource Locator) is a string of characters that gives the address of a aid on the net. URLs have a selected syntax that includes numerous elements:

Scheme: The scheme indicates the protocol used to access the resource. Common schemes include http, https, ftp, file, etc. In http://example.com, http is the scheme.

Authority: The authority part of the URL typically includes the domain name or IP address of the server hosting the resource. In http://example.com, example.com is the authority.

Path: The path specifies the location of the resource on the server's filesystem or within the application. It comes after the authority and starts with a /. In http://example.com/api/books, /api/books is the path.

Query Parameters: Query parameters are used to pass data to the server as part of the URL. They come after a ? and are separated by &. Each parameter consists of a key-value pair. For example, in http://example.com/search?q=rest+api, q=rest+api is a query parameter where q is the key and rest+api is the value.

Fragment: The fragment is used to specify a location within the resource itself. It comes after a #. For example, in http://example.com/page#section2, section2 is the fragment.

So, when you see a URL like http://example.com/api/books?q=rest+api, you can break it down as follows:

  • Scheme: http
  • Authority: example.com
  • Path: /api/books
  • Query Parameters: q=rest+api

This URL would typically be used to access a resource on the server located at example.com, under the path /api/books, with a query parameter q set to rest+api.

REST API:

A REST API (Representational State Transfer Application Programming Interface) is a type of net service that follows the concepts of REST architectural fashion. REST is an architectural fashion for designing networked programs. RESTful APIs use HTTP requests to carry out operations on sources, that are generally represented the usage of JSON or XML codecs.

RESTful APIs provide a simple and bendy manner to build internet offerings that can be without difficulty fed on through customers. By following the standards of REST, developers can create scalable and interoperable APIs which might be properly-acceptable for modern-day internet and cell packages.

Suppose you have got a RESTful API for dealing with customers. Here's how exceptional HTTP strategies can be used to perform operations at the "users" resource:

  • GET /users: Retrieve a list of all users.
  • GET /users/{id}: Retrieve information about a specific user.
  • POST /users: Create a new user.
  • PUT /users/{id}: Update information about a specific user.
  • DELETE /users/{id}: Delete a specific user.

Common HTTP Status Code Classes:

  • 1xx - Informational: These status codes indicate that the request has been received and is being processed. An example is 100 Continue, indicating that the client can continue with its request.
  • 2xx - Success: These status codes indicate that the request was successfully received, understood, and accepted by the server. For example, 200 OK signifies that the request was successful.
  • 3xx - Redirection: These status codes indicate that further action needs to be taken to complete the request. For example, 301 Moved Permanently indicates that the requested resource has been permanently moved to a different URI.
  • 4xx - Client Error: These status codes indicate that the client made a mistake in its request, such as providing invalid data or requesting a resource that doesn't exist. For example, 404 Not Found indicates that the requested resource could not be found on the server.
  • 5xx - Server Error: These status codes indicate that there was an error on the server side while processing the request. For example, 500 Internal Server Error indicates that there was an unexpected condition that prevented the server from fulfilling the request.

Commonly Encountered HTTP Status Codes:

  • 200 OK: The request was successful.
  • 201 Created: The request has been fulfilled, and a new resource has been created.
  • 204 No Content: The server successfully processed the request, but there is no content to return.
  • 400 Bad Request: The server could not understand the request due to invalid syntax or other client-side errors.
  • 401 Unauthorized: The client must authenticate itself to get the requested response.
  • 403 Forbidden: The client does not have permission to access the requested resource.
  • 404 Not Found: The server could not find the requested resource.
  • 500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.

REST Assured is a famous Java library used for trying out RESTful net offerings. It simplifies the technique of validating and interacting with REST APIs by way of offering a site-specific language (DSL) that is straightforward to understand and use. REST Assured integrates with present Java testing frameworks together with JUnit and TestNG, making it a powerful tool for developers and testers.

Key Features of REST Assured:

Simplified Syntax: REST Assured makes use of a readable and intuitive syntax, which makes writing checks truthful.

Integration with Testing Frameworks: It integrates seamlessly with JUnit, TestNG, and other checking out frameworks.

Support for JSON and XML: It can cope with JSON and XML requests and responses, making it flexible for one-of-a-kind styles of net services.

Built-in Assertions: REST Assured consists of built-in statement techniques to confirm the fame codes, response headers, and response bodies.

Support for OAuth, Basic Authentication, and Other Authentication Methods: It supports numerous authentication mechanisms required for having access to secured APIs.

Basic Example of REST Assured:

Here's a simple example of the use of REST Assured to check a RESTful API:

import io.restassured.RestAssured;

import io.restassured.response.Response;

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;


public class APITest {

    public static void main(String[] args) {

        // Base URI of the API

        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";


        // Making a GET request and validating the response

        given().

        when().

            get("/posts/1").

        then().

            statusCode(200).

            body("userId", equalTo(1)).

            body("id", equalTo(1)).

            body("title", notNullValue()).

            body("body", notNullValue());

    }

}

Steps in the Example:

  • Set Base URI: The baseURI is set to the URL of the API being tested.
  • Given-When-Then Syntax: This syntax is used to structure the test:
  • Given: Set up the request's parameters, headers, body, etc.
  • When: Specify the HTTP method (GET, POST, PUT, DELETE) and endpoint.
  • Then: Define the assertions to validate the response.

Advanced Features:

Path Parameters and Query Parameters: Support for dynamic request parameters.

Request and Response Specifications: Reuse common request and response configurations.

Filters: Preprocess requests and responses.

Logging: Detailed logging for debugging purposes.

Integration with Test Frameworks

REST Assured can be easily integrated with JUnit and TestNG for comprehensive testing. Here’s an example with JUnit:

import io.restassured.RestAssured;

import io.restassured.response.Response;

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;

import org.junit.Test;


public class APITest {


    @Test

    public void testGetPost() {

        // Base URI of the API

        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";


        // Making a GET request and validating the response

        given().

        when().

            get("/posts/1").

        then().

            statusCode(200).

            body("userId", equalTo(1)).

            body("id", equalTo(1)).

            body("title", notNullValue()).

            body("body", notNullValue());

    }

}

Assuming the base URL of the API is http://example.com/api/books, here's how you can write tests using REST Assured:

import org.testng.annotations.Test;

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;


public class BookAPITest {


    // Base URL of the API

    private static final String BASE_URL = "http://example.com/api/books";


    @Test

    public void testGetBooks() {

        // Test to retrieve all books

        given().

        when().

            get(BASE_URL).

        then().

            statusCode(200). // Check that the response status code is 200 (OK)

            body("size()", greaterThan(0)); // Check that at least one book is returned

    }


    @Test

    public void testAddBook() {

        // Test to add a new book

        String requestBody = "{\"title\": \"Test Book\", \"author\": \"Test Author\"}";


        given().

            contentType("application/json").

            body(requestBody).

        when().

            post(BASE_URL).

        then().

            statusCode(201); // Check that the response status code is 201 (Created)

    }


    @Test(dependsOnMethods = {"testAddBook"})

    public void testUpdateBook() {

        // Test to update an existing book

        String updatedBookBody = "{\"title\": \"Updated Test Book\", \"author\": \"Updated Test Author\"}";


        given().

            contentType("application/json").

            body(updatedBookBody).

        when().

            put(BASE_URL + "/{bookId}", "1"). // Assuming the book ID is 1

        then().

            statusCode(200); // Check that the response status code is 200 (OK)

    }


    @Test(dependsOnMethods = {"testUpdateBook"})

    public void testDeleteBook() {

        // Test to delete an existing book

        given().

        when().

            delete(BASE_URL + "/{bookId}", "1"). // Assuming the book ID is 1

        then().

            statusCode(204); // Check that the response status code is 204 (No Content)

    }

}

Explanation:

testGetBooks(): This test sends a GET request to retrieve all books from the API and verifies that the response status code is 200 (OK) and that at least one book is returned.

testAddBook(): This test sends a POST request to add a new book to the API and verifies that the response status code is 201 (Created).

testUpdateBook(): This test sends a PUT request to update an existing book in the API and verifies that the response status code is 200 (OK).

testDeleteBook(): This test sends a DELETE request to delete an existing book from the API and verifies that the response status code is 204 (No Content).

These exams display how you can use REST Assured to engage with a RESTful API and verify its conduct. You would typically run those checks as part of your automatic test suite to make certain the API functions efficiently.

Conclusion:

REST Assured is a effective device for API trying out that makes it easy to jot down readable and maintainable assessments. Its integration with Java checking out frameworks and help for numerous types of assertions and authentication strategies make it a cross-to choice for many developers and testers.

Next Post Previous Post
No Comment
Add Comment
comment url