Popular Searches
Popular Course Categories
Popular Courses

REST API Basics

API & Database Integration

<div class="selenium-notes">

<h1>REST API Basics</h1>

<p><strong>REST API (Representational State Transfer Application Programming Interface)</strong> is a widely used approach for enabling applications, services, and systems to communicate with each other over a network using standard HTTP methods. REST APIs are commonly used in web applications, mobile applications, automation frameworks, microservices, cloud applications, and integration testing.</p>

<p>In software testing and Selenium automation, understanding REST APIs is important because modern applications often depend on backend APIs for authentication, user management, product information, search, orders, payments, and other business operations. API testing allows testers to validate backend functionality directly without depending entirely on the user interface.</p>

<p>REST APIs generally use HTTP methods such as <strong>GET, POST, PUT, PATCH, and DELETE</strong> to perform operations on resources. Data is commonly exchanged using formats such as JSON.</p>

<p><strong>Course Resource:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

<hr>

<h2>1. What is an API?</h2>

<p>An <strong>API (Application Programming Interface)</strong> is a set of rules and mechanisms that allows one software application to communicate with another application or service.</p>

<p>For example, when a mobile application displays customer information, the application may send a request to a backend API. The API processes the request, communicates with the database or another service, and returns the required response.</p>

<pre><code>Client Application

        |

        | HTTP Request

        v

      REST API

        |

        v

    Application

      Server

        |

        v

    Database

        |

        v

    HTTP Response

        |

        v

Client Application</code></pre>

<hr>

<h2>2. What is REST?</h2>

<p><strong>REST</strong> stands for <strong>Representational State Transfer</strong>. It is an architectural style for designing network-based services.</p>

<p>REST uses standard web technologies, particularly HTTP, to allow clients and servers to communicate using resources and operations.</p>

<p>REST is not a programming language or a specific software tool. It is a set of architectural principles used to design APIs.</p>

<hr>

<h2>3. What is a REST API?</h2>

<p>A <strong>REST API</strong> is an API designed according to REST architectural principles. It exposes resources through URLs and uses HTTP methods to perform operations on those resources.</p>

<p>For example, an API may expose a user resource through:</p>

<pre><code>GET https://example.com/api/users</code></pre>

<p>The server can return a JSON response containing user information.</p>

<hr>

<h2>4. Why are REST APIs Important in Testing?</h2>

<p>REST API testing allows testers to validate backend functionality directly. API testing can be performed before, alongside, or independently of UI testing.</p>

<ul>

<li>Validates backend functionality.</li>

<li>Tests business logic independently of the UI.</li>

<li>Helps identify server-side defects.</li>

<li>Provides faster feedback than many UI tests.</li>

<li>Can validate request and response data.</li>

<li>Supports automated testing.</li>

<li>Helps test microservices and integrations.</li>

<li>Can be integrated with CI/CD pipelines.</li>

<li>Can be combined with Selenium UI automation.</li>

<li>Allows negative and boundary testing.</li>

</ul>

<hr>

<h2>5. REST API Architecture</h2>

<p>A typical REST API architecture contains a client, API/server layer, business logic, database, and external services.</p>

<pre><code>Client

   |

   | HTTP Request

   v

REST API Endpoint

   |

   v

Controller / Route

   |

   v

Business Logic

   |

   v

Database / External Service

   |

   v

Response

   |

   v

Client</code></pre>

<hr>

<h2>6. Client and Server</h2>

<p>The <strong>client</strong> is the application that sends requests to the server. The <strong>server</strong> receives requests, processes them, and returns responses.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Component</th><th>Responsibility</th></tr>

<tr><td>Client</td><td>Sends requests and consumes responses</td></tr>

<tr><td>Server</td><td>Processes requests and generates responses</td></tr>

<tr><td>API</td><td>Defines the communication interface</td></tr>

<tr><td>Database</td><td>Stores application data</td></tr>

</table>

<hr>

<h2>7. REST Resources</h2>

<p>In REST, information is represented as <strong>resources</strong>. A resource can represent a user, product, order, employee, customer, payment, or another business entity.</p>

<p>For example:</p>

<pre><code>/users

/products

/orders

/customers

/payments</code></pre>

<p>Each resource can have a unique URL or endpoint.</p>

<hr>

<h2>8. REST API Endpoint</h2>

<p>An <strong>endpoint</strong> is a specific URL through which a client can interact with an API resource.</p>

<p>Example:</p>

<pre><code>https://example.com/api/users</code></pre>

<p>Specific user:</p>

<pre><code>https://example.com/api/users/101</code></pre>

<p>Here, <strong>/users</strong> represents the resource and <strong>/101</strong> identifies a particular user.</p>

<hr>

<h2>9. HTTP Protocol</h2>

<p>REST APIs commonly use the <strong>HTTP (HyperText Transfer Protocol)</strong> protocol for communication between clients and servers.</p>

<p>HTTP defines methods, headers, status codes, and other mechanisms used to communicate between systems.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>HTTP Concept</th><th>Purpose</th></tr>

<tr><td>Method</td><td>Defines the requested operation</td></tr>

<tr><td>URL</td><td>Identifies the resource</td></tr>

<tr><td>Headers</td><td>Provide additional request or response information</td></tr>

<tr><td>Body</td><td>Contains request or response data</td></tr>

<tr><td>Status Code</td><td>Indicates the result of the request</td></tr>

</table>

<hr>

<h2>10. HTTP Methods</h2>

<p>The most commonly used HTTP methods in REST APIs are:</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Method</th><th>Common Purpose</th></tr>

<tr><td>GET</td><td>Retrieve data</td></tr>

<tr><td>POST</td><td>Create a resource or submit data</td></tr>

<tr><td>PUT</td><td>Replace or update a resource</td></tr>

<tr><td>PATCH</td><td>Partially update a resource</td></tr>

<tr><td>DELETE</td><td>Delete a resource</td></tr>

</table>

<hr>

<h2>11. GET Request</h2>

<p>The <strong>GET</strong> method is commonly used to retrieve information from a server.</p>

<pre><code>GET /api/users</code></pre>

<p>Example:</p>

<pre><code>GET https://example.com/api/users</code></pre>

<p>A successful response may contain a list of users.</p>

<hr>

<h2>12. GET Request for a Specific Resource</h2>

<p>A GET request can retrieve a specific resource by including an identifier in the URL.</p>

<pre><code>GET /api/users/101</code></pre>

<p>This request asks the server for the user whose identifier is <strong>101</strong>.</p>

<hr>

<h2>13. POST Request</h2>

<p>The <strong>POST</strong> method is commonly used to submit data to the server and create a new resource.</p>

<pre><code>POST /api/users</code></pre>

<p>Example JSON request body:</p>

<pre><code>{

  "name": "John",

  "email": "[email protected]",

  "role": "tester"

}</code></pre>

<hr>

<h2>14. PUT Request</h2>

<p>The <strong>PUT</strong> method is commonly used to replace or update an existing resource.</p>

<pre><code>PUT /api/users/101</code></pre>

<p>Example:</p>

<pre><code>{

  "name": "John Updated",

  "email": "[email protected]",

  "role": "tester"

}</code></pre>

<hr>

<h2>15. PATCH Request</h2>

<p>The <strong>PATCH</strong> method is commonly used when only part of an existing resource needs to be updated.</p>

<pre><code>PATCH /api/users/101</code></pre>

<p>Example:</p>

<pre><code>{

  "role": "admin"

}</code></pre>

<p>Unlike a full replacement, PATCH is generally used for partial modifications.</p>

<hr>

<h2>16. DELETE Request</h2>

<p>The <strong>DELETE</strong> method is used to request deletion of a resource.</p>

<pre><code>DELETE /api/users/101</code></pre>

<p>The server may return a success status indicating that the resource was deleted or that the deletion request was accepted.</p>

<hr>

<h2>17. CRUD Operations</h2>

<p>REST APIs are commonly associated with CRUD operations.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>CRUD</th><th>HTTP Method</th><th>Example</th></tr>

<tr><td>Create</td><td>POST</td><td>POST /users</td></tr>

<tr><td>Read</td><td>GET</td><td>GET /users/101</td></tr>

<tr><td>Update</td><td>PUT/PATCH</td><td>PUT /users/101</td></tr>

<tr><td>Delete</td><td>DELETE</td><td>DELETE /users/101</td></tr>

</table>

<hr>

<h2>18. API Request</h2>

<p>An API request is the message sent by a client to a server.</p>

<p>A request can contain:</p>

<ul>

<li>HTTP method.</li>

<li>URL or endpoint.</li>

<li>Path parameters.</li>

<li>Query parameters.</li>

<li>Headers.</li>

<li>Authentication information.</li>

<li>Request body.</li>

</ul>

<pre><code>POST /api/users

Content-Type: application/json

Authorization: Bearer &lt;token&gt;

 

{

  "name": "John",

  "email": "[email protected]"

}</code></pre>

<hr>

<h2>19. API Response</h2>

<p>An API response is the message returned by the server after processing a request.</p>

<p>A response can contain:</p>

<ul>

<li>Status code.</li>

<li>Response headers.</li>

<li>Response body.</li>

<li>Error information.</li>

<li>Metadata.</li>

</ul>

<hr>

<h2>20. HTTP Status Codes</h2>

<p>HTTP status codes indicate the result of an HTTP request.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Status Code</th><th>Meaning</th><th>Common Usage</th></tr>

<tr><td>200</td><td>OK</td><td>Successful request</td></tr>

<tr><td>201</td><td>Created</td><td>Resource successfully created</td></tr>

<tr><td>202</td><td>Accepted</td><td>Request accepted for processing</td></tr>

<tr><td>204</td><td>No Content</td><td>Successful response without response body</td></tr>

<tr><td>400</td><td>Bad Request</td><td>Invalid request</td></tr>

<tr><td>401</td><td>Unauthorized</td><td>Authentication required or invalid</td></tr>

<tr><td>403</td><td>Forbidden</td><td>Request understood but not permitted</td></tr>

<tr><td>404</td><td>Not Found</td><td>Resource or endpoint not found</td></tr>

<tr><td>405</td><td>Method Not Allowed</td><td>HTTP method not supported for the resource</td></tr>

<tr><td>409</td><td>Conflict</td><td>Request conflicts with current resource state</td></tr>

<tr><td>500</td><td>Internal Server Error</td><td>Unexpected server-side error</td></tr>

<tr><td>502</td><td>Bad Gateway</td><td>Gateway received an invalid upstream response</td></tr>

<tr><td>503</td><td>Service Unavailable</td><td>Service temporarily unavailable</td></tr>

</table>

<hr>

<h2>21. JSON in REST APIs</h2>

<p><strong>JSON (JavaScript Object Notation)</strong> is one of the most commonly used formats for exchanging structured data through REST APIs.</p>

<p>Example:</p>

<pre><code>{

  "id": 101,

  "name": "John",

  "email": "[email protected]",

  "active": true

}</code></pre>

<p>JSON represents information using objects, arrays, strings, numbers, booleans, and null values.</p>

<hr>

<h2>22. JSON Object</h2>

<p>A JSON object contains key-value pairs.</p>

<pre><code>{

  "name": "John",

  "age": 30,

  "active": true

}</code></pre>

<p>Here:</p>

<ul>

<li><strong>name</strong> is a key with a string value.</li>

<li><strong>age</strong> is a key with a numeric value.</li>

<li><strong>active</strong> is a key with a boolean value.</li>

</ul>

<hr>

<h2>23. JSON Array</h2>

<p>A JSON array contains multiple values or objects.</p>

<pre><code>{

  "users": [

    {

      "id": 1,

      "name": "John"

    },

    {

      "id": 2,

      "name": "David"

    }

  ]

}</code></pre>

<hr>

<h2>24. Request Headers</h2>

<p>HTTP headers provide additional information about a request.</p>

<p>Common request headers include:</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Header</th><th>Purpose</th></tr>

<tr><td>Content-Type</td><td>Specifies the format of the request body</td></tr>

<tr><td>Accept</td><td>Indicates acceptable response formats</td></tr>

<tr><td>Authorization</td><td>Provides authentication credentials or token</td></tr>

<tr><td>User-Agent</td><td>Identifies the client software</td></tr>

</table>

<hr>

<h2>25. Content-Type Header</h2>

<p>The <strong>Content-Type</strong> header tells the server what format is being sent in the request body.</p>

<p>For JSON:</p>

<pre><code>Content-Type: application/json</code></pre>

<p>Example:</p>

<pre><code>POST /api/users

Content-Type: application/json

 

{

  "name": "John"

}</code></pre>

<hr>

<h2>26. Accept Header</h2>

<p>The <strong>Accept</strong> header indicates the response formats that the client can process.</p>

<pre><code>Accept: application/json</code></pre>

<p>This is commonly used when the client expects a JSON response.</p>

<hr>

<h2>27. Authentication in REST APIs</h2>

<p>Many APIs require authentication to ensure that only authorized clients can access protected resources.</p>

<p>Common authentication mechanisms include:</p>

<ul>

<li>Basic Authentication.</li>

<li>API Keys.</li>

<li>Bearer Tokens.</li>

<li>OAuth 2.0.</li>

<li>JWT-based authentication.</li>

</ul>

<hr>

<h2>28. Bearer Token Authentication</h2>

<p>A bearer token is commonly sent through the Authorization header.</p>

<pre><code>Authorization: Bearer &lt;access-token&gt;</code></pre>

<p>Example request:</p>

<pre><code>GET /api/profile

Authorization: Bearer abc123token</code></pre>

<p>Real access tokens should be handled securely and should not be exposed in source code or test reports.</p>

<hr>

<h2>29. API Key Authentication</h2>

<p>Some APIs require an API key to identify or authorize the client.</p>

<p>An API key may be supplied through a header such as:</p>

<pre><code>X-API-Key: &lt;api-key&gt;</code></pre>

<p>The exact header name and authentication process depend on the API design.</p>

<hr>

<h2>30. Path Parameters</h2>

<p>A path parameter identifies a specific resource within the URL.</p>

<pre><code>GET /api/users/101</code></pre>

<p>Here, <strong>101</strong> is the user identifier.</p>

<p>Another example:</p>

<pre><code>GET /api/products/5001</code></pre>

<hr>

<h2>31. Query Parameters</h2>

<p>Query parameters are commonly used to filter, search, sort, or paginate resources.</p>

<pre><code>GET /api/products?category=electronics</code></pre>

<p>Multiple query parameters can be supplied:</p>

<pre><code>GET /api/products?category=electronics&amp;sort=price&amp;page=2</code></pre>

<hr>

<h2>32. Path Parameter vs Query Parameter</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Path Parameter</th><th>Query Parameter</th></tr>

<tr><td>Purpose</td><td>Identify a resource</td><td>Filter or modify a request</td></tr>

<tr><td>Example</td><td>/users/101</td><td>/users?role=admin</td></tr>

<tr><td>Common Usage</td><td>Specific resource</td><td>Search/filter/sort/pagination</td></tr>

</table>

<hr>

<h2>33. Request Body</h2>

<p>The request body contains data sent to the server, particularly for methods such as POST, PUT, and PATCH.</p>

<pre><code>{

  "name": "John",

  "email": "[email protected]",

  "role": "tester"

}</code></pre>

<hr>

<h2>34. Response Body</h2>

<p>The response body contains data returned by the server.</p>

<pre><code>{

  "id": 101,

  "name": "John",

  "email": "[email protected]",

  "role": "tester"

}</code></pre>

<hr>

<h2>35. Statelessness in REST</h2>

<p>One important REST principle is <strong>statelessness</strong>. Each request should contain the information necessary for the server to process that request.</p>

<p>The server should not depend on hidden client-session state to understand the meaning of an individual request.</p>

<pre><code>Request 1

Client ----------------> Server

 

Request 2

Client ----------------> Server

 

Request 3

Client ----------------> Server

 

Each request contains the information

needed to process that request.</code></pre>

<hr>

<h2>36. REST API URL Structure</h2>

<p>A typical REST API URL may contain a base URL, API version, resource, identifier, and query parameters.</p>

<pre><code>https://example.com/api/v1/users/101?active=true</code></pre>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Part</th><th>Example</th></tr>

<tr><td>Protocol</td><td>https</td></tr>

<tr><td>Host</td><td>example.com</td></tr>

<tr><td>Base Path</td><td>/api</td></tr>

<tr><td>Version</td><td>/v1</td></tr>

<tr><td>Resource</td><td>/users</td></tr>

<tr><td>Identifier</td><td>/101</td></tr>

<tr><td>Query Parameter</td><td>?active=true</td></tr>

</table>

<hr>

<h2>37. API Versioning</h2>

<p>API versioning allows an API provider to introduce changes while maintaining compatibility with existing clients.</p>

<p>A common URL-based approach is:</p>

<pre><code>/api/v1/users

/api/v2/users</code></pre>

<p>Other versioning strategies can use headers or other mechanisms depending on the API design.</p>

<hr>

<h2>38. Idempotency</h2>

<p><strong>Idempotency</strong> describes whether repeating the same request has the same intended effect as making it once.</p>

<p>GET, PUT, and DELETE are generally designed to be idempotent according to HTTP semantics, while POST is generally not idempotent.</p>

<p>Actual application behavior should still be verified against the API's documented contract.</p>

<hr>

<h2>39. Safe HTTP Methods</h2>

<p>Some HTTP methods are defined as <strong>safe</strong>, meaning they are intended for read-only operations and should not request a state-changing action.</p>

<p>GET is the most common safe method.</p>

<pre><code>GET /api/products</code></pre>

<hr>

<h2>40. REST API Testing</h2>

<p><strong>REST API testing</strong> involves sending requests to API endpoints and validating the resulting responses.</p>

<p>Typical validation areas include:</p>

<ul>

<li>Status code.</li>

<li>Response body.</li>

<li>Response headers.</li>

<li>Response schema.</li>

<li>Response time.</li>

<li>Business rules.</li>

<li>Authentication.</li>

<li>Authorization.</li>

<li>Error handling.</li>

<li>Data consistency.</li>

</ul>

<hr>

<h2>41. API Testing Flow</h2>

<pre><code>Identify API Endpoint

        |

        v

Select HTTP Method

        |

        v

Prepare Headers

        |

        v

Prepare Authentication

        |

        v

Prepare Request Parameters

        |

        v

Prepare Request Body

        |

        v

Send Request

        |

        v

Receive Response

        |

        v

Validate Status Code

        |

        v

Validate Response Body

        |

        v

Validate Headers / Schema

        |

        v

Generate Test Result</code></pre>

<hr>

<h2>42. Positive API Testing</h2>

<p>Positive testing verifies that the API behaves correctly when valid input is provided.</p>

<p>Example:</p>

<pre><code>POST /api/users

 

{

  "name": "John",

  "email": "[email protected]"

}</code></pre>

<p>Possible expected result:</p>

<pre><code>Status: 201 Created</code></pre>

<hr>

<h2>43. Negative API Testing</h2>

<p>Negative testing verifies how the API handles invalid, incomplete, unauthorized, or unexpected input.</p>

<p>Example:</p>

<pre><code>POST /api/users

 

{

  "email": "invalid-email"

}</code></pre>

<p>The API may return an appropriate client-error response according to its contract.</p>

<hr>

<h2>44. Boundary Testing in APIs</h2>

<p>Boundary testing checks values at or around important limits.</p>

<p>For example, if a username has a maximum length of 50 characters, test cases can include:</p>

<ul>

<li>49 characters.</li>

<li>50 characters.</li>

<li>51 characters.</li>

<li>Empty value.</li>

<li>Null value where applicable.</li>

</ul>

<hr>

<h2>45. API Validation</h2>

<p>API validation verifies that the response satisfies the expected contract.</p>

<p>Common validations include:</p>

<pre><code>HTTP Status Code

        +

Response Headers

        +

Response Body

        +

JSON Fields

        +

Data Types

        +

Business Rules

        =

API Validation</code></pre>

<hr>

<h2>46. Response Body Validation</h2>

<p>Suppose an API returns:</p>

<pre><code>{

  "id": 101,

  "name": "John",

  "active": true

}</code></pre>

<p>Tests can validate:</p>

<ul>

<li>id exists.</li>

<li>id is numeric.</li>

<li>name is present.</li>

<li>active is boolean.</li>

<li>Values satisfy the expected business rules.</li>

</ul>

<hr>

<h2>47. JSON Schema Validation</h2>

<p>Schema validation verifies that a response follows the expected structural contract.</p>

<p>A schema can define expected properties and data types.</p>

<pre><code>{

  "id": 101,

  "name": "John",

  "active": true

}</code></pre>

<p>For example, a test can verify that:</p>

<ul>

<li>id is a number.</li>

<li>name is a string.</li>

<li>active is a boolean.</li>

</ul>

<hr>

<h2>48. API Testing Tools</h2>

<p>Several tools can be used to develop and execute REST API tests.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Tool</th><th>Common Usage</th></tr>

<tr><td>Postman</td><td>Manual and automated API testing</td></tr>

<tr><td>cURL</td><td>Command-line HTTP requests</td></tr>

<tr><td>Rest Assured</td><td>Java-based API automation</td></tr>

<tr><td>SoapUI</td><td>API testing and service testing</td></tr>

<tr><td>JMeter</td><td>Performance and load testing</td></tr>

<tr><td>Swagger/OpenAPI tools</td><td>API documentation and exploration</td></tr>

</table>

<hr>

<h2>49. Postman Basics</h2>

<p><strong>Postman</strong> is a popular tool for creating, sending, and validating API requests.</p>

<p>A typical Postman request can contain:</p>

<ul>

<li>HTTP method.</li>

<li>Request URL.</li>

<li>Query parameters.</li>

<li>Headers.</li>

<li>Authorization.</li>

<li>Request body.</li>

<li>Tests.</li>

</ul>

<p>Example:</p>

<pre><code>GET https://example.com/api/users</code></pre>

<hr>

<h2>50. cURL Basics</h2>

<p><strong>cURL</strong> is a command-line utility that can send HTTP requests.</p>

<p>Example GET request:</p>

<pre><code>curl -X GET "https://example.com/api/users"</code></pre>

<p>Example POST request:</p>

<pre><code>curl -X POST "https://example.com/api/users" \

-H "Content-Type: application/json" \

-d '{"name":"John","email":"[email protected]"}'</code></pre>

<hr>

<h2>51. REST Assured</h2>

<p><strong>REST Assured</strong> is a Java library commonly used to automate REST API testing.</p>

<p>It can be integrated with testing frameworks such as TestNG and JUnit.</p>

<p>REST Assured supports request creation, response validation, JSON processing, authentication, headers, parameters, and assertions.</p>

<hr>

<h2>52. REST Assured GET Example</h2>

<pre><code>import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;

 

import org.testng.annotations.Test;

 

public class GetUserTest {

 

    @Test

    public void getUser() {

 

        given()

        .when()

            .get("https://example.com/api/users/101")

        .then()

            .statusCode(200);

    }

}</code></pre>

<hr>

<h2>53. REST Assured POST Example</h2>

<pre><code>import static io.restassured.RestAssured.*;

 

import org.testng.annotations.Test;

 

public class CreateUserTest {

 

    @Test

    public void createUser() {

 

        String requestBody = """

        {

            "name": "John",

            "email": "[email protected]"

        }

        """;

 

        given()

            .contentType("application/json")

            .body(requestBody)

        .when()

            .post("https://example.com/api/users")

        .then()

            .statusCode(201);

    }

}</code></pre>

<hr>

<h2>54. REST Assured Response Validation</h2>

<p>REST Assured can validate response status codes and JSON fields.</p>

<pre><code>given()

.when()

    .get("https://example.com/api/users/101")

.then()

    .statusCode(200)

    .body("id", equalTo(101));</code></pre>

<p>This approach allows API tests to verify both HTTP behavior and response content.</p>

<hr>

<h2>55. Given-When-Then Structure</h2>

<p>REST Assured commonly uses a readable <strong>Given-When-Then</strong> structure.</p>

<pre><code>given()

    // Request setup

 

.when()

    // Send request

 

.then()

    // Validate response</code></pre>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Section</th><th>Purpose</th></tr>

<tr><td>given()</td><td>Prepare request</td></tr>

<tr><td>when()</td><td>Execute request</td></tr>

<tr><td>then()</td><td>Validate response</td></tr>

</table>

<hr>

<h2>56. Query Parameters with REST Assured</h2>

<pre><code>given()

    .queryParam("category", "electronics")

    .queryParam("page", 2)

.when()

    .get("https://example.com/api/products")

.then()

    .statusCode(200);</code></pre>

<hr>

<h2>57. Path Parameters with REST Assured</h2>

<pre><code>given()

    .pathParam("id", 101)

.when()

    .get("https://example.com/api/users/{id}")

.then()

    .statusCode(200);</code></pre>

<hr>

<h2>58. Headers with REST Assured</h2>

<pre><code>given()

    .header("Accept", "application/json")

    .header("Content-Type", "application/json")

.when()

    .get("https://example.com/api/users")

.then()

    .statusCode(200);</code></pre>

<hr>

<h2>59. Authentication with REST Assured</h2>

<p>REST Assured supports different authentication mechanisms depending on the API.</p>

<p>Example of bearer-token authentication:</p>

<pre><code>given()

    .header("Authorization", "Bearer " + token)

.when()

    .get("https://example.com/api/profile")

.then()

    .statusCode(200);</code></pre>

<p>Tokens should be stored and managed securely rather than hard-coded in source-controlled test code.</p>

<hr>

<h2>60. REST API Testing with TestNG</h2>

<p>REST Assured can be combined with TestNG to create structured API automation suites.</p>

<pre><code>import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;

 

import org.testng.annotations.Test;

 

public class UserApiTest {

 

    @Test

    public void verifyUser() {

 

        given()

        .when()

            .get("https://example.com/api/users/101")

        .then()

            .statusCode(200)

            .body("id", equalTo(101));

    }

}</code></pre>

<hr>

<h2>61. REST API Testing with Data Providers</h2>

<p>TestNG Data Providers can be combined with REST Assured to execute the same API test against multiple data sets.</p>

<pre><code>import static io.restassured.RestAssured.*;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class ApiDataDrivenTest {

 

    @DataProvider(name = "users")

    public Object[][] users() {

        return new Object[][] {

            {101},

            {102},

            {103}

        };

    }

 

    @Test(dataProvider = "users")

    public void getUserTest(int userId) {

 

        given()

        .when()

            .get("https://example.com/api/users/" + userId)

        .then()

            .statusCode(200);

    }

}</code></pre>

<hr>

<h2>62. API Testing with Selenium</h2>

<p>Selenium primarily automates web browsers and user-interface interactions, while REST API tools such as REST Assured are used to test backend API behavior.</p>

<p>Both approaches can be combined in an automation framework.</p>

<pre><code>API Layer

   |

   | Create Test Data

   v

REST API

   |

   v

Database / Application

   |

   v

Selenium UI

   |

   v

Verify User Interface</code></pre>

<p>For example, an API can create a user before Selenium opens the application and verifies that the user appears correctly in the UI.</p>

<hr>

<h2>63. API Testing vs UI Testing</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>API Testing</th><th>UI Testing</th></tr>

<tr><td>Layer</td><td>Backend/service layer</td><td>User interface</td></tr>

<tr><td>Browser Required</td><td>Usually no</td><td>Usually yes</td></tr>

<tr><td>Execution Speed</td><td>Generally faster</td><td>Generally slower</td></tr>

<tr><td>Validation</td><td>Requests and responses</td><td>Visible application behavior</td></tr>

<tr><td>Typical Tools</td><td>REST Assured, Postman</td><td>Selenium</td></tr>

<tr><td>Best Use</td><td>Backend and integration validation</td><td>End-user workflow validation</td></tr>

</table>

<hr>

<h2>64. API Testing vs Selenium Testing</h2>

<p>Selenium and API testing complement each other rather than performing exactly the same role.</p>

<pre><code>API Testing

    |

    +-- Backend Validation

    +-- Request Validation

    +-- Response Validation

    +-- Business Logic

 

Selenium Testing

    |

    +-- Browser Automation

    +-- UI Validation

    +-- User Workflow

    +-- Visual Interaction</code></pre>

<hr>

<h2>65. API Chaining</h2>

<p><strong>API chaining</strong> means using data returned from one API request as input for another API request.</p>

<pre><code>Create User

    |

    v

Receive User ID

    |

    v

Get User Details

    |

    v

Update User

    |

    v

Delete User</code></pre>

<p>For example, the ID returned from a POST request can be used in a subsequent GET, PUT, or DELETE request.</p>

<hr>

<h2>66. API Workflow Testing</h2>

<p>A real application may require multiple API operations to be performed in sequence.</p>

<pre><code>Login API

    |

    v

Receive Token

    |

    v

Get Products

    |

    v

Create Order

    |

    v

Get Order

    |

    v

Cancel Order</code></pre>

<p>Testing such workflows helps verify that multiple API operations work correctly together.</p>

<hr>

<h2>67. API Response Time</h2>

<p>API tests can also validate response-time expectations when performance requirements are defined.</p>

<pre><code>Request

   |

   v

Start Timer

   |

   v

API Processing

   |

   v

Response

   |

   v

Stop Timer

   |

   v

Validate Response Time</code></pre>

<p>Response-time checks should be based on documented requirements rather than arbitrary values.</p>

<hr>

<h2>68. API Error Handling</h2>

<p>A good API should return meaningful responses when requests fail.</p>

<p>Common scenarios include:</p>

<ul>

<li>Invalid input.</li>

<li>Missing required field.</li>

<li>Invalid authentication.</li>

<li>Insufficient authorization.</li>

<li>Resource not found.</li>

<li>Duplicate data.</li>

<li>Unsupported HTTP method.</li>

<li>Server-side failure.</li>

</ul>

<hr>

<h2>69. API Security Testing Basics</h2>

<p>API security testing checks whether APIs properly protect sensitive resources and enforce authentication and authorization requirements.</p>

<p>Basic areas include:</p>

<ul>

<li>Authentication validation.</li>

<li>Authorization validation.</li>

<li>Token handling.</li>

<li>Input validation.</li>

<li>Sensitive-data exposure.</li>

<li>Access control.</li>

<li>HTTPS usage.</li>

<li>Rate limiting where applicable.</li>

</ul>

<p>Security testing should be performed only in authorized environments.</p>

<hr>

<h2>70. Common API Testing Scenarios</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Scenario</th><th>Example</th></tr>

<tr><td>Valid Request</td><td>Valid user data</td></tr>

<tr><td>Invalid Request</td><td>Missing required field</td></tr>

<tr><td>Authentication</td><td>Valid/invalid token</td></tr>

<tr><td>Authorization</td><td>User accessing restricted resource</td></tr>

<tr><td>Not Found</td><td>Invalid resource ID</td></tr>

<tr><td>Duplicate Data</td><td>Existing unique value</td></tr>

<tr><td>Boundary</td><td>Minimum/maximum values</td></tr>

<tr><td>Response Validation</td><td>Status and JSON fields</td></tr>

<tr><td>Performance</td><td>Response-time requirement</td></tr>

</table>

<hr>

<h2>71. Common REST API Mistakes</h2>

<ul>

<li>Using the wrong HTTP method.</li>

<li>Using an incorrect endpoint.</li>

<li>Sending invalid JSON.</li>

<li>Missing required headers.</li>

<li>Using incorrect authentication.</li>

<li>Ignoring HTTP status codes.</li>

<li>Validating only that a response exists.</li>

<li>Not validating response content.</li>

<li>Hard-coding credentials or tokens.</li>

<li>Not testing negative scenarios.</li>

<li>Ignoring API documentation.</li>

<li>Sharing production secrets in test code or reports.</li>

</ul>

<hr>

<h2>72. Best Practices for REST API Testing</h2>

<ul>

<li>Understand the API contract before writing tests.</li>

<li>Use meaningful endpoint and test names.</li>

<li>Validate status codes.</li>

<li>Validate important response fields.</li>

<li>Validate response structure and schema where appropriate.</li>

<li>Test both positive and negative scenarios.</li>

<li>Use reusable request specifications.</li>

<li>Separate test data from test logic.</li>

<li>Use environment-specific configuration.</li>

<li>Never expose sensitive credentials in reports.</li>

<li>Use API automation in CI/CD pipelines.</li>

<li>Keep API tests independent whenever practical.</li>

<li>Use data-driven testing for multiple input combinations.</li>

<li>Combine API and UI automation when end-to-end validation requires both layers.</li>

</ul>

<hr>

<h2>73. REST API Test Project Structure</h2>

<pre><code>src

|-- test

    |-- java

        |-- tests

        |   |-- UserApiTest.java

        |   |-- ProductApiTest.java

        |   |-- OrderApiTest.java

        |

        |-- requests

        |   |-- UserRequest.java

        |   |-- ProductRequest.java

        |

        |-- utilities

        |   |-- ConfigReader.java

        |   |-- JsonUtils.java

        |   |-- TokenManager.java

        |

        |-- data

        |   |-- UserDataProvider.java

        |   |-- ProductDataProvider.java

        |

        |-- models

            |-- User.java

            |-- Product.java</code></pre>

<hr>

<h2>74. Complete REST API Testing Flow</h2>

<pre><code>Test Data

    |

    v

TestNG / JUnit

    |

    v

REST Assured

    |

    v

Request Specification

    |

    v

HTTP Request

    |

    v

REST API

    |

    v

Application / Database

    |

    v

HTTP Response

    |

    v

Status Validation

    |

    v

Body Validation

    |

    v

Schema Validation

    |

    v

Test Report</code></pre>

<hr>

<h2>75. Practical REST API Example</h2>

<p>Consider a user-management API that supports creating and retrieving users.</p>

<p><strong>Step 1: Create User</strong></p>

<pre><code>POST /api/users

 

{

  "name": "John",

  "email": "[email protected]"

}</code></pre>

<p><strong>Step 2: Receive Response</strong></p>

<pre><code>{

  "id": 101,

  "name": "John",

  "email": "[email protected]"

}</code></pre>

<p><strong>Step 3: Retrieve User</strong></p>

<pre><code>GET /api/users/101</code></pre>

<p><strong>Step 4: Validate Response</strong></p>

<pre><code>Status Code = 200

id = 101

name = John

email = [email protected]</code></pre>

<hr>

<h2>76. Practical Selenium + REST API Scenario</h2>

<p>Suppose an automation framework needs to test an e-commerce application.</p>

<pre><code>REST API

   |

   | Create Test User

   v

User Created

   |

   | Selenium

   v

Open Website

   |

   v

Login

   |

   v

Search Product

   |

   v

Add Product to Cart

   |

   v

Checkout

   |

   v

Verify Order</code></pre>

<p>This approach can reduce unnecessary UI setup and allow API testing and UI testing to complement each other.</p>

<hr>

<h2>77. REST API and CI/CD</h2>

<p>API automation can be executed as part of a CI/CD pipeline.</p>

<pre><code>Developer Commit

       |

       v

Build

       |

       v

Unit Tests

       |

       v

API Tests

       |

       v

UI Automation

       |

       v

Reports

       |

       v

Deployment</code></pre>

<p>API tests are often useful early in the pipeline because they can validate service behavior without requiring a browser.</p>

<hr>

<h2>78. REST API and Test Reports</h2>

<p>API automation frameworks can generate test reports containing information such as:</p>

<ul>

<li>Test name.</li>

<li>Endpoint.</li>

<li>HTTP method.</li>

<li>Status code.</li>

<li>Pass/fail result.</li>

<li>Response validation result.</li>

<li>Execution duration.</li>

<li>Error details.</li>

</ul>

<p>Sensitive request or response information should be masked or excluded from reports when necessary.</p>

<hr>

<h2>79. REST API vs SOAP</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>REST</th><th>SOAP</th></tr>

<tr><td>Type</td><td>Architectural style</td><td>Protocol</td></tr>

<tr><td>Common Data Format</td><td>Often JSON</td><td>Often XML</td></tr>

<tr><td>Transport</td><td>Commonly HTTP/HTTPS</td><td>Commonly HTTP/HTTPS and other transports</td></tr>

<tr><td>Complexity</td><td>Generally lightweight</td><td>Generally more formal and specification-heavy</td></tr>

<tr><td>Usage</td><td>Web APIs and modern services</td><td>Enterprise/service integrations</td></tr>

</table>

<hr>

<h2>80. Interview Questions on REST API Basics</h2>

<h3>1. What is an API?</h3>

<p>An API is an interface that allows software applications or services to communicate with each other.</p>

<h3>2. What does REST stand for?</h3>

<p>REST stands for Representational State Transfer.</p>

<h3>3. What is a REST API?</h3>

<p>A REST API is an API designed using REST architectural principles and commonly accessed through HTTP.</p>

<h3>4. What are the common HTTP methods?</h3>

<p>GET, POST, PUT, PATCH, and DELETE are commonly used HTTP methods.</p>

<h3>5. What is GET used for?</h3>

<p>GET is generally used to retrieve resources.</p>

<h3>6. What is POST used for?</h3>

<p>POST is commonly used to submit data and create resources.</p>

<h3>7. What is the difference between PUT and PATCH?</h3>

<p>PUT is generally used for replacing a resource representation, while PATCH is generally used for partial modification.</p>

<h3>8. What is a REST API endpoint?</h3>

<p>An endpoint is a URL through which a client interacts with an API resource.</p>

<h3>9. What is JSON?</h3>

<p>JSON is a lightweight data-interchange format commonly used for REST API requests and responses.</p>

<h3>10. What is an HTTP status code?</h3>

<p>An HTTP status code indicates the result of an HTTP request.</p>

<h3>11. What does status code 200 mean?</h3>

<p>200 indicates that the request was successfully processed.</p>

<h3>12. What does status code 201 mean?</h3>

<p>201 indicates that a resource was successfully created.</p>

<h3>13. What does status code 400 mean?</h3>

<p>400 indicates that the server could not process the request because of invalid request information.</p>

<h3>14. What does status code 401 mean?</h3>

<p>401 indicates that authentication is required or the supplied authentication is not valid.</p>

<h3>15. What does status code 404 mean?</h3>

<p>404 indicates that the requested resource or endpoint could not be found.</p>

<h3>16. What is API testing?</h3>

<p>API testing validates API requests, responses, business rules, authentication, status codes, and data behavior.</p>

<h3>17. What is REST Assured?</h3>

<p>REST Assured is a Java library used for automating REST API tests.</p>

<h3>18. Can REST Assured be used with TestNG?</h3>

<p>Yes. REST Assured can be integrated with TestNG to create Java-based API automation suites.</p>

<h3>19. What is API chaining?</h3>

<p>API chaining is the process of using output from one API request as input for another request.</p>

<h3>20. Can Selenium and API testing be used together?</h3>

<p>Yes. Selenium can validate UI workflows while API automation validates backend services, and both can be combined in an end-to-end automation framework.</p>

<hr>

<h2>81. Quick Reference Table</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Concept</th><th>Description</th></tr>

<tr><td>API</td><td>Interface for software communication</td></tr>

<tr><td>REST</td><td>Architectural style for network-based services</td></tr>

<tr><td>Endpoint</td><td>URL used to access an API resource</td></tr>

<tr><td>GET</td><td>Retrieve data</td></tr>

<tr><td>POST</td><td>Create or submit data</td></tr>

<tr><td>PUT</td><td>Replace/update a resource</td></tr>

<tr><td>PATCH</td><td>Partially update a resource</td></tr>

<tr><td>DELETE</td><td>Delete a resource</td></tr>

<tr><td>JSON</td><td>Common data format for API communication</td></tr>

<tr><td>Header</td><td>Additional HTTP request/response information</td></tr>

<tr><td>Status Code</td><td>Indicates request result</td></tr>

<tr><td>Path Parameter</td><td>Identifies a resource in the URL path</td></tr>

<tr><td>Query Parameter</td><td>Filters or modifies a request</td></tr>

<tr><td>REST Assured</td><td>Java library for REST API automation</td></tr>

<tr><td>Postman</td><td>Tool for API development and testing</td></tr>

</table>

<hr>

<h2>82. Learning Roadmap for REST API Testing</h2>

<ol>

<li>Understand HTTP and HTTPS.</li>

<li>Learn API and REST fundamentals.</li>

<li>Understand resources and endpoints.</li>

<li>Learn GET, POST, PUT, PATCH, and DELETE.</li>

<li>Understand request and response structure.</li>

<li>Learn HTTP status codes.</li>

<li>Learn request and response headers.</li>

<li>Understand JSON objects and arrays.</li>

<li>Learn path and query parameters.</li>

<li>Understand API authentication.</li>

<li>Practice APIs using Postman.</li>

<li>Learn cURL basics.</li>

<li>Learn REST Assured.</li>

<li>Integrate REST Assured with TestNG.</li>

<li>Implement data-driven API testing.</li>

<li>Implement response assertions.</li>

<li>Learn schema validation.</li>

<li>Implement API chaining.</li>

<li>Combine API and Selenium testing.</li>

<li>Integrate API tests with Maven and CI/CD.</li>

</ol>

<hr>

<h2>83. Practical Exercises</h2>

<ol>

<li>Send a GET request and validate the status code.</li>

<li>Send a GET request using a path parameter.</li>

<li>Send a GET request using query parameters.</li>

<li>Create a POST request with JSON data.</li>

<li>Update a resource using PUT.</li>

<li>Partially update a resource using PATCH.</li>

<li>Delete a resource using DELETE.</li>

<li>Validate response headers.</li>

<li>Validate important JSON response fields.</li>

<li>Test invalid request data.</li>

<li>Test invalid authentication.</li>

<li>Create a REST Assured GET automation test.</li>

<li>Create a REST Assured POST automation test.</li>

<li>Integrate REST Assured with TestNG.</li>

<li>Use a Data Provider for multiple API inputs.</li>

<li>Implement API chaining.</li>

<li>Create a reusable API request utility.</li>

<li>Generate API automation reports.</li>

<li>Execute API tests through Maven.</li>

<li>Integrate API tests into a CI/CD pipeline.</li>

</ol>

<hr>

<h2>84. Real-World API Automation Architecture</h2>

<pre><code>Test Data

    |

    v

Data Provider

    |

    v

API Test Class

    |

    v

Request Specification

    |

    v

REST Assured

    |

    v

REST API

    |

    v

Application / Database

    |

    v

Response

    |

    +---- Status Validation

    |

    +---- Header Validation

    |

    +---- Body Validation

    |

    +---- Schema Validation

    |

    +---- Business Validation

    |

    v

Test Report</code></pre>

<hr>

<h2>85. Summary</h2>

<p>REST API is an important technology for communication between modern applications and backend services. REST APIs commonly use HTTP methods such as GET, POST, PUT, PATCH, and DELETE to work with application resources.</p>

<p>For automation testers, understanding REST API basics is valuable because many modern applications depend heavily on backend services. API testing allows testers to validate backend functionality, request and response data, authentication, business rules, error handling, and integrations without relying entirely on the browser interface.</p>

<p>Tools such as Postman, cURL, and REST Assured can be used to work with REST APIs. In Java-based Selenium frameworks, REST Assured can be integrated with TestNG, Data Providers, Maven, reporting systems, and CI/CD pipelines.</p>

<p>API automation and Selenium UI automation can also work together. APIs can be used to prepare or validate test data, while Selenium can validate the corresponding user-interface workflows.</p>

<hr>

<h2>86. Course Resources</h2>

<p>Learn more about Selenium automation, API testing, TestNG, Page Object Model, reporting, and related automation concepts:</p>

<ul>

<li><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a></li>

<li><a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Selenium Course Demo</a></li>

</ul>

<p><strong>Final Takeaway:</strong> REST API knowledge helps automation testers understand and validate the backend services that power modern applications. By combining REST API testing with Selenium, TestNG, REST Assured, data-driven testing, and CI/CD, testers can build broader and more maintainable automation solutions.</p>

</div>

Previous Next
whatsapp