<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[SS-API-RestAssured]]></title><description><![CDATA[SS-API-RestAssured]]></description><link>https://shreenibas-api-restassured.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 14 Oct 2026 11:23:22 GMT</lastBuildDate><atom:link href="https://shreenibas-api-restassured.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Assertion  & hamcrest]]></title><description><![CDATA[Perfect 👍 — this is an important Java + Selenium + TestNG/JUnit interview and practical topic.Let’s go step-by-step in detail on:

🔍 Assert (from TestNG/JUnit) and🧩 Hamcrest Matchers (from org.hamcrest) — what they are, how they differ, and how to...]]></description><link>https://shreenibas-api-restassured.hashnode.dev/assertion-and-hamcrest</link><guid isPermaLink="true">https://shreenibas-api-restassured.hashnode.dev/assertion-and-hamcrest</guid><category><![CDATA[@shreenibas]]></category><dc:creator><![CDATA[Shreenibas Samal]]></dc:creator><pubDate>Tue, 11 Nov 2025 05:04:23 GMT</pubDate><content:encoded><![CDATA[<p>Perfect 👍 — this is an important <strong>Java + Selenium + TestNG/JUnit</strong> interview and practical topic.<br />Let’s go <strong>step-by-step in detail</strong> on:</p>
<blockquote>
<p>🔍 <code>Assert</code> (from TestNG/JUnit) and<br />🧩 <code>Hamcrest Matchers</code> (from <code>org.hamcrest</code>) — what they are, how they differ, and how to use them <strong>in Selenium automation</strong>.</p>
</blockquote>
<hr />
<h1 id="heading-1-what-is-an-assertion">🧠 1️⃣ What is an Assertion?</h1>
<h3 id="heading-definition">🔹 Definition:</h3>
<p>An <strong>assertion</strong> is a <strong>checkpoint</strong> that verifies whether the <strong>actual result</strong> matches the <strong>expected result</strong> in your test case.</p>
<p>If the condition <strong>passes</strong> → test continues.<br />If it <strong>fails</strong> → test stops and marks as <strong>Failed</strong>.</p>
<hr />
<h1 id="heading-2-types-of-assertions-in-selenium-testng">🧩 2️⃣ Types of Assertions (in Selenium + TestNG)</h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Type</td><td>Package</td><td>Purpose</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Hard Assert</strong></td><td><code>org.testng.Assert</code></td><td>Stops execution when it fails</td></tr>
<tr>
<td><strong>Soft Assert</strong></td><td><code>org.testng.asserts.SoftAssert</code></td><td>Collects all failures, reports at the end</td></tr>
<tr>
<td><strong>Hamcrest Matchers</strong></td><td><code>org.hamcrest.*</code></td><td>Provides advanced, readable, flexible comparison logic</td></tr>
</tbody>
</table>
</div><hr />
<h1 id="heading-3-hard-assert-testng">🧩 3️⃣ HARD ASSERT (TestNG)</h1>
<h3 id="heading-meaning">🧠 Meaning:</h3>
<p>Used for <strong>strict verification</strong>.<br />If a Hard Assert fails, test execution <strong>immediately stops</strong> at that line.</p>
<h3 id="heading-common-methods">✅ Common Methods:</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Method</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>Assert.assertEquals(actual, expected)</code></td><td>Checks equality</td></tr>
<tr>
<td><code>Assert.assertNotEquals(actual, expected)</code></td><td>Checks non-equality</td></tr>
<tr>
<td><code>Assert.assertTrue(condition)</code></td><td>Pass if condition = true</td></tr>
<tr>
<td><code>Assert.assertFalse(condition)</code></td><td>Pass if condition = false</td></tr>
<tr>
<td><code>Assert.assertNull(object)</code></td><td>Pass if object = null</td></tr>
<tr>
<td><code>Assert.assertNotNull(object)</code></td><td>Pass if object ≠ null</td></tr>
<tr>
<td><code>Assert.fail("Message")</code></td><td>Forcefully fail the test</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-example-selenium-testng">🧩 Example (Selenium + TestNG)</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.testng.Assert;
<span class="hljs-keyword">import</span> org.testng.annotations.Test;
<span class="hljs-keyword">import</span> org.openqa.selenium.By;
<span class="hljs-keyword">import</span> org.openqa.selenium.WebDriver;
<span class="hljs-keyword">import</span> org.openqa.selenium.chrome.ChromeDriver;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PaymentAssertionTest</span> </span>{
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">verifyPaymentSuccess</span><span class="hljs-params">()</span> </span>{
        WebDriver driver = <span class="hljs-keyword">new</span> ChromeDriver();
        driver.get(<span class="hljs-string">"https://example.com/payment"</span>);

        driver.findElement(By.id(<span class="hljs-string">"payNow"</span>)).click();
        String actualMessage = driver.findElement(By.id(<span class="hljs-string">"paymentSuccessMsg"</span>)).getText();

        <span class="hljs-comment">// Hard Assert</span>
        Assert.assertEquals(actualMessage, <span class="hljs-string">"Payment Successful"</span>, <span class="hljs-string">"❌ Payment message mismatch"</span>);
        System.out.println(<span class="hljs-string">"✅ Payment verified successfully"</span>);

        driver.quit();
    }
}
</code></pre>
<p>👉 If message mismatches → test stops immediately and fails.</p>
<hr />
<h1 id="heading-4-soft-assert-testng">🧩 4️⃣ SOFT ASSERT (TestNG)</h1>
<h3 id="heading-meaning-1">🔹 Meaning:</h3>
<p>Soft asserts <strong>don’t stop</strong> the test when they fail.<br />They <strong>collect</strong> all failures and report at the end using <code>.assertAll()</code>.</p>
<h3 id="heading-syntax">✅ Syntax:</h3>
<pre><code class="lang-java">SoftAssert softAssert = <span class="hljs-keyword">new</span> SoftAssert();
softAssert.assertEquals(actual, expected);
softAssert.assertTrue(condition);
softAssert.assertAll();  <span class="hljs-comment">// mandatory</span>
</code></pre>
<hr />
<h3 id="heading-example-selenium">🧩 Example (Selenium)</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.testng.asserts.SoftAssert;

SoftAssert softAssert = <span class="hljs-keyword">new</span> SoftAssert();

softAssert.assertEquals(driver.getTitle(), <span class="hljs-string">"Payments"</span>);
softAssert.assertTrue(driver.findElement(By.id(<span class="hljs-string">"payNow"</span>)).isDisplayed());
softAssert.assertEquals(actualMessage, <span class="hljs-string">"Payment Successful"</span>);

System.out.println(<span class="hljs-string">"✅ Test continued despite assertion failures."</span>);
softAssert.assertAll();  <span class="hljs-comment">// Collects and reports all failures</span>
</code></pre>
<hr />
<h1 id="heading-5-why-use-hamcrest-matchers">🧠 5️⃣ Why Use Hamcrest Matchers?</h1>
<h3 id="heading-problem-with-assert">🔹 Problem with Assert:</h3>
<p><code>Assert</code> syntax can be <strong>rigid</strong> and <strong>less readable</strong> when you need complex validation:</p>
<pre><code class="lang-java">Assert.assertTrue(actualText.contains(<span class="hljs-string">"Success"</span>));
</code></pre>
<h3 id="heading-solution">🔹 Solution:</h3>
<p><strong>Hamcrest Matchers</strong> (from <code>org.hamcrest</code>) allow <strong>fluent, readable</strong>, and <strong>flexible</strong> conditions like:</p>
<pre><code class="lang-java">assertThat(actualText, containsString(<span class="hljs-string">"Success"</span>));
</code></pre>
<hr />
<h1 id="heading-6-hamcrest-core-concept">🧩 6️⃣ Hamcrest Core Concept</h1>
<p>✅ Import:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.MatcherAssert.assertThat;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;
</code></pre>
<p>✅ Syntax:</p>
<pre><code class="lang-java">assertThat(actualValue, matcherCondition);
</code></pre>
<hr />
<h1 id="heading-7-common-hamcrest-matchers">🧱 7️⃣ Common Hamcrest Matchers</h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Matcher</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>equalTo()</code></td><td>Checks equality</td><td><code>assertThat(title, equalTo("Dashboard"));</code></td></tr>
<tr>
<td><code>is()</code></td><td>Same as equalTo (adds readability)</td><td><code>assertThat(amount, is(100));</code></td></tr>
<tr>
<td><code>not()</code></td><td>Negation</td><td><code>assertThat(status, not("Failed"));</code></td></tr>
<tr>
<td><code>containsString()</code></td><td>Checks substring</td><td><code>assertThat(msg, containsString("Success"));</code></td></tr>
<tr>
<td><code>startsWith()</code> / <code>endsWith()</code></td><td>String prefix/suffix</td><td><code>assertThat(url, startsWith("https"));</code></td></tr>
<tr>
<td><code>greaterThan()</code> / <code>lessThan()</code></td><td>Numeric comparison</td><td><code>assertThat(price, greaterThan(0));</code></td></tr>
<tr>
<td><code>hasItem()</code></td><td>Checks if collection has element</td><td><code>assertThat(list, hasItem("Product1"));</code></td></tr>
<tr>
<td><code>hasItems()</code></td><td>Multiple elements</td><td><code>assertThat(list, hasItems("Item1", "Item2"));</code></td></tr>
<tr>
<td><code>instanceOf()</code></td><td>Checks type</td><td><code>assertThat(driver, instanceOf(WebDriver.class));</code></td></tr>
<tr>
<td><code>anyOf()</code></td><td>Logical OR</td><td><code>assertThat(status, anyOf(is("OK"), is("Done")));</code></td></tr>
<tr>
<td><code>allOf()</code></td><td>Logical AND</td><td><code>assertThat(msg, allOf(containsString("Payment"), containsString("Success")));</code></td></tr>
</tbody>
</table>
</div><hr />
<h1 id="heading-8-example-hamcrest-in-selenium">🧩 8️⃣ Example — Hamcrest in Selenium</h1>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.MatcherAssert.assertThat;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;
<span class="hljs-keyword">import</span> org.openqa.selenium.By;
<span class="hljs-keyword">import</span> org.openqa.selenium.WebDriver;
<span class="hljs-keyword">import</span> org.openqa.selenium.chrome.ChromeDriver;
<span class="hljs-keyword">import</span> org.testng.annotations.Test;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HamcrestPaymentTest</span> </span>{

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">verifyPaymentConfirmation</span><span class="hljs-params">()</span> </span>{
        WebDriver driver = <span class="hljs-keyword">new</span> ChromeDriver();
        driver.get(<span class="hljs-string">"https://example.com/checkout"</span>);
        driver.findElement(By.id(<span class="hljs-string">"payNow"</span>)).click();

        String confirmationMsg = driver.findElement(By.id(<span class="hljs-string">"paymentSuccessMsg"</span>)).getText();

        <span class="hljs-comment">// Hamcrest Assertions</span>
        assertThat(<span class="hljs-string">"✅ Payment confirmation validation"</span>,
                   confirmationMsg,
                   allOf(startsWith(<span class="hljs-string">"Payment"</span>), containsString(<span class="hljs-string">"Success"</span>)));

        String url = driver.getCurrentUrl();
        assertThat(url, containsString(<span class="hljs-string">"confirmation"</span>));

        driver.quit();
    }
}
</code></pre>
<p>🟢 <strong>Output:</strong> Test passes only if message starts with “Payment” and includes “Success”.</p>
<hr />
<h1 id="heading-9-combining-hamcrest-testng-softassert-advanced">⚙️ 9️⃣ Combining Hamcrest + TestNG SoftAssert (Advanced)</h1>
<p>Sometimes you can use both to get readable, non-blocking checks:</p>
<pre><code class="lang-java">SoftAssert softAssert = <span class="hljs-keyword">new</span> SoftAssert();

<span class="hljs-keyword">try</span> {
    assertThat(price, greaterThan(<span class="hljs-number">0.0</span>));
} <span class="hljs-keyword">catch</span> (AssertionError e) {
    softAssert.fail(e.getMessage());
}

<span class="hljs-keyword">try</span> {
    assertThat(message, containsString(<span class="hljs-string">"Success"</span>));
} <span class="hljs-keyword">catch</span> (AssertionError e) {
    softAssert.fail(e.getMessage());
}

softAssert.assertAll();
</code></pre>
<p>✅ Gives best of both worlds — flexible matching + multiple validation collection.</p>
<hr />
<h1 id="heading-10-hamcrest-logical-matchers-advanced">🧠 1️⃣0️⃣ Hamcrest Logical Matchers (Advanced)</h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Matcher</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>allOf(m1, m2, m3)</code></td><td>All must match (AND)</td><td><code>assertThat(value, allOf(greaterThan(10), lessThan(20)));</code></td></tr>
<tr>
<td><code>anyOf(m1, m2)</code></td><td>Any one can match (OR)</td><td><code>assertThat(color, anyOf(is("Red"), is("Blue")));</code></td></tr>
<tr>
<td><code>not(anyOf(...))</code></td><td>None should match</td><td><code>assertThat(status, not(anyOf(is("Fail"), is("Error"))));</code></td></tr>
</tbody>
</table>
</div><hr />
<h1 id="heading-11-real-e-commerce-payment-example-combined">🧾 1️⃣1️⃣ Real E-commerce Payment Example (Combined)</h1>
<pre><code class="lang-java"><span class="hljs-meta">@Test</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">verifyPaymentFlow</span><span class="hljs-params">()</span> </span>{
    WebDriver driver = <span class="hljs-keyword">new</span> ChromeDriver();
    driver.get(<span class="hljs-string">"https://shopdemo.example.com"</span>);

    driver.findElement(By.id(<span class="hljs-string">"addToCart"</span>)).click();
    driver.findElement(By.id(<span class="hljs-string">"checkout"</span>)).click();
    driver.findElement(By.id(<span class="hljs-string">"payNow"</span>)).click();

    String message = driver.findElement(By.id(<span class="hljs-string">"paymentSuccessMsg"</span>)).getText();
    <span class="hljs-keyword">double</span> totalAmount = Double.parseDouble(driver.findElement(By.id(<span class="hljs-string">"totalAmount"</span>)).getText().replace(<span class="hljs-string">"$"</span>, <span class="hljs-string">""</span>));

    assertThat(<span class="hljs-string">"Verify payment confirmation message"</span>,
               message,
               allOf(containsString(<span class="hljs-string">"Payment"</span>), containsString(<span class="hljs-string">"Success"</span>)));

    assertThat(<span class="hljs-string">"Verify total amount greater than zero"</span>, totalAmount, greaterThan(<span class="hljs-number">0.0</span>));

    assertThat(<span class="hljs-string">"Verify redirection URL"</span>, driver.getCurrentUrl(), containsString(<span class="hljs-string">"confirmation"</span>));

    driver.quit();
}
</code></pre>
<hr />
<h1 id="heading-12-difference-summary-table">🧠 1️⃣2️⃣ Difference Summary Table</h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>TestNG Assert</td><td>SoftAssert</td><td>Hamcrest</td></tr>
</thead>
<tbody>
<tr>
<td>Stops on failure</td><td>✅ Yes</td><td>❌ No</td><td>✅ Yes</td></tr>
<tr>
<td>Reports multiple failures</td><td>❌ No</td><td>✅ Yes</td><td>❌ No</td></tr>
<tr>
<td>Readability</td><td>Medium</td><td>Medium</td><td>✅ High</td></tr>
<tr>
<td>Complex matching</td><td>Limited</td><td>Limited</td><td>✅ Very Flexible</td></tr>
<tr>
<td>Logical combinations</td><td>❌ No</td><td>❌ No</td><td>✅ Yes (<code>allOf</code>, <code>anyOf</code>)</td></tr>
<tr>
<td>Common use</td><td>Functional tests</td><td>Batch verifications</td><td>Readable validation</td></tr>
</tbody>
</table>
</div><hr />
<h1 id="heading-summary-in-one-line">✅ Summary in One Line</h1>
<blockquote>
<p>🔹 <strong>Use</strong> <code>Assert</code> for simple direct verifications.<br />🔹 <strong>Use</strong> <code>SoftAssert</code> when you need to collect multiple results.<br />🔹 <strong>Use</strong> <code>Hamcrest Matchers</code> when you want expressive, flexible, human-readable validation in automation frameworks.</p>
</blockquote>
<hr />
<p>Would you like me to show you<br />👉 a <strong>real-time hybrid example</strong> where TestNG, SoftAssert, and Hamcrest are used <strong>together</strong> in a single Selenium test (like full payment flow validation)?</p>
<h5 id="heading-you-said">You said:</h5>
<p>give for rest assured</p>
<h6 id="heading-chatgpt-said">ChatGPT said:</h6>
<p>Excellent 🔥 — now let’s go <strong>deep into</strong> <code>Assert</code> and <code>Hamcrest Matchers</code> in REST Assured,<br />which is extremely important for <strong>API Testing automation</strong> interviews and frameworks.</p>
<p>We’ll cover everything step-by-step —<br />✅ From basics → advanced usage → real e-commerce payment API example.</p>
<hr />
<h2 id="heading-1-what-is-rest-assured">🧠 1️⃣ What is REST Assured?</h2>
<p><code>REST Assured</code> is a <strong>Java library</strong> for <strong>testing REST APIs</strong>.<br />It helps to:</p>
<ul>
<li><p>Send API requests (<code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code>, etc.)</p>
</li>
<li><p>Validate <strong>status codes</strong>, <strong>response bodies</strong>, and <strong>headers</strong></p>
</li>
<li><p>Perform <strong>BDD-style assertions</strong> using <strong>Hamcrest Matchers</strong></p>
</li>
</ul>
<hr />
<h2 id="heading-2-types-of-assertions-in-rest-assured">🧩 2️⃣ Types of Assertions in REST Assured</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Type</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Inline Assertions</strong></td><td>Done inside <code>.then()</code> using Hamcrest matchers</td><td><code>.then().body("status", equalTo("success"))</code></td></tr>
<tr>
<td><strong>External Assertions (TestNG/JUnit)</strong></td><td>Done after extracting response data</td><td><code>Assert.assertEquals(statusCode, 200)</code></td></tr>
<tr>
<td><strong>Multiple Assertions</strong></td><td>Combine both styles for deeper checks</td><td>BDD + TestNG combo</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-3-basic-rest-assured-structure">⚙️ 3️⃣ Basic REST Assured Structure</h2>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;

given()
    .baseUri(<span class="hljs-string">"https://api.example.com"</span>)
    .when()
    .get(<span class="hljs-string">"/payment/status"</span>)
    .then()
    .statusCode(<span class="hljs-number">200</span>)
    .body(<span class="hljs-string">"status"</span>, equalTo(<span class="hljs-string">"SUCCESS"</span>));
</code></pre>
<p>✅ Here:</p>
<ul>
<li><p><code>given()</code> → Setup request</p>
</li>
<li><p><code>when()</code> → Trigger API call</p>
</li>
<li><p><code>then()</code> → Verify response using <strong>Hamcrest Matchers</strong></p>
</li>
</ul>
<hr />
<h2 id="heading-4-using-assert-testng-junit-with-rest-assured">🧱 4️⃣ Using <code>Assert</code> (TestNG / JUnit) with REST Assured</h2>
<p>You can extract response data and validate using <strong>TestNG Assert</strong>:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> io.restassured.response.Response;
<span class="hljs-keyword">import</span> org.testng.Assert;

Response response = 
    given()
        .baseUri(<span class="hljs-string">"https://api.example.com"</span>)
        .when()
        .get(<span class="hljs-string">"/payment/status"</span>);

<span class="hljs-keyword">int</span> statusCode = response.getStatusCode();
String status = response.jsonPath().getString(<span class="hljs-string">"status"</span>);

Assert.assertEquals(statusCode, <span class="hljs-number">200</span>, <span class="hljs-string">"Invalid Status Code"</span>);
Assert.assertEquals(status, <span class="hljs-string">"SUCCESS"</span>, <span class="hljs-string">"Payment status failed"</span>);
</code></pre>
<p>🟢 <strong>Use this approach</strong> when you need detailed validation logic or multiple fields.</p>
<hr />
<h2 id="heading-5-hamcrest-matchers-in-rest-assured">🧠 5️⃣ Hamcrest Matchers in REST Assured</h2>
<p>REST Assured integrates <strong>Hamcrest</strong> for <strong>BDD-style validation</strong> directly in <code>.then()</code> section.</p>
<h3 id="heading-import-required">🔹 Import Required:</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;
</code></pre>
<h3 id="heading-example">🔹 Example:</h3>
<pre><code class="lang-java">given()
    .baseUri(<span class="hljs-string">"https://api.example.com"</span>)
    .when()
    .get(<span class="hljs-string">"/order/123"</span>)
    .then()
    .statusCode(<span class="hljs-number">200</span>)
    .body(<span class="hljs-string">"orderId"</span>, equalTo(<span class="hljs-number">123</span>))
    .body(<span class="hljs-string">"payment.status"</span>, is(<span class="hljs-string">"Success"</span>))
    .body(<span class="hljs-string">"items.size()"</span>, greaterThan(<span class="hljs-number">0</span>));
</code></pre>
<p>✅ <strong>Advantages:</strong></p>
<ul>
<li><p>Fluent and readable</p>
</li>
<li><p>No need for explicit response extraction</p>
</li>
<li><p>Combines multiple checks easily</p>
</li>
</ul>
<hr />
<h2 id="heading-6-commonly-used-hamcrest-matchers-in-rest-assured">🧩 6️⃣ Commonly Used Hamcrest Matchers in REST Assured</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Matcher</td><td>Usage</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>equalTo(value)</code></td><td>Exact equality</td><td><code>.body("status", equalTo("Success"))</code></td></tr>
<tr>
<td><code>is(value)</code></td><td>Same as equalTo</td><td><code>.body("amount", is(1000))</code></td></tr>
<tr>
<td><code>not(value)</code></td><td>Negation</td><td><code>.body("status", not("Failed"))</code></td></tr>
<tr>
<td><code>hasItem(value)</code></td><td>For lists</td><td><code>.body("items.name", hasItem("Laptop"))</code></td></tr>
<tr>
<td><code>hasItems(...)</code></td><td>Multiple items</td><td><code>.body("items.name", hasItems("Phone", "Tablet"))</code></td></tr>
<tr>
<td><code>containsString(value)</code></td><td>Partial text match</td><td><code>.body("message", containsString("Payment"))</code></td></tr>
<tr>
<td><code>startsWith(value)</code></td><td>Prefix</td><td><code>.body("status", startsWith("Suc"))</code></td></tr>
<tr>
<td><code>endsWith(value)</code></td><td>Suffix</td><td><code>.body("status", endsWith("cess"))</code></td></tr>
<tr>
<td><code>greaterThan(value)</code></td><td>Numeric compare</td><td><code>.body("amount", greaterThan(0))</code></td></tr>
<tr>
<td><code>lessThan(value)</code></td><td>Numeric compare</td><td><code>.body("discount", lessThan(50))</code></td></tr>
<tr>
<td><code>anyOf(...)</code></td><td>Logical OR</td><td><code>.body("status", anyOf(is("Success"), is("Pending")))</code></td></tr>
<tr>
<td><code>allOf(...)</code></td><td>Logical AND</td><td><code>.body("message", allOf(containsString("Payment"), containsString("Success")))</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-7-real-e-commerce-payment-api-example">🧾 7️⃣ Real E-commerce Payment API Example</h2>
<h3 id="heading-scenario">🧩 Scenario:</h3>
<p>User makes a payment — <code>/api/payment/confirm</code> returns:</p>
<pre><code class="lang-java">{
  <span class="hljs-string">"transactionId"</span>: <span class="hljs-string">"TXN12345"</span>,
  <span class="hljs-string">"status"</span>: <span class="hljs-string">"Success"</span>,
  <span class="hljs-string">"amount"</span>: <span class="hljs-number">999.99</span>,
  <span class="hljs-string">"currency"</span>: <span class="hljs-string">"INR"</span>,
  <span class="hljs-string">"message"</span>: <span class="hljs-string">"Payment Successful"</span>,
  <span class="hljs-string">"paymentMode"</span>: <span class="hljs-string">"UPI"</span>
}
</code></pre>
<h3 id="heading-test-case-hamcrest-rest-assured">✅ Test Case (Hamcrest + REST Assured)</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;
<span class="hljs-keyword">import</span> org.testng.annotations.Test;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PaymentAPITest</span> </span>{

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">verifyPaymentConfirmation</span><span class="hljs-params">()</span> </span>{
        given()
            .baseUri(<span class="hljs-string">"https://api.ecommerce.com"</span>)
            .contentType(<span class="hljs-string">"application/json"</span>)
            .body(<span class="hljs-string">"{\"orderId\":\"ORD12345\", \"amount\":999.99, \"mode\":\"UPI\"}"</span>)
        .when()
            .post(<span class="hljs-string">"/api/payment/confirm"</span>)
        .then()
            .statusCode(<span class="hljs-number">200</span>)
            .body(<span class="hljs-string">"status"</span>, equalTo(<span class="hljs-string">"Success"</span>))
            .body(<span class="hljs-string">"message"</span>, containsString(<span class="hljs-string">"Payment"</span>))
            .body(<span class="hljs-string">"amount"</span>, greaterThan(<span class="hljs-number">0.0f</span>))
            .body(<span class="hljs-string">"currency"</span>, is(<span class="hljs-string">"INR"</span>))
            .body(<span class="hljs-string">"paymentMode"</span>, anyOf(is(<span class="hljs-string">"UPI"</span>), is(<span class="hljs-string">"Card"</span>), is(<span class="hljs-string">"NetBanking"</span>)));
    }
}
</code></pre>
<p>🟢 Here we validated:</p>
<ul>
<li><p>HTTP status</p>
</li>
<li><p>Response fields</p>
</li>
<li><p>Value ranges</p>
</li>
<li><p>Logical OR for multiple payment modes</p>
</li>
</ul>
<hr />
<h2 id="heading-8-extract-test-using-assert-hamcrest-hybrid">⚙️ 8️⃣ Extract + Test Using Assert + Hamcrest Hybrid</h2>
<p>You can combine both styles for flexible logic:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> io.restassured.response.Response;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.MatcherAssert.assertThat;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;
<span class="hljs-keyword">import</span> org.testng.Assert;

Response response = 
    given()
        .baseUri(<span class="hljs-string">"https://api.ecommerce.com"</span>)
        .when()
        .get(<span class="hljs-string">"/api/payment/ORD12345"</span>);

<span class="hljs-keyword">int</span> statusCode = response.getStatusCode();
String status = response.jsonPath().getString(<span class="hljs-string">"status"</span>);
<span class="hljs-keyword">double</span> amount = response.jsonPath().getDouble(<span class="hljs-string">"amount"</span>);

<span class="hljs-comment">// TestNG assertions</span>
Assert.assertEquals(statusCode, <span class="hljs-number">200</span>, <span class="hljs-string">"Invalid Status Code"</span>);
Assert.assertNotNull(status, <span class="hljs-string">"Status missing"</span>);

<span class="hljs-comment">// Hamcrest matchers</span>
assertThat(status, is(<span class="hljs-string">"Success"</span>));
assertThat(amount, greaterThan(<span class="hljs-number">0.0</span>));
</code></pre>
<p>✅ Use this style when you want flexibility + detailed failure messages.</p>
<hr />
<h2 id="heading-9-validating-complex-json-responses">🧠 9️⃣ Validating Complex JSON Responses</h2>
<p>Example:</p>
<pre><code class="lang-java">{
  <span class="hljs-string">"orders"</span>: [
    { <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"status"</span>: <span class="hljs-string">"Delivered"</span> },
    { <span class="hljs-string">"id"</span>: <span class="hljs-number">2</span>, <span class="hljs-string">"status"</span>: <span class="hljs-string">"Shipped"</span> }
  ]
}
</code></pre>
<p>Validation:</p>
<pre><code class="lang-java">given()
    .when()
    .get(<span class="hljs-string">"/orders"</span>)
    .then()
    .statusCode(<span class="hljs-number">200</span>)
    .body(<span class="hljs-string">"orders.id"</span>, hasItems(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>))
    .body(<span class="hljs-string">"orders.status"</span>, hasItem(<span class="hljs-string">"Shipped"</span>));
</code></pre>
<hr />
<h2 id="heading-10-validate-response-headers-and-time">⚡ 1️⃣0️⃣ Validate Response Headers and Time</h2>
<pre><code class="lang-java">given()
    .when()
    .get(<span class="hljs-string">"/api/payment/ORD12345"</span>)
    .then()
    .statusCode(<span class="hljs-number">200</span>)
    .header(<span class="hljs-string">"Content-Type"</span>, equalTo(<span class="hljs-string">"application/json"</span>))
    .time(lessThan(<span class="hljs-number">2000L</span>)); <span class="hljs-comment">// response within 2 seconds</span>
</code></pre>
<hr />
<h2 id="heading-11-error-handling-example-negative-test">💥 1️⃣1️⃣ Error Handling Example (Negative Test)</h2>
<pre><code class="lang-java">given()
    .baseUri(<span class="hljs-string">"https://api.ecommerce.com"</span>)
    .when()
    .get(<span class="hljs-string">"/api/payment/invalidOrder"</span>)
    .then()
    .statusCode(<span class="hljs-number">404</span>)
    .body(<span class="hljs-string">"error.message"</span>, containsString(<span class="hljs-string">"Order not found"</span>))
    .body(<span class="hljs-string">"error.code"</span>, equalTo(<span class="hljs-string">"404_NOT_FOUND"</span>));
</code></pre>
<hr />
<h2 id="heading-12-difference-between-assert-amp-hamcrest-in-rest-assured">🧩 1️⃣2️⃣ Difference Between Assert &amp; Hamcrest in REST Assured</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>TestNG / JUnit Assert</td><td>Hamcrest Matcher</td></tr>
</thead>
<tbody>
<tr>
<td>Style</td><td>Procedural</td><td>Fluent / BDD-style</td></tr>
<tr>
<td>Readability</td><td>Medium</td><td>✅ Very high</td></tr>
<tr>
<td>Multiple Checks</td><td>Manual</td><td>Inline (chained)</td></tr>
<tr>
<td>JSON Support</td><td>Needs parsing</td><td>Built-in path validation</td></tr>
<tr>
<td>Failure Message</td><td>Simple</td><td>Descriptive</td></tr>
<tr>
<td>Typical Use</td><td>Extracted response validation</td><td>Inline <code>.then().body()</code> checks</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-13-chaining-multiple-conditions-allof-anyof">🧠 1️⃣3️⃣ Chaining Multiple Conditions (allOf / anyOf)</h2>
<pre><code class="lang-java">given()
    .when()
    .get(<span class="hljs-string">"/api/payment/ORD12345"</span>)
    .then()
    .body(<span class="hljs-string">"message"</span>, allOf(containsString(<span class="hljs-string">"Payment"</span>), containsString(<span class="hljs-string">"Success"</span>)))
    .body(<span class="hljs-string">"status"</span>, anyOf(is(<span class="hljs-string">"Success"</span>), is(<span class="hljs-string">"Completed"</span>)));
</code></pre>
<p>✅ Combines multiple conditions cleanly.</p>
<hr />
<h2 id="heading-14-complete-example-payment-module-test-flow">🧾 1️⃣4️⃣ Complete Example: Payment Module Test Flow</h2>
<pre><code class="lang-java"><span class="hljs-meta">@Test</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testFullPaymentFlow</span><span class="hljs-params">()</span> </span>{
    given()
        .baseUri(<span class="hljs-string">"https://api.ecommerce.com"</span>)
        .contentType(<span class="hljs-string">"application/json"</span>)
        .body(<span class="hljs-string">"{\"userId\":1, \"orderId\":\"ORD1001\", \"amount\":500.0}"</span>)
    .when()
        .post(<span class="hljs-string">"/api/payment/confirm"</span>)
    .then()
        .statusCode(<span class="hljs-number">200</span>)
        .body(<span class="hljs-string">"status"</span>, equalTo(<span class="hljs-string">"Success"</span>))
        .body(<span class="hljs-string">"transactionId"</span>, notNullValue())
        .body(<span class="hljs-string">"message"</span>, containsString(<span class="hljs-string">"Successful"</span>))
        .body(<span class="hljs-string">"paymentMode"</span>, anyOf(is(<span class="hljs-string">"UPI"</span>), is(<span class="hljs-string">"Card"</span>)))
        .body(<span class="hljs-string">"amount"</span>, greaterThan(<span class="hljs-number">0.0f</span>))
        .body(<span class="hljs-string">"currency"</span>, is(<span class="hljs-string">"INR"</span>))
        .header(<span class="hljs-string">"Content-Type"</span>, containsString(<span class="hljs-string">"application/json"</span>));
}
</code></pre>
<hr />
<h2 id="heading-15-summary">✅ 1️⃣5️⃣ Summary</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Use Case</td><td>Use This</td></tr>
</thead>
<tbody>
<tr>
<td>Simple equality checks</td><td><code>Assert.assertEquals()</code></td></tr>
<tr>
<td>Multiple, human-readable validations</td><td><code>Hamcrest Matchers</code></td></tr>
<tr>
<td>Inline JSON + header validation</td><td><code>.then().body()</code> + Hamcrest</td></tr>
<tr>
<td>Extract → post-validation logic</td><td><code>Assert</code> + extracted values</td></tr>
<tr>
<td>Logical / compound checks</td><td><code>allOf()</code>, <code>anyOf()</code></td></tr>
</tbody>
</table>
</div><hr />
<p>Would you like me to give you a <strong>real-world API test class</strong> that covers:</p>
<ul>
<li><p><code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code></p>
</li>
<li><p>uses both <code>Assert</code> and <code>Hamcrest</code></p>
</li>
<li><p>for a full <strong>e-commerce payment + order API flow</strong> (end-to-end)?</p>
</li>
</ul>
<h5 id="heading-you-said-1">You said:</h5>
<p>json and json path in detail and give playground for practice</p>
<h6 id="heading-chatgpt-said-1">ChatGPT said:</h6>
<p>Perfect 🔥 — this is one of the <strong>most important topics</strong> in API Testing and automation with <strong>REST Assured</strong> and <strong>Selenium frameworks</strong>:</p>
<p>Let’s go <strong>step-by-step</strong> and <strong>in-depth</strong> on 👇</p>
<blockquote>
<p><strong>JSON + JSONPath</strong> with full explanation, syntax, practical examples, and free playgrounds for hands-on practice.</p>
</blockquote>
<hr />
<h1 id="heading-1-what-is-json">🧠 1️⃣ What is JSON?</h1>
<h3 id="heading-definition-1">🔹 Definition:</h3>
<p><strong>JSON</strong> (JavaScript Object Notation) is a <strong>lightweight data-interchange format</strong> used to store and exchange data between systems — mostly between <strong>client</strong> and <strong>server</strong> in REST APIs.</p>
<p>It’s easy for <strong>humans to read</strong> and <strong>machines to parse</strong>.</p>
<hr />
<h3 id="heading-basic-json-example">🧩 Basic JSON Example</h3>
<pre><code class="lang-java">{
  <span class="hljs-string">"id"</span>: <span class="hljs-number">101</span>,
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Shreenibas"</span>,
  <span class="hljs-string">"email"</span>: <span class="hljs-string">"shree@test.com"</span>,
  <span class="hljs-string">"isActive"</span>: <span class="hljs-keyword">true</span>,
  <span class="hljs-string">"skills"</span>: [<span class="hljs-string">"Java"</span>, <span class="hljs-string">"Selenium"</span>, <span class="hljs-string">"API Testing"</span>],
  <span class="hljs-string">"address"</span>: {
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"Bhubaneswar"</span>,
    <span class="hljs-string">"pin"</span>: <span class="hljs-number">751024</span>
  }
}
</code></pre>
<hr />
<h1 id="heading-2-json-data-types">🧱 2️⃣ JSON Data Types</h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Type</td><td>Example</td><td>Notes</td></tr>
</thead>
<tbody>
<tr>
<td><strong>String</strong></td><td><code>"Selenium"</code></td><td>Text in double quotes</td></tr>
<tr>
<td><strong>Number</strong></td><td><code>101</code>, <code>99.9</code></td><td>No quotes</td></tr>
<tr>
<td><strong>Boolean</strong></td><td><code>true</code>, <code>false</code></td><td>Lowercase only</td></tr>
<tr>
<td><strong>Null</strong></td><td><code>null</code></td><td>Represents no value</td></tr>
<tr>
<td><strong>Array</strong></td><td><code>["A", "B", "C"]</code></td><td>List of values</td></tr>
<tr>
<td><strong>Object</strong></td><td><code>{"key":"value"}</code></td><td>Key-value pairs</td></tr>
</tbody>
</table>
</div><hr />
<h1 id="heading-3-json-structure-hierarchy">🧠 3️⃣ JSON Structure Hierarchy</h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Level</td><td>Type</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>Root</td><td>Object <code>{}</code></td><td>Holds all key–value pairs</td></tr>
<tr>
<td>Nested Object</td><td>Object inside another</td><td><code>"address": { "city": "Delhi" }</code></td></tr>
<tr>
<td>Array</td><td><code>[]</code></td><td>List of objects or values</td></tr>
<tr>
<td>Nested Array</td><td>Array inside array/object</td><td><code>"orders": [ { "id":1 }, { "id":2 } ]</code></td></tr>
</tbody>
</table>
</div><hr />
<h1 id="heading-4-what-is-jsonpath">🧩 4️⃣ What is JSONPath?</h1>
<h3 id="heading-definition-2">🔹 Definition:</h3>
<p><strong>JSONPath</strong> is a <strong>query language</strong> for extracting specific data from JSON.<br />It’s similar to <strong>XPath</strong> (for XML).</p>
<p>👉 It helps you <strong>navigate JSON</strong> using keys, indexes, and filters.</p>
<hr />
<h1 id="heading-5-basic-jsonpath-syntax">⚙️ 5️⃣ Basic JSONPath Syntax</h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Symbol</td><td>Meaning</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>$</code></td><td>Root element</td><td><code>$</code></td></tr>
<tr>
<td><code>.</code></td><td>Child operator</td><td><code>$.name</code></td></tr>
<tr>
<td><code>[]</code></td><td>Array index or filter</td><td><code>$.skills[0]</code></td></tr>
<tr>
<td><code>*</code></td><td>Wildcard (any element)</td><td><code>$.skills[*]</code></td></tr>
<tr>
<td><code>..</code></td><td>Recursive descent (any depth)</td><td><code>$..id</code></td></tr>
<tr>
<td><code>[?()]</code></td><td>Filter expression</td><td><code>$.students[?(@.marks&gt;80)]</code></td></tr>
<tr>
<td><code>[start:end]</code></td><td>Slice operator</td><td><code>$.skills[0:2]</code></td></tr>
</tbody>
</table>
</div><hr />
<h1 id="heading-6-example-json-for-practice">🧾 6️⃣ Example JSON for Practice</h1>
<p>Let’s use this JSON:</p>
<pre><code class="lang-java">{
  <span class="hljs-string">"company"</span>: <span class="hljs-string">"TechCorp"</span>,
  <span class="hljs-string">"employees"</span>: [
    {
      <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>,
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"Alice"</span>,
      <span class="hljs-string">"role"</span>: <span class="hljs-string">"QA"</span>,
      <span class="hljs-string">"skills"</span>: [<span class="hljs-string">"Selenium"</span>, <span class="hljs-string">"Java"</span>, <span class="hljs-string">"API Testing"</span>],
      <span class="hljs-string">"salary"</span>: <span class="hljs-number">60000</span>
    },
    {
      <span class="hljs-string">"id"</span>: <span class="hljs-number">2</span>,
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"Bob"</span>,
      <span class="hljs-string">"role"</span>: <span class="hljs-string">"Developer"</span>,
      <span class="hljs-string">"skills"</span>: [<span class="hljs-string">"Java"</span>, <span class="hljs-string">"SpringBoot"</span>],
      <span class="hljs-string">"salary"</span>: <span class="hljs-number">90000</span>
    },
    {
      <span class="hljs-string">"id"</span>: <span class="hljs-number">3</span>,
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"Carol"</span>,
      <span class="hljs-string">"role"</span>: <span class="hljs-string">"Manager"</span>,
      <span class="hljs-string">"skills"</span>: [<span class="hljs-string">"Leadership"</span>, <span class="hljs-string">"Planning"</span>],
      <span class="hljs-string">"salary"</span>: <span class="hljs-number">120000</span>
    }
  ]
}
</code></pre>
<hr />
<h1 id="heading-7-jsonpath-examples-explained">🧠 7️⃣ JSONPath Examples Explained</h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Query</td><td>Description</td><td>Output</td></tr>
</thead>
<tbody>
<tr>
<td><code>$.company</code></td><td>Get company name</td><td><code>"TechCorp"</code></td></tr>
<tr>
<td><code>$.employees[0].name</code></td><td>Get first employee name</td><td><code>"Alice"</code></td></tr>
<tr>
<td><code>$.employees[*].name</code></td><td>Get all employee names</td><td><code>["Alice","Bob","Carol"]</code></td></tr>
<tr>
<td><code>$..name</code></td><td>Get all names (at any level)</td><td><code>["Alice","Bob","Carol"]</code></td></tr>
<tr>
<td><code>$.employees[?(@.role=="Developer")].name</code></td><td>Get developer’s name</td><td><code>"Bob"</code></td></tr>
<tr>
<td><code>$.employees[?(@.salary&gt;70000)].name</code></td><td>Employees with salary &gt; 70000</td><td><code>["Bob","Carol"]</code></td></tr>
<tr>
<td><code>$.employees[?(@.skills[?(@=="Java")])].name</code></td><td>Employees having Java skill</td><td><code>["Alice","Bob"]</code></td></tr>
<tr>
<td><code>$.employees[-1:]</code></td><td>Last employee</td><td><code>{ "id":3,"name":"Carol"... }</code></td></tr>
<tr>
<td><code>$.employees[0:2].name</code></td><td>First two names</td><td><code>["Alice","Bob"]</code></td></tr>
</tbody>
</table>
</div><hr />
<h1 id="heading-8-jsonpath-in-rest-assured">🧩 8️⃣ JSONPath in REST Assured</h1>
<p>In <strong>REST Assured</strong>, <code>JsonPath</code> helps to extract data from API response.</p>
<h3 id="heading-example-1">Example:</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> io.restassured.path.json.JsonPath;
<span class="hljs-keyword">import</span> io.restassured.response.Response;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;

Response response = 
    given()
        .baseUri(<span class="hljs-string">"https://api.techcorp.com"</span>)
    .when()
        .get(<span class="hljs-string">"/employees"</span>);

JsonPath json = response.jsonPath();
System.out.println(json.getString(<span class="hljs-string">"employees[0].name"</span>));   <span class="hljs-comment">// Alice</span>
System.out.println(json.getList(<span class="hljs-string">"employees.name"</span>));        <span class="hljs-comment">// [Alice, Bob, Carol]</span>
System.out.println(json.getInt(<span class="hljs-string">"employees[1].salary"</span>));    <span class="hljs-comment">// 90000</span>
</code></pre>
<hr />
<h1 id="heading-9-jsonpath-filtering-and-conditions-in-rest-assured">⚙️ 9️⃣ JSONPath — Filtering and Conditions in REST Assured</h1>
<pre><code class="lang-java">List&lt;String&gt; highEarners = json.getList(<span class="hljs-string">"employees.findAll { it.salary &gt; 80000 }.name"</span>);
System.out.println(highEarners); <span class="hljs-comment">// [Bob, Carol]</span>
</code></pre>
<p>✅ <code>findAll { it.condition }</code> → Groovy syntax used by REST Assured internally.</p>
<hr />
<h1 id="heading-advanced-jsonpath-with-groovy-used-by-rest-assured">🧩 🔟 Advanced JsonPath with Groovy (used by REST Assured)</h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Expression</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>find { it.key == 'value' }</code></td><td>Returns first match</td></tr>
<tr>
<td><code>findAll { it.salary &gt; 80000 }</code></td><td>Returns all matches</td></tr>
<tr>
<td><code>collect { it.name }</code></td><td>Extract property values</td></tr>
<tr>
<td><code>size()</code></td><td>Returns array length</td></tr>
<tr>
<td><code>sum()</code></td><td>Returns total sum of numeric array</td></tr>
</tbody>
</table>
</div><h3 id="heading-example-2">Example:</h3>
<pre><code class="lang-java">List&lt;Integer&gt; salaries = json.getList(<span class="hljs-string">"employees.salary"</span>);
<span class="hljs-keyword">int</span> total = salaries.stream().mapToInt(Integer::intValue).sum();
System.out.println(<span class="hljs-string">"Total Salary: "</span> + total);
</code></pre>
<hr />
<h1 id="heading-11-example-extract-nested-data">🧾 1️⃣1️⃣ Example: Extract Nested Data</h1>
<pre><code class="lang-java">String firstSkill = json.getString(<span class="hljs-string">"employees[0].skills[1]"</span>);  <span class="hljs-comment">// Java</span>
List&lt;String&gt; allSkills = json.getList(<span class="hljs-string">"employees.skills.flatten()"</span>);
System.out.println(allSkills);
</code></pre>
<p>👉 <code>.flatten()</code> merges all nested arrays into one.</p>
<hr />
<h1 id="heading-12-real-rest-assured-example-with-jsonpath">🧠 1️⃣2️⃣ Real REST Assured Example with JSONPath</h1>
<pre><code class="lang-java"><span class="hljs-meta">@Test</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">verifyEmployeeData</span><span class="hljs-params">()</span> </span>{
    Response response = 
        given()
            .baseUri(<span class="hljs-string">"https://api.techcorp.com"</span>)
        .when()
            .get(<span class="hljs-string">"/employees"</span>);

    JsonPath json = response.jsonPath();

    <span class="hljs-comment">// Extract values</span>
    List&lt;String&gt; names = json.getList(<span class="hljs-string">"employees.name"</span>);
    List&lt;Integer&gt; salaries = json.getList(<span class="hljs-string">"employees.salary"</span>);
    String firstRole = json.getString(<span class="hljs-string">"employees[0].role"</span>);

    System.out.println(<span class="hljs-string">"Names: "</span> + names);
    System.out.println(<span class="hljs-string">"Salaries: "</span> + salaries);
    System.out.println(<span class="hljs-string">"First role: "</span> + firstRole);

    <span class="hljs-comment">// Assertions</span>
    assertThat(json.getString(<span class="hljs-string">"company"</span>), equalTo(<span class="hljs-string">"TechCorp"</span>));
    assertThat(json.getInt(<span class="hljs-string">"employees.size()"</span>), greaterThan(<span class="hljs-number">2</span>));
    assertThat(names, hasItems(<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>));
}
</code></pre>
<hr />
<h1 id="heading-13-common-mistakes-to-avoid">🧩 1️⃣3️⃣ Common Mistakes to Avoid</h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Mistake</td><td>Example</td><td>Fix</td></tr>
</thead>
<tbody>
<tr>
<td>Wrong index</td><td><code>$.employees[3]</code></td><td>Check array size first</td></tr>
<tr>
<td>Wrong type</td><td>Using <code>.getInt()</code> on string</td><td>Match correct data type</td></tr>
<tr>
<td>Misusing filter</td><td><code>@.role</code> vs <code>@['role']</code></td><td>Use correct attribute name</td></tr>
<tr>
<td>Forget <code>$</code> root</td><td><code>.employees</code> without <code>$</code></td><td>Always start with <code>$</code> (except REST Assured auto-handling)</td></tr>
</tbody>
</table>
</div><hr />
<h1 id="heading-14-tools-amp-playgrounds-for-practice">🧰 1️⃣4️⃣ Tools &amp; Playgrounds for Practice</h1>
<p>Here are the <strong>best free JSON &amp; JSONPath playgrounds</strong> 👇</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Tool</td><td>Link</td><td>Features</td></tr>
</thead>
<tbody>
<tr>
<td><strong>JSONPath Online Evaluator (jsonpath.com)</strong></td><td>🌐 <a target="_blank" href="https://jsonpath.com">https://jsonpath.com</a></td><td>Paste JSON + run queries live</td></tr>
<tr>
<td><strong>JSONPath Finder (jsonpathfinder.com)</strong></td><td>🌐 <a target="_blank" href="https://jsonpathfinder.com">https://jsonpathfinder.com</a></td><td>Click elements → auto generates JSONPath</td></tr>
<tr>
<td><strong>CodeBeautify JSON Viewer</strong></td><td>🌐 <a target="_blank" href="https://codebeautify.org/jsonviewer">https://codebeautify.org/jsonviewer</a></td><td>Format, validate, visualize</td></tr>
<tr>
<td><strong>JsonPath Expression Tester (jsonpath.herokuapp.com)</strong></td><td>🌐 https://jsonpath.herokuapp.com/</td><td>Advanced filter testing</td></tr>
<tr>
<td><strong>REQBIN API Playground</strong></td><td>🌐 <a target="_blank" href="https://reqbin.com/">https://reqbin.com/</a></td><td>Send API requests and test JSONPath inline</td></tr>
</tbody>
</table>
</div><p>👉 I recommend using <a target="_blank" href="https://jsonpath.com"><strong>https://jsonpath.com</strong></a> for live testing — just paste the sample JSON and try the queries above.</p>
<hr />
<h1 id="heading-15-mini-practice-challenges">🧾 1️⃣5️⃣ Mini Practice Challenges 🧩</h1>
<h3 id="heading-use-this-json-in-httpsjsonpathcomhttpsjsonpathcom">Use this JSON 👇 in <a target="_blank" href="https://jsonpath.com">https://jsonpath.com</a></h3>
<pre><code class="lang-java">{
  <span class="hljs-string">"store"</span>: {
    <span class="hljs-string">"book"</span>: [
      { <span class="hljs-string">"category"</span>: <span class="hljs-string">"reference"</span>, <span class="hljs-string">"price"</span>: <span class="hljs-number">8.95</span> },
      { <span class="hljs-string">"category"</span>: <span class="hljs-string">"fiction"</span>, <span class="hljs-string">"price"</span>: <span class="hljs-number">12.99</span> },
      { <span class="hljs-string">"category"</span>: <span class="hljs-string">"fiction"</span>, <span class="hljs-string">"price"</span>: <span class="hljs-number">22.99</span> }
    ],
    <span class="hljs-string">"bicycle"</span>: {
      <span class="hljs-string">"color"</span>: <span class="hljs-string">"red"</span>,
      <span class="hljs-string">"price"</span>: <span class="hljs-number">19.95</span>
    }
  }
}
</code></pre>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Task</td><td>JSONPath</td><td>Expected Output</td></tr>
</thead>
<tbody>
<tr>
<td>All book categories</td><td><code>$.store.book[*].category</code></td><td><code>["reference","fiction","fiction"]</code></td></tr>
<tr>
<td>Second book price</td><td><code>$.store.book[1].price</code></td><td><code>12.99</code></td></tr>
<tr>
<td>All prices &gt; 10</td><td><code>$.store.book[?(@.price&gt;10)].price</code></td><td><code>[12.99, 22.99]</code></td></tr>
<tr>
<td>Bicycle color</td><td><code>$.store.bicycle.color</code></td><td><code>"red"</code></td></tr>
</tbody>
</table>
</div><hr />
<h1 id="heading-16-summary-table">🧠 1️⃣6️⃣ Summary Table</h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Concept</td><td>JSON</td><td>JSONPath</td><td>REST Assured Usage</td></tr>
</thead>
<tbody>
<tr>
<td>Structure</td><td>Key-value</td><td>Query language</td><td>Data extraction</td></tr>
<tr>
<td>Syntax</td><td><code>{}</code> and <code>[]</code></td><td><code>$</code>, <code>.</code>, <code>[]</code>, <code>?()</code></td><td><code>jsonPath().get()</code></td></tr>
<tr>
<td>Used for</td><td>Representing data</td><td>Querying JSON</td><td>Validate/extract API response</td></tr>
<tr>
<td>Example</td><td><code>{ "name":"John" }</code></td><td><code>$.name</code></td><td><code>response.jsonPath().get("name")</code></td></tr>
</tbody>
</table>
</div><hr />
<p>Would you like me to give you a <strong>hands-on REST Assured project exercise</strong> (with sample APIs + JSONPath queries + assertions) that you can directly run in Eclipse or IntelliJ?<br />It will simulate a <strong>real e-commerce API</strong> (products + cart + payments).</p>
<h5 id="heading-you-said-2">You said:</h5>
<p>ok</p>
<h6 id="heading-chatgpt-said-2">ChatGPT said:</h6>
<p>Perfect 👍 let’s now move to a <strong>hands-on REST Assured project exercise</strong> using <strong>JSON + JSONPath</strong> with a <strong>realistic e-commerce API simulation</strong> —<br />so you can directly practice in <strong>Eclipse/IntelliJ</strong> or <strong>Postman</strong> and master data extraction + validation.</p>
<hr />
<h2 id="heading-realistic-scenario-e-commerce-rest-api">🏪 Realistic Scenario — E-Commerce REST API</h2>
<p>You’re testing an <strong>E-Commerce backend</strong> that handles:</p>
<ul>
<li><p>Product catalog</p>
</li>
<li><p>Cart operations</p>
</li>
<li><p>Order placement</p>
</li>
<li><p>Payment module</p>
</li>
</ul>
<p>Each API returns <strong>JSON</strong> responses you’ll validate using <strong>REST Assured</strong> + <strong>JSONPath</strong>.</p>
<hr />
<h2 id="heading-project-setup-pomxml">⚙️ Project Setup (pom.xml)</h2>
<p>Make sure these dependencies exist:</p>
<pre><code class="lang-java">&lt;dependencies&gt;
    &lt;!-- Rest Assured --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;io.rest-assured&lt;/groupId&gt;
        &lt;artifactId&gt;rest-assured&lt;/artifactId&gt;
        &lt;version&gt;<span class="hljs-number">5.4</span>.<span class="hljs-number">0</span>&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;!-- TestNG --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.testng&lt;/groupId&gt;
        &lt;artifactId&gt;testng&lt;/artifactId&gt;
        &lt;version&gt;<span class="hljs-number">7.10</span>.<span class="hljs-number">2</span>&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;!-- Hamcrest <span class="hljs-keyword">for</span> assertions --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.hamcrest&lt;/groupId&gt;
        &lt;artifactId&gt;hamcrest&lt;/artifactId&gt;
        &lt;version&gt;<span class="hljs-number">2.2</span>&lt;/version&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;
</code></pre>
<hr />
<h2 id="heading-step-1-sample-product-list-api-response">🧩 Step 1️⃣ — Sample Product List API Response</h2>
<h3 id="heading-get-products"><strong>GET /products</strong></h3>
<pre><code class="lang-java">{
  <span class="hljs-string">"store"</span>: {
    <span class="hljs-string">"products"</span>: [
      {
        <span class="hljs-string">"id"</span>: <span class="hljs-number">101</span>,
        <span class="hljs-string">"name"</span>: <span class="hljs-string">"Laptop"</span>,
        <span class="hljs-string">"brand"</span>: <span class="hljs-string">"HP"</span>,
        <span class="hljs-string">"price"</span>: <span class="hljs-number">75000</span>,
        <span class="hljs-string">"stock"</span>: <span class="hljs-number">10</span>,
        <span class="hljs-string">"category"</span>: <span class="hljs-string">"Electronics"</span>
      },
      {
        <span class="hljs-string">"id"</span>: <span class="hljs-number">102</span>,
        <span class="hljs-string">"name"</span>: <span class="hljs-string">"Smartphone"</span>,
        <span class="hljs-string">"brand"</span>: <span class="hljs-string">"Samsung"</span>,
        <span class="hljs-string">"price"</span>: <span class="hljs-number">35000</span>,
        <span class="hljs-string">"stock"</span>: <span class="hljs-number">25</span>,
        <span class="hljs-string">"category"</span>: <span class="hljs-string">"Mobiles"</span>
      },
      {
        <span class="hljs-string">"id"</span>: <span class="hljs-number">103</span>,
        <span class="hljs-string">"name"</span>: <span class="hljs-string">"Shoes"</span>,
        <span class="hljs-string">"brand"</span>: <span class="hljs-string">"Puma"</span>,
        <span class="hljs-string">"price"</span>: <span class="hljs-number">3500</span>,
        <span class="hljs-string">"stock"</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">"category"</span>: <span class="hljs-string">"Fashion"</span>
      }
    ]
  }
}
</code></pre>
<hr />
<h2 id="heading-step-2-jsonpath-queries-to-extract-data">🧠 Step 2️⃣ — JSONPath Queries to Extract Data</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Goal</td><td>JSONPath</td><td>Output</td></tr>
</thead>
<tbody>
<tr>
<td>All product names</td><td><code>$.store.products[*].name</code></td><td><code>["Laptop","Smartphone","Shoes"]</code></td></tr>
<tr>
<td>First product name</td><td><code>$.store.products[0].name</code></td><td><code>"Laptop"</code></td></tr>
<tr>
<td>All prices</td><td><code>$.store.products[*].price</code></td><td><code>[75000, 35000, 3500]</code></td></tr>
<tr>
<td>Brand of product with id 102</td><td><code>$.store.products[?(@.id==102)].brand</code></td><td><code>"Samsung"</code></td></tr>
<tr>
<td>Products with price &lt; 40000</td><td><code>$.store.products[?(@.price&lt;40000)].name</code></td><td><code>["Smartphone","Shoes"]</code></td></tr>
</tbody>
</table>
</div><p>👉 Try these in <a target="_blank" href="https://jsonpath.com">https://jsonpath.com</a> to visualize them live.</p>
<hr />
<h2 id="heading-step-3-rest-assured-test-code">💻 Step 3️⃣ — REST Assured Test Code</h2>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.ecommerce.api;

<span class="hljs-keyword">import</span> io.restassured.path.json.JsonPath;
<span class="hljs-keyword">import</span> io.restassured.response.Response;
<span class="hljs-keyword">import</span> org.testng.annotations.Test;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.MatcherAssert.assertThat;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductAPITest</span> </span>{

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">verifyProductListAPI</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Fake endpoint for demo (you can mock it using ReqRes or Postman Mock)</span>
        Response response = given()
                .baseUri(<span class="hljs-string">"https://api.mocki.io/v2/5185415ba171ea3a00704eed"</span>) <span class="hljs-comment">// use your endpoint</span>
            .when()
                .get(<span class="hljs-string">"/products"</span>);

        <span class="hljs-comment">// Validate status code</span>
        response.then().statusCode(<span class="hljs-number">200</span>);

        JsonPath json = response.jsonPath();

        <span class="hljs-comment">// Extract values</span>
        String firstProduct = json.getString(<span class="hljs-string">"store.products[0].name"</span>);
        <span class="hljs-keyword">int</span> secondProductPrice = json.getInt(<span class="hljs-string">"store.products[1].price"</span>);
        <span class="hljs-keyword">int</span> totalProducts = json.getList(<span class="hljs-string">"store.products"</span>).size();

        System.out.println(<span class="hljs-string">"First Product: "</span> + firstProduct);
        System.out.println(<span class="hljs-string">"Second Product Price: "</span> + secondProductPrice);
        System.out.println(<span class="hljs-string">"Total Products: "</span> + totalProducts);

        <span class="hljs-comment">// Assertions</span>
        assertThat(firstProduct, equalTo(<span class="hljs-string">"Laptop"</span>));
        assertThat(secondProductPrice, greaterThan(<span class="hljs-number">30000</span>));
        assertThat(totalProducts, equalTo(<span class="hljs-number">3</span>));
    }
}
</code></pre>
<hr />
<h2 id="heading-step-4-extract-and-validate-with-filters">🧩 Step 4️⃣ — Extract and Validate with Filters</h2>
<pre><code class="lang-java"><span class="hljs-meta">@Test</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">verifyFilterProducts</span><span class="hljs-params">()</span> </span>{
    Response response = get(<span class="hljs-string">"https://mockapi.io/fake-store/products"</span>);
    JsonPath json = response.jsonPath();

    <span class="hljs-comment">// Extract product names cheaper than 40000</span>
    List&lt;String&gt; cheapProducts = json.getList(<span class="hljs-string">"store.products.findAll { it.price &lt; 40000 }.name"</span>);
    System.out.println(<span class="hljs-string">"Affordable Products: "</span> + cheapProducts);

    <span class="hljs-comment">// Assert</span>
    assertThat(cheapProducts, hasItems(<span class="hljs-string">"Smartphone"</span>, <span class="hljs-string">"Shoes"</span>));
}
</code></pre>
<hr />
<h2 id="heading-step-5-simulated-payment-api">💰 Step 5️⃣ — Simulated Payment API</h2>
<h3 id="heading-post-payment"><strong>POST /payment</strong></h3>
<pre><code class="lang-java">{
  <span class="hljs-string">"paymentId"</span>: <span class="hljs-string">"P12345"</span>,
  <span class="hljs-string">"orderId"</span>: <span class="hljs-string">"O9876"</span>,
  <span class="hljs-string">"amount"</span>: <span class="hljs-number">35000</span>,
  <span class="hljs-string">"method"</span>: <span class="hljs-string">"UPI"</span>,
  <span class="hljs-string">"status"</span>: <span class="hljs-string">"Success"</span>,
  <span class="hljs-string">"transaction"</span>: {
    <span class="hljs-string">"timestamp"</span>: <span class="hljs-string">"2025-11-11T08:30:00Z"</span>,
    <span class="hljs-string">"bankRef"</span>: <span class="hljs-string">"ICIC12345"</span>,
    <span class="hljs-string">"currency"</span>: <span class="hljs-string">"INR"</span>
  }
}
</code></pre>
<h3 id="heading-validation-example">✅ Validation Example</h3>
<pre><code class="lang-java"><span class="hljs-meta">@Test</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">verifyPaymentResponse</span><span class="hljs-params">()</span> </span>{
    String responseBody = <span class="hljs-string">"{ \"paymentId\":\"P12345\", \"orderId\":\"O9876\", \"amount\":35000, \"method\":\"UPI\", \"status\":\"Success\" }"</span>;

    JsonPath json = <span class="hljs-keyword">new</span> JsonPath(responseBody);

    <span class="hljs-comment">// Extract</span>
    String status = json.getString(<span class="hljs-string">"status"</span>);
    <span class="hljs-keyword">int</span> amount = json.getInt(<span class="hljs-string">"amount"</span>);

    <span class="hljs-comment">// Assert</span>
    assertThat(status, equalTo(<span class="hljs-string">"Success"</span>));
    assertThat(amount, greaterThan(<span class="hljs-number">0</span>));
}
</code></pre>
<hr />
<h2 id="heading-step-6-jsonpath-practice-challenges-for-you">🧾 Step 6️⃣ — JSONPath Practice Challenges for You 🎯</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Task</td><td>JSONPath</td><td>Expected Result</td></tr>
</thead>
<tbody>
<tr>
<td>Get total number of products</td><td><code>$.store.products.length()</code></td><td><code>3</code></td></tr>
<tr>
<td>Get all categories</td><td><code>$.store.products[*].category</code></td><td><code>["Electronics","Mobiles","Fashion"]</code></td></tr>
<tr>
<td>Find product with minimum price</td><td><code>$.store.products.min { it.price }.name</code></td><td><code>"Shoes"</code></td></tr>
<tr>
<td>Get all stock quantities</td><td><code>$.store.products[*].stock</code></td><td><code>[10,25,100]</code></td></tr>
<tr>
<td>Get products with brand "HP"</td><td><code>$.store.products[?(@.brand=='HP')].name</code></td><td><code>"Laptop"</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-step-7-integration-idea-for-real-practice">🧠 Step 7️⃣ — Integration Idea (for Real Practice)</h2>
<p>You can simulate the whole flow:</p>
<ol>
<li><p><strong>GET /products</strong> → extract product ID &amp; price</p>
</li>
<li><p><strong>POST /cart</strong> → add product to cart</p>
</li>
<li><p><strong>POST /order</strong> → place order</p>
</li>
<li><p><strong>POST /payment</strong> → simulate payment success</p>
</li>
<li><p><strong>GET /order/{id}</strong> → verify order status = "Completed"</p>
</li>
</ol>
<p>Each response is JSON — you’ll extract and assert data with <strong>JsonPath</strong>.</p>
<hr />
<h2 id="heading-step-8-recommended-practice-tools">🧰 Step 8️⃣ — Recommended Practice Tools</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Tool</td><td>Use</td><td>Link</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Postman</strong></td><td>Create Mock APIs</td><td><a target="_blank" href="https://www.postman.com/">https://www.postman.com/</a></td></tr>
<tr>
<td><strong>ReqRes</strong></td><td>Public JSON API</td><td><a target="_blank" href="https://reqres.in/">https://reqres.in/</a></td></tr>
<tr>
<td><strong>MockAPI.io</strong></td><td>Custom JSON endpoints</td><td><a target="_blank" href="https://mockapi.io/">https://mockapi.io/</a></td></tr>
<tr>
<td><strong>JSONPath.com</strong></td><td>Test JSONPath queries</td><td><a target="_blank" href="https://jsonpath.com/">https://jsonpath.com/</a></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-summary">🏁 Summary</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Concept</td><td>Where Used</td><td>Tool / Syntax</td></tr>
</thead>
<tbody>
<tr>
<td>JSON</td><td>API Response</td><td><code>{ "key": "value" }</code></td></tr>
<tr>
<td>JSONPath</td><td>Query data</td><td><code>$.store.products[0].name</code></td></tr>
<tr>
<td>REST Assured</td><td>Validate response</td><td><code>response.jsonPath().get("key")</code></td></tr>
<tr>
<td>Hamcrest</td><td>Assertions</td><td><code>assertThat(value, equalTo("Success"))</code></td></tr>
<tr>
<td>Groovy</td><td>Advanced filters</td><td><code>findAll { it.price &lt; 40000 }</code></td></tr>
</tbody>
</table>
</div><hr />
<p>Would you like me to add the <strong>next part</strong> —</p>
<blockquote>
<p>🔹 “E-Commerce Full Flow API Automation Project” (Products → Cart → Payment → Assertions)<br />with <strong>end-to-end REST Assured TestNG code</strong> and reusable JSONPath extraction?</p>
</blockquote>
<p>It’ll be a real-world ready mini framework example.</p>
<h5 id="heading-you-said-3">You said:</h5>
<p>yes</p>
<h6 id="heading-chatgpt-said-3">ChatGPT said:</h6>
<p>Perfect ⚡ — let’s build your <strong>End-to-End E-Commerce API Automation Project</strong> using <strong>REST Assured + TestNG + JSONPath + Hamcrest</strong>.</p>
<p>We’ll simulate a <strong>real automation tester workflow</strong> for:<br />🛒 Products → 🧺 Cart → 📦 Order → 💳 Payment</p>
<p>This will give you a <em>mini automation framework</em> you can run in Eclipse or IntelliJ — perfect for resume projects and interviews.</p>
<hr />
<h2 id="heading-1-project-structure">🧱 1️⃣ PROJECT STRUCTURE</h2>
<pre><code class="lang-java">ecommerce-api-automation/
│
├── pom.xml
├── src/
│   └── test/java/
│       └── com/ecommerce/tests/
│           ├── BaseTest.java
│           ├── ProductTest.java
│           ├── CartTest.java
│           ├── OrderTest.java
│           └── PaymentTest.java
└── testng.xml
</code></pre>
<hr />
<h2 id="heading-2-pomxml-dependencies">⚙️ 2️⃣ pom.xml Dependencies</h2>
<pre><code class="lang-java">&lt;dependencies&gt;
    &lt;!-- REST Assured --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;io.rest-assured&lt;/groupId&gt;
        &lt;artifactId&gt;rest-assured&lt;/artifactId&gt;
        &lt;version&gt;<span class="hljs-number">5.4</span>.<span class="hljs-number">0</span>&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;!-- TestNG --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.testng&lt;/groupId&gt;
        &lt;artifactId&gt;testng&lt;/artifactId&gt;
        &lt;version&gt;<span class="hljs-number">7.10</span>.<span class="hljs-number">2</span>&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;!-- Hamcrest --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.hamcrest&lt;/groupId&gt;
        &lt;artifactId&gt;hamcrest&lt;/artifactId&gt;
        &lt;version&gt;<span class="hljs-number">2.2</span>&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!-- JSON --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.json&lt;/groupId&gt;
        &lt;artifactId&gt;json&lt;/artifactId&gt;
        &lt;version&gt;<span class="hljs-number">20240303</span>&lt;/version&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;
</code></pre>
<hr />
<h2 id="heading-3-mock-api-setup-you-can-use-any-of-these">🌐 3️⃣ Mock API Setup (you can use any of these)</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Tool</td><td>Use</td><td>URL</td></tr>
</thead>
<tbody>
<tr>
<td><strong>ReqRes</strong></td><td>Ready-made REST API</td><td><a target="_blank" href="https://reqres.in">https://reqres.in</a></td></tr>
<tr>
<td><strong>MockAPI.io</strong></td><td>Create custom endpoints</td><td><a target="_blank" href="https://mockapi.io">https://mockapi.io</a></td></tr>
<tr>
<td><strong>Postman Mock Server</strong></td><td>Create &amp; test local API mocks</td><td>https://postman.com</td></tr>
</tbody>
</table>
</div><p>If you use <strong>MockAPI.io</strong>, create 4 endpoints:</p>
<pre><code class="lang-java">GET   /products
POST  /cart
POST  /order
POST  /payment
</code></pre>
<p>Each will return simple JSON data.</p>
<hr />
<h2 id="heading-4-basetestjava">🧩 4️⃣ BaseTest.java</h2>
<p>Centralized setup (Base URI and reusable methods).</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.ecommerce.tests;

<span class="hljs-keyword">import</span> io.restassured.RestAssured;
<span class="hljs-keyword">import</span> io.restassured.response.Response;
<span class="hljs-keyword">import</span> org.testng.annotations.BeforeClass;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BaseTest</span> </span>{

    <span class="hljs-meta">@BeforeClass</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
        RestAssured.baseURI = <span class="hljs-string">"https://mockapi.io/api/v1"</span>; <span class="hljs-comment">// Replace with your mock API base URL</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Response <span class="hljs-title">getRequest</span><span class="hljs-params">(String endpoint)</span> </span>{
        <span class="hljs-keyword">return</span> RestAssured
                .given()
                .when()
                .get(endpoint)
                .then()
                .extract()
                .response();
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Response <span class="hljs-title">postRequest</span><span class="hljs-params">(String endpoint, Object body)</span> </span>{
        <span class="hljs-keyword">return</span> RestAssured
                .given()
                .header(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>)
                .body(body)
                .when()
                .post(endpoint)
                .then()
                .extract()
                .response();
    }
}
</code></pre>
<hr />
<h2 id="heading-5-producttestjava-fetch-and-validate-products">🛍️ 5️⃣ ProductTest.java — Fetch and Validate Products</h2>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.ecommerce.tests;

<span class="hljs-keyword">import</span> io.restassured.path.json.JsonPath;
<span class="hljs-keyword">import</span> io.restassured.response.Response;
<span class="hljs-keyword">import</span> org.testng.annotations.Test;

<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.MatcherAssert.assertThat;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductTest</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseTest</span> </span>{

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">verifyProductList</span><span class="hljs-params">()</span> </span>{
        Response response = getRequest(<span class="hljs-string">"/products"</span>);
        response.then().statusCode(<span class="hljs-number">200</span>);

        JsonPath json = response.jsonPath();

        <span class="hljs-comment">// Validate</span>
        List&lt;String&gt; productNames = json.getList(<span class="hljs-string">"store.products.name"</span>);
        System.out.println(<span class="hljs-string">"Products: "</span> + productNames);

        assertThat(productNames, hasItems(<span class="hljs-string">"Laptop"</span>, <span class="hljs-string">"Smartphone"</span>, <span class="hljs-string">"Shoes"</span>));
        assertThat(json.getInt(<span class="hljs-string">"store.products.size()"</span>), greaterThan(<span class="hljs-number">0</span>));

        <span class="hljs-comment">// Extract one product for next step</span>
        <span class="hljs-keyword">int</span> selectedProductId = json.getInt(<span class="hljs-string">"store.products[1].id"</span>);
        System.setProperty(<span class="hljs-string">"productId"</span>, String.valueOf(selectedProductId));
    }
}
</code></pre>
<hr />
<h2 id="heading-6-carttestjava-add-product-to-cart">🧺 6️⃣ CartTest.java — Add Product to Cart</h2>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.ecommerce.tests;

<span class="hljs-keyword">import</span> io.restassured.path.json.JsonPath;
<span class="hljs-keyword">import</span> io.restassured.response.Response;
<span class="hljs-keyword">import</span> org.json.JSONObject;
<span class="hljs-keyword">import</span> org.testng.annotations.Test;

<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.MatcherAssert.assertThat;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CartTest</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseTest</span> </span>{

    <span class="hljs-meta">@Test(dependsOnMethods = "com.ecommerce.tests.ProductTest.verifyProductList")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addToCart</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">int</span> productId = Integer.parseInt(System.getProperty(<span class="hljs-string">"productId"</span>));

        JSONObject request = <span class="hljs-keyword">new</span> JSONObject();
        request.put(<span class="hljs-string">"productId"</span>, productId);
        request.put(<span class="hljs-string">"quantity"</span>, <span class="hljs-number">2</span>);

        Response response = postRequest(<span class="hljs-string">"/cart"</span>, request.toString());
        response.then().statusCode(<span class="hljs-number">201</span>);

        JsonPath json = response.jsonPath();

        assertThat(json.getString(<span class="hljs-string">"message"</span>), equalTo(<span class="hljs-string">"Item added to cart"</span>));
        assertThat(json.getInt(<span class="hljs-string">"cart.quantity"</span>), equalTo(<span class="hljs-number">2</span>));

        String cartId = json.getString(<span class="hljs-string">"cart.id"</span>);
        System.setProperty(<span class="hljs-string">"cartId"</span>, cartId);
    }
}
</code></pre>
<hr />
<h2 id="heading-7-ordertestjava-place-an-order">📦 7️⃣ OrderTest.java — Place an Order</h2>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.ecommerce.tests;

<span class="hljs-keyword">import</span> io.restassured.path.json.JsonPath;
<span class="hljs-keyword">import</span> io.restassured.response.Response;
<span class="hljs-keyword">import</span> org.json.JSONObject;
<span class="hljs-keyword">import</span> org.testng.annotations.Test;

<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.MatcherAssert.assertThat;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrderTest</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseTest</span> </span>{

    <span class="hljs-meta">@Test(dependsOnMethods = "com.ecommerce.tests.CartTest.addToCart")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">placeOrder</span><span class="hljs-params">()</span> </span>{
        String cartId = System.getProperty(<span class="hljs-string">"cartId"</span>);

        JSONObject request = <span class="hljs-keyword">new</span> JSONObject();
        request.put(<span class="hljs-string">"cartId"</span>, cartId);
        request.put(<span class="hljs-string">"address"</span>, <span class="hljs-string">"Bhubaneswar, Odisha"</span>);

        Response response = postRequest(<span class="hljs-string">"/order"</span>, request.toString());
        response.then().statusCode(<span class="hljs-number">201</span>);

        JsonPath json = response.jsonPath();

        assertThat(json.getString(<span class="hljs-string">"status"</span>), equalTo(<span class="hljs-string">"Order Placed"</span>));
        assertThat(json.getString(<span class="hljs-string">"orderId"</span>), notNullValue());

        System.setProperty(<span class="hljs-string">"orderId"</span>, json.getString(<span class="hljs-string">"orderId"</span>));
    }
}
</code></pre>
<hr />
<h2 id="heading-8-paymenttestjava-verify-payment-success">💳 8️⃣ PaymentTest.java — Verify Payment Success</h2>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.ecommerce.tests;

<span class="hljs-keyword">import</span> io.restassured.path.json.JsonPath;
<span class="hljs-keyword">import</span> io.restassured.response.Response;
<span class="hljs-keyword">import</span> org.json.JSONObject;
<span class="hljs-keyword">import</span> org.testng.annotations.Test;

<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.MatcherAssert.assertThat;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PaymentTest</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseTest</span> </span>{

    <span class="hljs-meta">@Test(dependsOnMethods = "com.ecommerce.tests.OrderTest.placeOrder")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">verifyPaymentSuccess</span><span class="hljs-params">()</span> </span>{
        String orderId = System.getProperty(<span class="hljs-string">"orderId"</span>);

        JSONObject request = <span class="hljs-keyword">new</span> JSONObject();
        request.put(<span class="hljs-string">"orderId"</span>, orderId);
        request.put(<span class="hljs-string">"method"</span>, <span class="hljs-string">"UPI"</span>);
        request.put(<span class="hljs-string">"amount"</span>, <span class="hljs-number">35000</span>);

        Response response = postRequest(<span class="hljs-string">"/payment"</span>, request.toString());
        response.then().statusCode(<span class="hljs-number">200</span>);

        JsonPath json = response.jsonPath();

        assertThat(json.getString(<span class="hljs-string">"status"</span>), equalTo(<span class="hljs-string">"Success"</span>));
        assertThat(json.getInt(<span class="hljs-string">"amount"</span>), greaterThan(<span class="hljs-number">0</span>));
        assertThat(json.getString(<span class="hljs-string">"transaction.currency"</span>), equalTo(<span class="hljs-string">"INR"</span>));

        System.out.println(<span class="hljs-string">"✅ Payment successful for order: "</span> + orderId);
    }
}
</code></pre>
<hr />
<h2 id="heading-9-testngxml">⚡ 9️⃣ testng.xml</h2>
<p>Run all tests in proper sequence:</p>
<pre><code class="lang-java">&lt;!DOCTYPE suite SYSTEM <span class="hljs-string">"https://testng.org/testng-1.0.dtd"</span>&gt;
&lt;suite name=<span class="hljs-string">"E-Commerce API Suite"</span>&gt;
    &lt;test name=<span class="hljs-string">"API Tests"</span>&gt;
        &lt;classes&gt;
            &lt;<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">name</span></span>=<span class="hljs-string">"com.ecommerce.tests.ProductTest"</span>/&gt;
            &lt;<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">name</span></span>=<span class="hljs-string">"com.ecommerce.tests.CartTest"</span>/&gt;
            &lt;<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">name</span></span>=<span class="hljs-string">"com.ecommerce.tests.OrderTest"</span>/&gt;
            &lt;<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">name</span></span>=<span class="hljs-string">"com.ecommerce.tests.PaymentTest"</span>/&gt;
        &lt;/classes&gt;
    &lt;/test&gt;
&lt;/suite&gt;
</code></pre>
<hr />
<h2 id="heading-what-you-learn-here">🧠 🔟 What You Learn Here</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Concept</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Chaining Tests</strong></td><td>Pass data (productId, cartId, orderId) between tests dynamically</td></tr>
<tr>
<td><strong>JSONPath Extraction</strong></td><td>Parse and assert JSON response</td></tr>
<tr>
<td><strong>Hamcrest Matchers</strong></td><td>Perform readable validations</td></tr>
<tr>
<td><strong>Reusable Methods</strong></td><td>Centralize setup &amp; requests</td></tr>
<tr>
<td><strong>End-to-End Flow</strong></td><td>Realistic automation pattern</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-11-how-to-practice">🧰 1️⃣1️⃣ How to Practice</h2>
<ol>
<li><p>Go to <a target="_blank" href="https://mockapi.io"><strong>https://mockapi.io</strong></a></p>
</li>
<li><p>Create a new project</p>
</li>
<li><p>Add endpoints <code>/products</code>, <code>/cart</code>, <code>/order</code>, <code>/payment</code> with JSON similar to examples above</p>
</li>
<li><p>Copy the base URL into your <code>BaseTest.java</code></p>
</li>
<li><p>Run from TestNG or <code>mvn test</code></p>
</li>
</ol>
<p>You’ll see each test depend on the previous one — forming a <strong>complete e-commerce flow</strong>.</p>
<hr />
<h2 id="heading-12-output-example-console">🧾 1️⃣2️⃣ Output Example (Console)</h2>
<pre><code class="lang-java">Products: [Laptop, Smartphone, Shoes]
Affordable Products: [Smartphone, Shoes]
Item added to cart
✅ Order placed successfully
✅ Payment successful <span class="hljs-keyword">for</span> order: O12345
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Authentication in RestAssured]]></title><description><![CDATA[authentication is a core part of API testing in RestAssured, and mastering it is must-have for automation testers.
Let’s go step-by-step — covering all authentication types, their usage, code examples, when to use, and common errors.

🔐 Authenticati...]]></description><link>https://shreenibas-api-restassured.hashnode.dev/authentication-in-restassured</link><guid isPermaLink="true">https://shreenibas-api-restassured.hashnode.dev/authentication-in-restassured</guid><category><![CDATA[@shreenibas]]></category><dc:creator><![CDATA[Shreenibas Samal]]></dc:creator><pubDate>Mon, 20 Oct 2025 10:20:08 GMT</pubDate><content:encoded><![CDATA[<p>authentication is a <strong>core part of API testing in RestAssured</strong>, and mastering it is <strong>must-have for automation testers</strong>.</p>
<p>Let’s go <strong>step-by-step</strong> — covering <strong>all authentication types</strong>, their <strong>usage</strong>, <strong>code examples</strong>, <strong>when to use</strong>, and <strong>common errors</strong>.</p>
<hr />
<h1 id="heading-authentication-in-restassured-complete-guide">🔐 Authentication in RestAssured — Complete Guide</h1>
<p>Authentication means <strong>verifying the identity</strong> of the API client (you or your test).<br />Most APIs require authentication to ensure only authorized users can access data.</p>
<hr />
<h2 id="heading-1-no-authentication-open-api">🧩 1️⃣ No Authentication (Open API)</h2>
<h3 id="heading-description">👉 Description</h3>
<ul>
<li><p>Public APIs that don’t require credentials.</p>
</li>
<li><p>Example: Open weather APIs, currency converters.</p>
</li>
</ul>
<h3 id="heading-example">✅ Example</h3>
<pre><code class="lang-java">given()
    .when()
    .get(<span class="hljs-string">"https://api.zippopotam.us/us/90210"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>)
    .log().all();
</code></pre>
<h3 id="heading-when-to-use">💡 When to use</h3>
<ul>
<li><p>Open/public data endpoints</p>
</li>
<li><p>Simple testing or health check APIs</p>
</li>
</ul>
<hr />
<h2 id="heading-2-basic-authentication">🧩 2️⃣ Basic Authentication</h2>
<h3 id="heading-description-1">👉 Description</h3>
<ul>
<li><p>The simplest authentication type.</p>
</li>
<li><p>Sends username and password in the header (Base64 encoded).</p>
</li>
</ul>
<blockquote>
<p>⚠️ Not secure if used over HTTP (always use HTTPS).</p>
</blockquote>
<h3 id="heading-syntax">✅ Syntax</h3>
<pre><code class="lang-java">given()
    .auth()
    .basic(<span class="hljs-string">"username"</span>, <span class="hljs-string">"password"</span>)
.when()
    .get(<span class="hljs-string">"https://api.example.com/users"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>);
</code></pre>
<h3 id="heading-alternate-way-preemptive">✅ Alternate Way (Preemptive)</h3>
<pre><code class="lang-java">given()
    .auth()
    .preemptive()
    .basic(<span class="hljs-string">"username"</span>, <span class="hljs-string">"password"</span>)
.when()
    .get(<span class="hljs-string">"https://api.example.com/users"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>);
</code></pre>
<h3 id="heading-difference">💡 Difference:</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Type</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>basic()</code></td><td>Server first sends 401, then client sends credentials</td></tr>
<tr>
<td><code>preemptive().basic()</code></td><td>Client sends credentials in the first request itself (faster)</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-3-digest-authentication">🧩 3️⃣ Digest Authentication</h2>
<h3 id="heading-description-2">👉 Description</h3>
<ul>
<li><p>More secure version of Basic Authentication.</p>
</li>
<li><p>Uses a hash of the password instead of sending it in plain text.</p>
</li>
<li><p>Common in legacy enterprise systems.</p>
</li>
</ul>
<h3 id="heading-example-1">✅ Example</h3>
<pre><code class="lang-java">given()
    .auth()
    .digest(<span class="hljs-string">"username"</span>, <span class="hljs-string">"password"</span>)
.when()
    .get(<span class="hljs-string">"https://api.example.com/secure/data"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>);
</code></pre>
<h3 id="heading-when-to-use-1">💡 When to use</h3>
<ul>
<li>APIs supporting Digest Authentication (older web servers or internal APIs)</li>
</ul>
<hr />
<h2 id="heading-4-bearer-token-oauth2-token">🧩 4️⃣ Bearer Token / OAuth2 Token</h2>
<h3 id="heading-description-3">👉 Description</h3>
<ul>
<li><p>The most common modern authentication.</p>
</li>
<li><p>Token is issued after login and sent with every request.</p>
</li>
<li><p>Used in most <strong>REST APIs (JWT, OAuth2, API keys)</strong>.</p>
</li>
</ul>
<h3 id="heading-example-2">✅ Example</h3>
<pre><code class="lang-java">given()
    .auth()
    .oauth2(<span class="hljs-string">"your_token_here"</span>)
.when()
    .get(<span class="hljs-string">"https://api.github.com/user"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>);
</code></pre>
<p>Or with Header manually:</p>
<pre><code class="lang-java">given()
    .header(<span class="hljs-string">"Authorization"</span>, <span class="hljs-string">"Bearer your_token_here"</span>)
.when()
    .get(<span class="hljs-string">"https://api.github.com/user"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>);
</code></pre>
<h3 id="heading-when-to-use-2">💡 When to use</h3>
<ul>
<li>APIs using JWT, OAuth2, or token-based sessions (GitHub, Google, Jira, etc.)</li>
</ul>
<hr />
<h2 id="heading-5-api-key-authentication">🧩 5️⃣ API Key Authentication</h2>
<h3 id="heading-description-4">👉 Description</h3>
<ul>
<li><p>Common for public APIs where a single key identifies the client.</p>
</li>
<li><p>Key is sent as a <strong>query param</strong> or <strong>header</strong>.</p>
</li>
</ul>
<h3 id="heading-example-header">✅ Example (Header)</h3>
<pre><code class="lang-java">given()
    .header(<span class="hljs-string">"x-api-key"</span>, <span class="hljs-string">"12345abcde"</span>)
.when()
    .get(<span class="hljs-string">"https://api.weatherapi.com/v1/current.json?q=London"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>);
</code></pre>
<h3 id="heading-example-query-param">✅ Example (Query Param)</h3>
<pre><code class="lang-java">given()
    .queryParam(<span class="hljs-string">"appid"</span>, <span class="hljs-string">"your_api_key"</span>)
    .queryParam(<span class="hljs-string">"q"</span>, <span class="hljs-string">"London"</span>)
.when()
    .get(<span class="hljs-string">"https://api.openweathermap.org/data/2.5/weather"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>);
</code></pre>
<h3 id="heading-when-to-use-3">💡 When to use</h3>
<ul>
<li>External or third-party APIs (Google Maps, OpenWeather, NewsAPI, etc.)</li>
</ul>
<hr />
<h2 id="heading-6-form-authentication">🧩 6️⃣ Form Authentication</h2>
<h3 id="heading-description-5">👉 Description</h3>
<ul>
<li><p>Used when the application authenticates using a login form (HTML form submission).</p>
</li>
<li><p>RestAssured can simulate form-based login.</p>
</li>
</ul>
<h3 id="heading-example-3">✅ Example</h3>
<pre><code class="lang-java">given()
    .auth()
    .form(<span class="hljs-string">"username"</span>, <span class="hljs-string">"password"</span>, <span class="hljs-keyword">new</span> FormAuthConfig(<span class="hljs-string">"/login"</span>, <span class="hljs-string">"uname"</span>, <span class="hljs-string">"pwd"</span>))
.when()
    .get(<span class="hljs-string">"https://app.example.com/home"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>);
</code></pre>
<h3 id="heading-parameters">💡 Parameters:</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Argument</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>/login</code></td><td>Login endpoint</td></tr>
<tr>
<td><code>uname</code></td><td>Username field name</td></tr>
<tr>
<td><code>pwd</code></td><td>Password field name</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-7-oauth-10">🧩 7️⃣ OAuth 1.0</h2>
<h3 id="heading-description-6">👉 Description</h3>
<ul>
<li><p>Older version of OAuth (used by Twitter API v1).</p>
</li>
<li><p>Uses consumer key, secret, token, and token secret.</p>
</li>
</ul>
<h3 id="heading-example-4">✅ Example</h3>
<pre><code class="lang-java">given()
    .auth()
    .oauth(<span class="hljs-string">"consumerKey"</span>, <span class="hljs-string">"consumerSecret"</span>, <span class="hljs-string">"accessToken"</span>, <span class="hljs-string">"secretToken"</span>)
.when()
    .get(<span class="hljs-string">"https://api.twitter.com/1.1/statuses/home_timeline.json"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>);
</code></pre>
<h3 id="heading-when-to-use-4">💡 When to use</h3>
<ul>
<li>Only when working with legacy APIs (Twitter API v1.1, some banking APIs)</li>
</ul>
<hr />
<h2 id="heading-8-oauth-20-access-token-flow">🧩 8️⃣ OAuth 2.0 (Access Token Flow)</h2>
<h3 id="heading-description-7">👉 Description</h3>
<ul>
<li><p>The <strong>modern standard</strong> for authentication (used by Google, GitHub, Azure, etc.)</p>
</li>
<li><p>Involves:</p>
<ol>
<li><p>Getting access token using client credentials.</p>
</li>
<li><p>Using token in further requests.</p>
</li>
</ol>
</li>
</ul>
<h3 id="heading-step-1-get-token">✅ Step 1: Get Token</h3>
<pre><code class="lang-java">Response tokenResponse = given()
    .formParam(<span class="hljs-string">"client_id"</span>, <span class="hljs-string">"myClientId"</span>)
    .formParam(<span class="hljs-string">"client_secret"</span>, <span class="hljs-string">"mySecret"</span>)
    .formParam(<span class="hljs-string">"grant_type"</span>, <span class="hljs-string">"client_credentials"</span>)
.when()
    .post(<span class="hljs-string">"https://authserver.com/oauth/token"</span>);

String accessToken = tokenResponse.jsonPath().getString(<span class="hljs-string">"access_token"</span>);
</code></pre>
<h3 id="heading-step-2-use-token">✅ Step 2: Use Token</h3>
<pre><code class="lang-java">given()
    .header(<span class="hljs-string">"Authorization"</span>, <span class="hljs-string">"Bearer "</span> + accessToken)
.when()
    .get(<span class="hljs-string">"https://api.example.com/resource"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>);
</code></pre>
<hr />
<h2 id="heading-9-session-cookie-based-authentication">🧩 9️⃣ Session / Cookie Based Authentication</h2>
<h3 id="heading-description-8">👉 Description</h3>
<ul>
<li><p>Used in traditional web apps.</p>
</li>
<li><p>You first log in → receive a <strong>session cookie</strong> → use it for later requests.</p>
</li>
</ul>
<h3 id="heading-example-5">✅ Example</h3>
<pre><code class="lang-java">Response res = given()
    .formParam(<span class="hljs-string">"username"</span>, <span class="hljs-string">"admin"</span>)
    .formParam(<span class="hljs-string">"password"</span>, <span class="hljs-string">"admin123"</span>)
.when()
    .post(<span class="hljs-string">"https://app.example.com/login"</span>);

String sessionId = res.getCookie(<span class="hljs-string">"JSESSIONID"</span>);

given()
    .cookie(<span class="hljs-string">"JSESSIONID"</span>, sessionId)
.when()
    .get(<span class="hljs-string">"https://app.example.com/dashboard"</span>)
.then()
    .statusCode(<span class="hljs-number">200</span>);
</code></pre>
<hr />
<h2 id="heading-10-summary-table">🧠 10️⃣ Summary Table</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Type</td><td>Security Level</td><td>Use Case</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><strong>No Auth</strong></td><td>❌</td><td>Open/Public APIs</td><td>Public weather APIs</td></tr>
<tr>
<td><strong>Basic</strong></td><td>⚠️ Low</td><td>Legacy systems</td><td>Internal APIs</td></tr>
<tr>
<td><strong>Digest</strong></td><td>✅ Medium</td><td>Enterprise</td><td>Internal/secure APIs</td></tr>
<tr>
<td><strong>Bearer/OAuth2</strong></td><td>🔒 High</td><td>Modern APIs</td><td>GitHub, Google, Jira</td></tr>
<tr>
<td><strong>API Key</strong></td><td>✅ Medium</td><td>Third-party</td><td>OpenWeather, NewsAPI</td></tr>
<tr>
<td><strong>Form Auth</strong></td><td>⚠️ Low</td><td>Web apps</td><td>Login forms</td></tr>
<tr>
<td><strong>OAuth1.0</strong></td><td>✅ Medium</td><td>Legacy OAuth</td><td>Twitter v1</td></tr>
<tr>
<td><strong>Session/Cookie</strong></td><td>⚠️ Medium</td><td>Web portals</td><td>Old-style logins</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-11-best-practices">⚙️ 11️⃣ Best Practices</h2>
<p>✅ Always use <strong>HTTPS</strong> (never send credentials over HTTP)<br />✅ Use <strong>Config/Properties file</strong> for credentials, not hardcoded values<br />✅ Use <strong>token refresh logic</strong> for long-running tests<br />✅ Parameterize <strong>auth tokens</strong> for CI/CD (Jenkins secrets or environment variables)<br />✅ Add <strong>utility methods</strong> for token retrieval and reuse</p>
]]></content:encoded></item><item><title><![CDATA[Xml  & Json]]></title><description><![CDATA[🧩 1. What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format.It is easy for humans to read and write, and easy for machines to parse and generate.
Used in:

API responses and requests

Config files

Data transfer bet...]]></description><link>https://shreenibas-api-restassured.hashnode.dev/xml-and-json</link><guid isPermaLink="true">https://shreenibas-api-restassured.hashnode.dev/xml-and-json</guid><category><![CDATA[@shreenibas]]></category><dc:creator><![CDATA[Shreenibas Samal]]></dc:creator><pubDate>Sun, 19 Oct 2025 02:25:10 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-1-what-is-json">🧩 <strong>1. What is JSON?</strong></h2>
<p><strong>JSON (JavaScript Object Notation)</strong> is a lightweight data-interchange format.<br />It is easy for humans to read and write, and easy for machines to parse and generate.</p>
<p>Used in:</p>
<ul>
<li><p>API responses and requests</p>
</li>
<li><p>Config files</p>
</li>
<li><p>Data transfer between front-end and back-end</p>
</li>
</ul>
<hr />
<h2 id="heading-2-json-syntax-rules">⚙️ <strong>2. JSON Syntax Rules</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Concept</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Object</strong></td><td>Collection of key-value pairs inside <code>{}</code></td><td><code>{ "name": "John", "age": 30 }</code></td></tr>
<tr>
<td><strong>Array</strong></td><td>Ordered list of values inside <code>[]</code></td><td><code>[ "apple", "banana", "cherry" ]</code></td></tr>
<tr>
<td><strong>Key</strong></td><td>Always a string, wrapped in quotes</td><td><code>"name"</code></td></tr>
<tr>
<td><strong>Value</strong></td><td>Can be string, number, object, array, boolean, or null</td><td><code>"John"</code>, <code>30</code>, <code>true</code>, <code>null</code></td></tr>
<tr>
<td><strong>Comma</strong></td><td>Separates key-value pairs</td><td><code>{ "a":1, "b":2 }</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-3-example-json-structure">📘 <strong>3. Example JSON Structure</strong></h2>
<pre><code class="lang-java">{
  <span class="hljs-string">"id"</span>: <span class="hljs-number">101</span>,
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Shreenibas"</span>,
  <span class="hljs-string">"email"</span>: <span class="hljs-string">"shree@example.com"</span>,
  <span class="hljs-string">"isActive"</span>: <span class="hljs-keyword">true</span>,
  <span class="hljs-string">"skills"</span>: [<span class="hljs-string">"Java"</span>, <span class="hljs-string">"Selenium"</span>, <span class="hljs-string">"API Testing"</span>],
  <span class="hljs-string">"address"</span>: {
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"Bhubaneswar"</span>,
    <span class="hljs-string">"pincode"</span>: <span class="hljs-number">751024</span>
  }
}
</code></pre>
<hr />
<h2 id="heading-4-json-data-types">🧠 <strong>4. JSON Data Types</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Type</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td>String</td><td><code>"Hello"</code></td></tr>
<tr>
<td>Number</td><td><code>25</code>, <code>3.14</code></td></tr>
<tr>
<td>Boolean</td><td><code>true</code> / <code>false</code></td></tr>
<tr>
<td>Null</td><td><code>null</code></td></tr>
<tr>
<td>Object</td><td><code>{ "key": "value" }</code></td></tr>
<tr>
<td>Array</td><td><code>[1,2,3]</code> or <code>[{"id":1},{"id":2}]</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-5-json-in-java-parsing-and-serialization">🧰 <strong>5. JSON in Java (Parsing and Serialization)</strong></h2>
<h3 id="heading-using-orgjson">🔹 <strong>Using org.json</strong></h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.json.JSONObject;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">JsonExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        String jsonData = <span class="hljs-string">"{ \"name\": \"Shree\", \"age\": 30 }"</span>;

        JSONObject obj = <span class="hljs-keyword">new</span> JSONObject(jsonData);
        System.out.println(obj.getString(<span class="hljs-string">"name"</span>)); <span class="hljs-comment">// Shree</span>
        System.out.println(obj.getInt(<span class="hljs-string">"age"</span>));     <span class="hljs-comment">// 30</span>
    }
}
</code></pre>
<hr />
<h3 id="heading-using-jackson-faster-and-widely-used">🔹 <strong>Using Jackson (faster and widely used)</strong></h3>
<h4 id="heading-convert-json-java-object-deserialization">➤ Convert JSON → Java Object (Deserialization)</h4>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> com.fasterxml.jackson.databind.ObjectMapper;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Demo</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        String json = <span class="hljs-string">"{ \"name\":\"Shree\", \"age\":30 }"</span>;

        ObjectMapper mapper = <span class="hljs-keyword">new</span> ObjectMapper();
        Person p = mapper.readValue(json, Person.class);

        System.out.println(p.getName());
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;

    <span class="hljs-comment">// getters and setters</span>
}
</code></pre>
<h4 id="heading-convert-java-object-json-serialization">➤ Convert Java Object → JSON (Serialization)</h4>
<pre><code class="lang-java">Person p = <span class="hljs-keyword">new</span> Person();
p.setName(<span class="hljs-string">"Shree"</span>);
p.setAge(<span class="hljs-number">30</span>);

ObjectMapper mapper = <span class="hljs-keyword">new</span> ObjectMapper();
String jsonOutput = mapper.writeValueAsString(p);
System.out.println(jsonOutput);
</code></pre>
<p>Output:</p>
<pre><code class="lang-java">{<span class="hljs-string">"name"</span>:<span class="hljs-string">"Shree"</span>,<span class="hljs-string">"age"</span>:<span class="hljs-number">30</span>}
</code></pre>
<hr />
<h2 id="heading-6-json-in-rest-assured">🧪 <strong>6. JSON in Rest Assured</strong></h2>
<h3 id="heading-extract-value-from-api-response">✅ Extract value from API response</h3>
<pre><code class="lang-java">Response res = given().get(<span class="hljs-string">"https://api.example.com/users/1"</span>);

String name = res.jsonPath().getString(<span class="hljs-string">"name"</span>);
<span class="hljs-keyword">int</span> id = res.jsonPath().getInt(<span class="hljs-string">"id"</span>);
</code></pre>
<h3 id="heading-send-json-payload-in-post-request">✅ Send JSON payload in POST request</h3>
<pre><code class="lang-java">JSONObject request = <span class="hljs-keyword">new</span> JSONObject();
request.put(<span class="hljs-string">"name"</span>, <span class="hljs-string">"Shree"</span>);
request.put(<span class="hljs-string">"job"</span>, <span class="hljs-string">"Tester"</span>);

given()
  .header(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>)
  .body(request.toString())
.when()
  .post(<span class="hljs-string">"https://reqres.in/api/users"</span>)
.then()
  .statusCode(<span class="hljs-number">201</span>);
</code></pre>
<hr />
<h2 id="heading-7-json-path-for-reading-json">🔍 <strong>7. JSON Path (for reading JSON)</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Expression</td><td>Description</td><td>Example Output</td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="http://store.book"><code>store.book</code></a><code>[0].title</code></td><td>Get title of first book</td><td>“Java Basics”</td></tr>
<tr>
<td><a target="_blank" href="http://store.book"><code>store.book</code></a><code>[-1].price</code></td><td>Get last book’s price</td><td>30.5</td></tr>
<tr>
<td><a target="_blank" href="http://store.book"><code>store.book</code></a><code>.find { it.price &gt; 10 }</code></td><td>Find book where price &gt; 10</td><td>Object</td></tr>
<tr>
<td><a target="_blank" href="http://store.book"><code>store.book</code></a><code>.size()</code></td><td>Count books</td><td>3</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-8-json-schema-validation-in-rest-assured">🚀 <strong>8. JSON Schema Validation in Rest Assured</strong></h2>
<p>Used to validate API responses against predefined structure.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.<span class="hljs-keyword">module</span>.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;

given()
  .get(<span class="hljs-string">"/users/1"</span>)
.then()
  .assertThat()
  .body(matchesJsonSchemaInClasspath(<span class="hljs-string">"userSchema.json"</span>));
</code></pre>
<hr />
<h2 id="heading-9-common-json-errors">🧩 <strong>9. Common JSON Errors</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Error</td><td>Reason</td><td>Fix</td></tr>
</thead>
<tbody>
<tr>
<td>Missing quotes</td><td>Keys must be in quotes</td><td><code>"name": "John"</code></td></tr>
<tr>
<td>Trailing comma</td><td>Last pair shouldn’t end with comma</td><td>Remove comma</td></tr>
<tr>
<td>Invalid nesting</td><td>Braces/Brackets mismatch</td><td>Check <code>{}</code> and <code>[]</code> balance</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-10-practice-tasks">💡 <strong>10. Practice Tasks</strong></h2>
<ol>
<li><p>Create JSON for Employee → name, id, skills[], address{}</p>
</li>
<li><p>Parse JSON and extract nested values</p>
</li>
<li><p>Convert List of POJOs to JSON array using Jackson</p>
</li>
<li><p>Validate JSON response schema in RestAssured</p>
</li>
<li><p>Write test that compares expected and actual JSONs</p>
</li>
</ol>
<hr />
<p>Would you like me to create a <strong>practice-based JSON mini project</strong> (like validating API responses or reading test data from JSON in Selenium)?<br />It can be beginner → advanced in 3 levels.</p>
<h5 id="heading-you-said">You said:</h5>
<p>json path</p>
<h6 id="heading-chatgpt-said">ChatGPT said:</h6>
<p>Perfect 👍 — let’s now go deep into <strong>JSONPath</strong>, which is one of the most powerful and frequently asked topics for <strong>API automation (RestAssured)</strong> and <strong>JSON parsing</strong>.</p>
<hr />
<h1 id="heading-jsonpath-tutorial-complete-guide-for-testers">🧩 JSONPath Tutorial (Complete Guide for Testers)</h1>
<hr />
<h2 id="heading-what-is-jsonpath">💡 What is JSONPath?</h2>
<p><strong>JSONPath</strong> is a query language for <strong>navigating and extracting data from JSON documents</strong>, just like <strong>XPath</strong> for XML.<br />It helps you get specific values, arrays, or nested data easily.</p>
<p>Example JSON:</p>
<pre><code class="lang-java">{
  <span class="hljs-string">"store"</span>: {
    <span class="hljs-string">"book"</span>: [
      { <span class="hljs-string">"category"</span>: <span class="hljs-string">"fiction"</span>, <span class="hljs-string">"title"</span>: <span class="hljs-string">"The Alchemist"</span>, <span class="hljs-string">"price"</span>: <span class="hljs-number">12.99</span> },
      { <span class="hljs-string">"category"</span>: <span class="hljs-string">"programming"</span>, <span class="hljs-string">"title"</span>: <span class="hljs-string">"Java Basics"</span>, <span class="hljs-string">"price"</span>: <span class="hljs-number">25.50</span> },
      { <span class="hljs-string">"category"</span>: <span class="hljs-string">"fiction"</span>, <span class="hljs-string">"title"</span>: <span class="hljs-string">"Harry Potter"</span>, <span class="hljs-string">"price"</span>: <span class="hljs-number">30.00</span> }
    ],
    <span class="hljs-string">"bicycle"</span>: {
      <span class="hljs-string">"color"</span>: <span class="hljs-string">"red"</span>,
      <span class="hljs-string">"price"</span>: <span class="hljs-number">120.50</span>
    }
  }
}
</code></pre>
<hr />
<h2 id="heading-basic-jsonpath-syntax">⚙️ Basic JSONPath Syntax</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Symbol</td><td>Meaning</td><td>Example</td><td>Output</td></tr>
</thead>
<tbody>
<tr>
<td><code>$</code></td><td>Root element</td><td><code>$</code></td><td>whole JSON</td></tr>
<tr>
<td><code>.</code></td><td>Child operator</td><td><code>$.</code><a target="_blank" href="http://store.book"><code>store.book</code></a></td><td>all books</td></tr>
<tr>
<td><code>[]</code></td><td>Array index</td><td><code>$.</code><a target="_blank" href="http://store.book"><code>store.book</code></a><code>[0]</code></td><td>1st book</td></tr>
<tr>
<td><code>*</code></td><td>Wildcard (all elements)</td><td><code>$.</code><a target="_blank" href="http://store.book"><code>store.book</code></a><code>[*].title</code></td><td>all book titles</td></tr>
<tr>
<td><code>..</code></td><td>Recursive search</td><td><code>$..price</code></td><td>all prices</td></tr>
<tr>
<td><code>@</code></td><td>Current element</td><td><code>$.</code><a target="_blank" href="http://store.book"><code>store.book</code></a><code>[?(@.price &gt; 20)]</code></td><td>books with price &gt; 20</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-examples">🧠 Examples</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Expression</td><td>Description</td><td>Output</td></tr>
</thead>
<tbody>
<tr>
<td><code>$.</code><a target="_blank" href="http://store.book"><code>store.book</code></a><code>[0].title</code></td><td>Title of 1st book</td><td><code>"The Alchemist"</code></td></tr>
<tr>
<td><code>$.</code><a target="_blank" href="http://store.book"><code>store.book</code></a><code>[*].price</code></td><td>All book prices</td><td><code>[12.99, 25.50, 30.00]</code></td></tr>
<tr>
<td><code>$..price</code></td><td>All prices (book + bicycle)</td><td><code>[12.99, 25.50, 30.00, 120.50]</code></td></tr>
<tr>
<td><code>$.</code><a target="_blank" href="http://store.book"><code>store.book</code></a><code>[?(@.price &gt; 20)]</code></td><td>Books where price &gt; 20</td><td>2 books</td></tr>
<tr>
<td><code>$.</code><a target="_blank" href="http://store.book"><code>store.book</code></a><code>[?(@.category == 'fiction')]</code></td><td>Books in fiction category</td><td>2 books</td></tr>
<tr>
<td><code>$.</code><a target="_blank" href="http://store.book"><code>store.book</code></a><code>[-1:].title</code></td><td>Last book’s title</td><td><code>"Harry Potter"</code></td></tr>
<tr>
<td><code>$.</code><a target="_blank" href="http://store.book"><code>store.book</code></a><code>.length()</code></td><td>Number of books</td><td><code>3</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-jsonpath-in-restassured">🧪 JSONPath in <strong>RestAssured</strong></h2>
<h3 id="heading-example-1-extract-a-value">✅ Example 1: Extract a value</h3>
<pre><code class="lang-java">Response res = given()
    .when().get(<span class="hljs-string">"https://reqres.in/api/users/2"</span>);

String email = res.jsonPath().getString(<span class="hljs-string">"data.email"</span>);
System.out.println(email);
</code></pre>
<hr />
<h3 id="heading-example-2-extract-nested-values-from-json-array">✅ Example 2: Extract nested values from JSON array</h3>
<pre><code class="lang-java">Response res = given().get(<span class="hljs-string">"https://reqres.in/api/users?page=2"</span>);

List&lt;String&gt; emails = res.jsonPath().getList(<span class="hljs-string">"data.email"</span>);
System.out.println(emails);
</code></pre>
<hr />
<h3 id="heading-example-3-conditional-extraction">✅ Example 3: Conditional extraction</h3>
<pre><code class="lang-java">List&lt;String&gt; names = res.jsonPath()
    .getList(<span class="hljs-string">"data.findAll { it.id &gt; 10 }.first_name"</span>);
System.out.println(names);
</code></pre>
<p>👉 Here <code>findAll {</code> <a target="_blank" href="http://it.id"><code>it.id</code></a> <code>&gt; 10 }</code> acts like a filter, returning all objects where id &gt; 10.</p>
<hr />
<h2 id="heading-jsonpath-operators">🧮 JSONPath Operators</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td>Meaning</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>@</code></td><td>Current node</td><td><code>@.price</code></td></tr>
<tr>
<td><code>==</code>, <code>!=</code></td><td>Equal / Not equal</td><td><code>@.category == 'fiction'</code></td></tr>
<tr>
<td><code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, <code>&gt;=</code></td><td>Comparisons</td><td><code>@.price &gt; 20</code></td></tr>
<tr>
<td><code>&amp;&amp;</code>, `</td><td></td><td>`</td></tr>
<tr>
<td><code>?()</code></td><td>Filter expression</td><td><code>[?(@.price &lt; 30)]</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-jsonpath-vs-xpath-quick-comparison">🔍 JSONPath vs XPath (Quick Comparison)</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>JSONPath</td><td>XPath</td></tr>
</thead>
<tbody>
<tr>
<td>Data Format</td><td>JSON</td><td>XML</td></tr>
<tr>
<td>Root Symbol</td><td><code>$</code></td><td><code>/</code></td></tr>
<tr>
<td>Arrays</td><td><code>[]</code></td><td><code>[index]</code></td></tr>
<tr>
<td>Recursive Search</td><td><code>..</code></td><td><code>//</code></td></tr>
<tr>
<td>Filter</td><td><code>[?()]</code></td><td><code>[condition]</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-jsonpath-in-real-api-automation">💼 JSONPath in Real API Automation</h2>
<p>Example API Response:</p>
<pre><code class="lang-java">{
  <span class="hljs-string">"data"</span>: [
    { <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>, <span class="hljs-string">"role"</span>: <span class="hljs-string">"Tester"</span> },
    { <span class="hljs-string">"id"</span>: <span class="hljs-number">2</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"David"</span>, <span class="hljs-string">"role"</span>: <span class="hljs-string">"Developer"</span> }
  ]
}
</code></pre>
<h3 id="heading-get-all-names">✅ Get all names:</h3>
<pre><code class="lang-java">List&lt;String&gt; names = response.jsonPath().getList(<span class="hljs-string">"data.name"</span>);
</code></pre>
<h3 id="heading-get-name-of-user-where-id-2">✅ Get name of user where id = 2:</h3>
<pre><code class="lang-java">String name = response.jsonPath().getString(<span class="hljs-string">"data.find { it.id == 2 }.name"</span>);
</code></pre>
<hr />
<h2 id="heading-advanced-use-jsonpath-validation-in-restassured">🧪 Advanced Use — JSONPath Validation in RestAssured</h2>
<pre><code class="lang-java">given()
  .when().get(<span class="hljs-string">"/users"</span>)
  .then()
  .body(<span class="hljs-string">"data.find { it.id == 2 }.email"</span>, equalTo(<span class="hljs-string">"janet.weaver@reqres.in"</span>))
  .body(<span class="hljs-string">"data.size()"</span>, greaterThan(<span class="hljs-number">0</span>))
  .body(<span class="hljs-string">"data.email"</span>, hasItem(<span class="hljs-string">"janet.weaver@reqres.in"</span>));
</code></pre>
<hr />
<h2 id="heading-jsonpath-groovy-expressions-used-inside-restassured">⚡ JSONPath + Groovy Expressions (Used Inside RestAssured)</h2>
<p>RestAssured uses <strong>Groovy syntax</strong>, so you can apply filters like:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Expression</td><td>Meaning</td></tr>
</thead>
<tbody>
<tr>
<td><code>find {</code> <a target="_blank" href="http://it.id"><code>it.id</code></a> <code>== 1 }</code></td><td>First match</td></tr>
<tr>
<td><code>findAll { it.price &gt; 20 }</code></td><td>All matches</td></tr>
<tr>
<td><code>collect {</code> <a target="_blank" href="http://it.name"><code>it.name</code></a> <code>}</code></td><td>Collect all names</td></tr>
<tr>
<td><code>sum { it.price }</code></td><td>Sum of prices</td></tr>
<tr>
<td><code>max { it.price }</code></td><td>Maximum value</td></tr>
</tbody>
</table>
</div><p>Example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">float</span> maxPrice = response.jsonPath().getFloat(<span class="hljs-string">"store.book.max { it.price }.price"</span>);
System.out.println(<span class="hljs-string">"Max Price: "</span> + maxPrice);
</code></pre>
<hr />
<h2 id="heading-practice-tasks">🧩 Practice Tasks</h2>
<ol>
<li><p>Extract all “fiction” book titles from given JSON.</p>
</li>
<li><p>Find the highest-priced book using JSONPath.</p>
</li>
<li><p>Get the first user whose email contains “<a target="_blank" href="http://gmail.com">gmail.com</a>”.</p>
</li>
<li><p>Count total books having price &gt; 20.</p>
</li>
<li><p>Validate JSON response fields using JSONPath in RestAssured.</p>
</li>
</ol>
<hr />
<p>Would you like me to give a <strong>practice JSON + JSONPath exercise set</strong> (with real API responses and expected outputs)?<br />It’ll help you master filtering, array handling, and conditional queries used in interviews.</p>
<h5 id="heading-you-said-1">You said:</h5>
<p>now give same for xml</p>
<h6 id="heading-chatgpt-said-1">ChatGPT said:</h6>
<p>Excellent — let’s now cover <strong>XML and XPath</strong>, just like we did for JSON and JSONPath.<br />This is <strong>very important for API (SOAP) testing, data validation, and automation frameworks</strong>.</p>
<hr />
<h1 id="heading-xml-amp-xpath-tutorial-complete-guide-for-testers">🧩 <strong>XML &amp; XPath Tutorial (Complete Guide for Testers)</strong></h1>
<hr />
<h2 id="heading-what-is-xml">💡 <strong>What is XML?</strong></h2>
<p><strong>XML (eXtensible Markup Language)</strong> is a markup language used to store and transport structured data.<br />It’s similar to HTML, but it <strong>describes</strong> data rather than displaying it.</p>
<h3 id="heading-example">Example:</h3>
<pre><code class="lang-java">&lt;store&gt;
  &lt;book category=<span class="hljs-string">"fiction"</span>&gt;
    &lt;title&gt;The Alchemist&lt;/title&gt;
    &lt;author&gt;Paulo Coelho&lt;/author&gt;
    &lt;price&gt;<span class="hljs-number">12.99</span>&lt;/price&gt;
  &lt;/book&gt;
  &lt;book category=<span class="hljs-string">"programming"</span>&gt;
    &lt;title&gt;Java Basics&lt;/title&gt;
    &lt;author&gt;James Gosling&lt;/author&gt;
    &lt;price&gt;<span class="hljs-number">25.50</span>&lt;/price&gt;
  &lt;/book&gt;
&lt;/store&gt;
</code></pre>
<hr />
<h2 id="heading-xml-basics">⚙️ <strong>XML Basics</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Concept</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Tag</strong></td><td>Defines start and end of element</td><td><code>&lt;book&gt; ... &lt;/book&gt;</code></td></tr>
<tr>
<td><strong>Attribute</strong></td><td>Key-value inside start tag</td><td><code>&lt;book category="fiction"&gt;</code></td></tr>
<tr>
<td><strong>Element</strong></td><td>Data enclosed in tags</td><td><code>&lt;title&gt;Java&lt;/title&gt;</code></td></tr>
<tr>
<td><strong>Root Element</strong></td><td>The top-level parent</td><td><code>&lt;store&gt;</code></td></tr>
<tr>
<td><strong>Nested Elements</strong></td><td>Elements inside another</td><td><code>&lt;book&gt;&lt;title&gt;...&lt;/title&gt;&lt;/book&gt;</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-well-formed-xml-rules">🧠 <strong>Well-formed XML Rules</strong></h2>
<ol>
<li><p>Must have <strong>one root element</strong></p>
</li>
<li><p>Every start tag must have <strong>a closing tag</strong></p>
</li>
<li><p>Tags are <strong>case-sensitive</strong></p>
</li>
<li><p>Attributes must be <strong>quoted</strong></p>
</li>
<li><p>No overlapping tags (like <code>&lt;a&gt;&lt;b&gt;&lt;/a&gt;&lt;/b&gt;</code> ❌)</p>
</li>
</ol>
<hr />
<h2 id="heading-xml-vs-json">🧩 <strong>XML vs JSON</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>XML</td><td>JSON</td></tr>
</thead>
<tbody>
<tr>
<td>Format</td><td>Tag-based</td><td>Key-value</td></tr>
<tr>
<td>Readability</td><td>Verbose</td><td>Compact</td></tr>
<tr>
<td>Data types</td><td>Text only</td><td>Supports numbers, booleans</td></tr>
<tr>
<td>Comments</td><td>Allowed</td><td>Not allowed</td></tr>
<tr>
<td>Schema validation</td><td>XSD</td><td>JSON Schema</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-xpath-xml-query-language">🧪 <strong>XPath — XML Query Language</strong></h2>
<p><strong>XPath</strong> (XML Path Language) is used to <strong>navigate XML documents</strong> and <strong>extract specific elements</strong> or attributes.<br />Think of it as <strong>JSONPath for XML</strong>.</p>
<hr />
<h2 id="heading-xpath-syntax">⚙️ <strong>XPath Syntax</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Symbol</td><td>Meaning</td><td>Example</td><td>Output</td></tr>
</thead>
<tbody>
<tr>
<td><code>/</code></td><td>Select root or direct child</td><td><code>/store/book/title</code></td><td>All titles</td></tr>
<tr>
<td><code>//</code></td><td>Select from anywhere (recursive)</td><td><code>//price</code></td><td>All prices</td></tr>
<tr>
<td><code>@</code></td><td>Select attribute</td><td><code>//book/@category</code></td><td>All categories</td></tr>
<tr>
<td><code>[]</code></td><td>Filter (index or condition)</td><td><code>//book[1]/title</code></td><td>First title</td></tr>
<tr>
<td><code>text()</code></td><td>Get element text</td><td><code>//title/text()</code></td><td>Text value</td></tr>
<tr>
<td><code>*</code></td><td>Wildcard (any element)</td><td><code>//book/*</code></td><td>All child nodes</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-xpath-examples">🔍 <strong>XPath Examples</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>XPath Expression</td><td>Description</td><td>Output</td></tr>
</thead>
<tbody>
<tr>
<td><code>/store/book/title</code></td><td>All book titles under store</td><td>Titles</td></tr>
<tr>
<td><code>//book/title</code></td><td>Titles of all books</td><td>Titles</td></tr>
<tr>
<td><code>//book[1]/title</code></td><td>Title of first book</td><td>“The Alchemist”</td></tr>
<tr>
<td><code>//book[last()]/title</code></td><td>Title of last book</td><td>“Java Basics”</td></tr>
<tr>
<td><code>//book[@category='fiction']/title</code></td><td>Titles of fiction books</td><td>“The Alchemist”</td></tr>
<tr>
<td><code>//book[price&gt;20]/title</code></td><td>Books with price &gt; 20</td><td>“Java Basics”</td></tr>
<tr>
<td><code>count(//book)</code></td><td>Number of books</td><td><code>2</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-xpath-operators">🧩 <strong>XPath Operators</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>=</code></td><td>Equal</td><td><code>@category='fiction'</code></td></tr>
<tr>
<td><code>!=</code></td><td>Not equal</td><td><code>@category!='fiction'</code></td></tr>
<tr>
<td><code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code></td><td>Comparison</td><td><code>price&gt;20</code></td></tr>
<tr>
<td><code>and</code>, <code>or</code></td><td>Logical</td><td><code>@category='fiction' and price&gt;10</code></td></tr>
<tr>
<td><code>position()</code></td><td>Position in list</td><td><code>//book[position()=2]</code></td></tr>
<tr>
<td><code>last()</code></td><td>Last element</td><td><code>//book[last()]</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-xpath-in-restassured-xml-api-testing">🧪 <strong>XPath in RestAssured (XML API Testing)</strong></h2>
<h3 id="heading-example-1-verify-single-element">✅ Example 1: Verify single element</h3>
<pre><code class="lang-java">given()
  .when()
  .get(<span class="hljs-string">"https://example.com/books.xml"</span>)
  .then()
  .body(<span class="hljs-string">"store.book[0].title"</span>, equalTo(<span class="hljs-string">"The Alchemist"</span>));
</code></pre>
<hr />
<h3 id="heading-example-2-using-xmlpath">✅ Example 2: Using XMLPath</h3>
<pre><code class="lang-java">Response res = given()
    .when()
    .get(<span class="hljs-string">"https://example.com/books.xml"</span>);

String title = res.xmlPath().getString(<span class="hljs-string">"store.book[0].title"</span>);
System.out.println(title);
</code></pre>
<hr />
<h3 id="heading-example-3-extract-attribute">✅ Example 3: Extract attribute</h3>
<pre><code class="lang-java">String category = res.xmlPath().getString(<span class="hljs-string">"store.book[0].@category"</span>);
System.out.println(category); <span class="hljs-comment">// fiction</span>
</code></pre>
<hr />
<h2 id="heading-advanced-xpath-queries">🧩 <strong>Advanced XPath Queries</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Expression</td><td>Meaning</td></tr>
</thead>
<tbody>
<tr>
<td><code>//book[contains(title,'Java')]</code></td><td>Books with title containing “Java”</td></tr>
<tr>
<td><code>//book[starts-with(author,'P')]</code></td><td>Authors starting with “P”</td></tr>
<tr>
<td><code>//book[price&gt;10 and price&lt;30]</code></td><td>Books priced between 10–30</td></tr>
<tr>
<td>`//book/title</td><td>//bicycle/color`</td></tr>
<tr>
<td><code>//book[not(@category='fiction')]</code></td><td>Non-fiction books</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-xpath-functions">🧮 <strong>XPath Functions</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Function</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>count()</code></td><td>Count nodes</td><td><code>count(//book)</code></td></tr>
<tr>
<td><code>sum()</code></td><td>Sum of numeric nodes</td><td><code>sum(//price)</code></td></tr>
<tr>
<td><code>contains()</code></td><td>Substring match</td><td><code>contains(title,'Java')</code></td></tr>
<tr>
<td><code>starts-with()</code></td><td>Prefix match</td><td><code>starts-with(author,'P')</code></td></tr>
<tr>
<td><code>text()</code></td><td>Return text</td><td><code>//book/title/text()</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-xml-validation-in-restassured">🧰 <strong>XML Validation in RestAssured</strong></h2>
<h3 id="heading-validate-xml-schema-xsd">✅ Validate XML Schema (XSD)</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.<span class="hljs-keyword">module</span>.jsv.XmlSchemaValidator.matchesXsdInClasspath;

given()
  .when()
  .get(<span class="hljs-string">"/books.xml"</span>)
  .then()
  .body(matchesXsdInClasspath(<span class="hljs-string">"booksSchema.xsd"</span>));
</code></pre>
<hr />
<h2 id="heading-xml-parsing-in-java">🧩 <strong>XML Parsing in Java</strong></h2>
<h3 id="heading-using-dom-parser">➤ Using DOM Parser</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> javax.xml.parsers.*;
<span class="hljs-keyword">import</span> org.w3c.dom.*;

File file = <span class="hljs-keyword">new</span> File(<span class="hljs-string">"books.xml"</span>);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);

NodeList list = doc.getElementsByTagName(<span class="hljs-string">"book"</span>);
System.out.println(<span class="hljs-string">"Books count: "</span> + list.getLength());
</code></pre>
<hr />
<h3 id="heading-using-xpath-in-java">➤ Using XPath in Java</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> javax.xml.xpath.*;
<span class="hljs-keyword">import</span> org.w3c.dom.*;

XPathFactory xFactory = XPathFactory.newInstance();
XPath xpath = xFactory.newXPath();
String expr = <span class="hljs-string">"//book[@category='fiction']/title/text()"</span>;
String title = xpath.evaluate(expr, doc);
System.out.println(title);
</code></pre>
<hr />
<h2 id="heading-common-xml-interview-questions">🧩 <strong>Common XML Interview Questions</strong></h2>
<ol>
<li><p>What is XML and how is it different from HTML/JSON?</p>
</li>
<li><p>What is XPath and how is it used in RestAssured?</p>
</li>
<li><p>How to extract XML attributes using XPath?</p>
</li>
<li><p>How to validate XML Schema in automation?</p>
</li>
<li><p>Write XPath to select the last node or filter by value.</p>
</li>
<li><p>How to handle SOAP response in API automation?</p>
</li>
</ol>
<hr />
<h2 id="heading-practice-tasks-1">🧠 <strong>Practice Tasks</strong></h2>
<ol>
<li><p>Write XPath to get the 2nd <code>&lt;book&gt;</code> title.</p>
</li>
<li><p>Get the category attribute for all books.</p>
</li>
<li><p>Extract all book titles where price &gt; 20.</p>
</li>
<li><p>Count total <code>&lt;book&gt;</code> nodes.</p>
</li>
<li><p>Validate XML response against an XSD schema.</p>
</li>
</ol>
<hr />
<p>Would you like me to now create a <strong>practice-based XML + XPath exercise set</strong> (with sample XML responses and questions like extract, filter, and validate — just like a mini project for RestAssured)?</p>
<h5 id="heading-you-said-2">You said:</h5>
<p>give full diferences</p>
<h6 id="heading-chatgpt-said-2">ChatGPT said:</h6>
<p>Perfect — here’s a <strong>complete comparison of JSON vs XML</strong> with every key difference clearly explained from a <strong>tester’s and automation engineer’s</strong> perspective (especially for API testing using RestAssured / Postman).</p>
<hr />
<h1 id="heading-json-vs-xml-full-comparison-table">🧩 <strong>JSON vs XML — Full Comparison Table</strong></h1>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Category</strong></td><td><strong>JSON (JavaScript Object Notation)</strong></td><td><strong>XML (eXtensible Markup Language)</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Definition</strong></td><td>Lightweight data-interchange format</td><td>Markup language used to describe structured data</td></tr>
<tr>
<td><strong>Structure Type</strong></td><td>Key–Value pairs</td><td>Tag-based hierarchical structure</td></tr>
<tr>
<td><strong>Syntax Example</strong></td><td><code>{ "name": "Shree", "age": 30 }</code></td><td><code>&lt;person&gt;&lt;name&gt;Shree&lt;/name&gt;&lt;age&gt;30&lt;/age&gt;&lt;/person&gt;</code></td></tr>
<tr>
<td><strong>Root Element</strong></td><td>Optional</td><td>Mandatory — XML must have one root element</td></tr>
<tr>
<td><strong>Readability</strong></td><td>Compact and easier to read</td><td>Verbose and harder to read due to nested tags</td></tr>
<tr>
<td><strong>Data Representation</strong></td><td>Uses objects <code>{}</code> and arrays <code>[]</code></td><td>Uses nested elements <code>&lt;tag&gt;</code> and attributes</td></tr>
<tr>
<td><strong>Data Types Supported</strong></td><td>String, Number, Boolean, Null, Array, Object</td><td>Text only (all values are strings)</td></tr>
<tr>
<td><strong>Schema Validation</strong></td><td>JSON Schema (<code>.json</code> file)</td><td>XML Schema (XSD file)</td></tr>
<tr>
<td><strong>Attribute Support</strong></td><td>Doesn’t support attributes; everything is key–value</td><td>Supports attributes inside tags (<code>&lt;book category="fiction"&gt;</code>)</td></tr>
<tr>
<td><strong>Comments</strong></td><td>Not allowed in standard JSON</td><td>Allowed using <code>&lt;!-- comment --&gt;</code></td></tr>
<tr>
<td><strong>Namespaces</strong></td><td>Not supported</td><td>Fully supports namespaces</td></tr>
<tr>
<td><strong>Order Sensitivity</strong></td><td>Order usually doesn’t matter</td><td>Order can be significant in XML</td></tr>
<tr>
<td><strong>Metadata Representation</strong></td><td>No built-in mechanism</td><td>Attributes provide metadata</td></tr>
<tr>
<td><strong>Data Interchange</strong></td><td>Commonly used for REST APIs</td><td>Commonly used for SOAP APIs</td></tr>
<tr>
<td><strong>Parsing Speed</strong></td><td>Faster (lightweight)</td><td>Slower (more complex structure)</td></tr>
<tr>
<td><strong>File Size</strong></td><td>Smaller (compact format)</td><td>Larger due to tag redundancy</td></tr>
<tr>
<td><strong>Data Types Flexibility</strong></td><td>Supports native data types directly</td><td>All data is stored as text and needs conversion</td></tr>
<tr>
<td><strong>Support in Web APIs</strong></td><td>Used in almost all RESTful services</td><td>Used mainly in older SOAP services</td></tr>
<tr>
<td><strong>Parsing Tools in Java</strong></td><td>Jackson, Gson, org.json, JSON.simple</td><td>DOM, SAX, StAX, JAXB parsers</td></tr>
<tr>
<td><strong>Validation Tools</strong></td><td><code>jsonschema</code> validator</td><td>XSD validator</td></tr>
<tr>
<td><strong>Data Access Path</strong></td><td>JSONPath (<code>$..price</code>)</td><td>XPath (<code>//price</code>)</td></tr>
<tr>
<td><strong>Mapping with Java Object</strong></td><td>Easy with Jackson/Gson (POJO mapping)</td><td>More complex with JAXB (XML Binding)</td></tr>
<tr>
<td><strong>Empty Values Representation</strong></td><td><code>null</code></td><td><code>&lt;tag&gt;&lt;/tag&gt;</code> or <code>&lt;tag/&gt;</code></td></tr>
<tr>
<td><strong>APIs Commonly Using It</strong></td><td>REST APIs</td><td>SOAP APIs</td></tr>
<tr>
<td><strong>Interoperability</strong></td><td>Modern and widely accepted</td><td>Legacy systems still use XML</td></tr>
<tr>
<td><strong>Human Friendliness</strong></td><td>Easier to read and modify</td><td>More formal and structured</td></tr>
<tr>
<td><strong>Error Handling</strong></td><td>Simple (less strict syntax)</td><td>Strict (must be well-formed)</td></tr>
<tr>
<td><strong>Extensibility</strong></td><td>Limited</td><td>Highly extensible using tags</td></tr>
<tr>
<td><strong>Best For</strong></td><td>RESTful web services, configuration files</td><td>Document storage, SOAP, configuration, legacy systems</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-quick-summary-for-automation-testers">💡 <strong>Quick Summary for Automation Testers</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Purpose</td><td>Prefer JSON</td><td>Prefer XML</td></tr>
</thead>
<tbody>
<tr>
<td>REST API Testing</td><td>✅ Yes</td><td>❌ No</td></tr>
<tr>
<td>SOAP API Testing</td><td>❌ No</td><td>✅ Yes</td></tr>
<tr>
<td>Lightweight data transfer</td><td>✅ Yes</td><td>❌ No</td></tr>
<tr>
<td>Complex hierarchical document (with attributes)</td><td>❌ No</td><td>✅ Yes</td></tr>
<tr>
<td>Easy serialization/deserialization</td><td>✅ Jackson / Gson</td><td>⚙️ JAXB / DOM</td></tr>
<tr>
<td>Schema validation in automation</td><td>✅ JSON Schema</td><td>✅ XSD Schema</td></tr>
<tr>
<td>Fast parsing in RestAssured</td><td>✅ jsonPath()</td><td>✅ xmlPath() (but slower)</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-code-example-comparison-in-restassured">⚙️ <strong>Code Example (Comparison in RestAssured)</strong></h2>
<h3 id="heading-json-example">JSON Example</h3>
<pre><code class="lang-java">Response res = given()
    .contentType(<span class="hljs-string">"application/json"</span>)
    .body(<span class="hljs-string">"{\"name\":\"Shree\", \"age\":30}"</span>)
.when()
    .post(<span class="hljs-string">"/createUser"</span>);

String name = res.jsonPath().getString(<span class="hljs-string">"name"</span>);
</code></pre>
<h3 id="heading-xml-example">XML Example</h3>
<pre><code class="lang-java">Response res = given()
    .contentType(<span class="hljs-string">"application/xml"</span>)
    .body(<span class="hljs-string">"&lt;user&gt;&lt;name&gt;Shree&lt;/name&gt;&lt;age&gt;30&lt;/age&gt;&lt;/user&gt;"</span>)
.when()
    .post(<span class="hljs-string">"/createUser"</span>);

String name = res.xmlPath().getString(<span class="hljs-string">"user.name"</span>);
</code></pre>
<hr />
<h2 id="heading-interview-focused-key-points">🧩 <strong>Interview-Focused Key Points</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Question</td><td>JSON Answer</td><td>XML Answer</td></tr>
</thead>
<tbody>
<tr>
<td>What is it used for?</td><td>Data exchange in REST APIs</td><td>Data exchange in SOAP APIs</td></tr>
<tr>
<td>Supports comments?</td><td>❌ No</td><td>✅ Yes</td></tr>
<tr>
<td>Supports attributes?</td><td>❌ No</td><td>✅ Yes</td></tr>
<tr>
<td>Easy to map with Java objects?</td><td>✅ Yes</td><td>⚙️ Slightly complex</td></tr>
<tr>
<td>Supports array?</td><td>✅ Yes (<code>[]</code>)</td><td>⚙️ Must use repeated tags</td></tr>
<tr>
<td>Can validate structure?</td><td>✅ JSON Schema</td><td>✅ XSD</td></tr>
<tr>
<td>Preferred in automation frameworks?</td><td>✅ Yes</td><td>⚙️ Only for SOAP or legacy</td></tr>
<tr>
<td>Data navigation method?</td><td>JSONPath</td><td>XPath</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-conclusion">⚡ <strong>Conclusion</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Area</td><td>Winner</td></tr>
</thead>
<tbody>
<tr>
<td>Simplicity</td><td>JSON ✅</td></tr>
<tr>
<td>Readability</td><td>JSON ✅</td></tr>
<tr>
<td>Flexibility</td><td>XML ✅</td></tr>
<tr>
<td>Speed</td><td>JSON ✅</td></tr>
<tr>
<td>Hierarchical complexity</td><td>XML ✅</td></tr>
<tr>
<td>Modern API usage</td><td>JSON ✅</td></tr>
<tr>
<td>Legacy system integration</td><td>XML ✅</td></tr>
</tbody>
</table>
</div>]]></content:encoded></item><item><title><![CDATA[05 Complex Post Request]]></title><description><![CDATA[This is one of the most asked advanced topics in Rest Assured interviews — especially for Automation Engineers using Java.

🧩 Scenario: Complex POST Request
You need to send this nested JSON body to create an order:
{
  "orderId": 101,
  "customer":...]]></description><link>https://shreenibas-api-restassured.hashnode.dev/05-complex-post-request</link><guid isPermaLink="true">https://shreenibas-api-restassured.hashnode.dev/05-complex-post-request</guid><category><![CDATA[@shreenibas]]></category><dc:creator><![CDATA[Shreenibas Samal]]></dc:creator><pubDate>Wed, 15 Oct 2025 00:24:34 GMT</pubDate><content:encoded><![CDATA[<p>This is one of the <strong>most asked advanced topics</strong> in Rest Assured interviews — especially for <strong>Automation Engineers using Java</strong>.</p>
<hr />
<h2 id="heading-scenario-complex-post-request">🧩 <strong>Scenario: Complex POST Request</strong></h2>
<p>You need to send this <strong>nested JSON body</strong> to create an order:</p>
<pre><code class="lang-java">{
  <span class="hljs-string">"orderId"</span>: <span class="hljs-number">101</span>,
  <span class="hljs-string">"customer"</span>: {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"Nini"</span>,
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"nini@test.com"</span>,
    <span class="hljs-string">"address"</span>: {
      <span class="hljs-string">"street"</span>: <span class="hljs-string">"MG Road"</span>,
      <span class="hljs-string">"city"</span>: <span class="hljs-string">"Bangalore"</span>,
      <span class="hljs-string">"pincode"</span>: <span class="hljs-string">"560001"</span>
    }
  },
  <span class="hljs-string">"items"</span>: [
    { <span class="hljs-string">"itemName"</span>: <span class="hljs-string">"Laptop"</span>, <span class="hljs-string">"quantity"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"price"</span>: <span class="hljs-number">75000</span> },
    { <span class="hljs-string">"itemName"</span>: <span class="hljs-string">"Mouse"</span>, <span class="hljs-string">"quantity"</span>: <span class="hljs-number">2</span>, <span class="hljs-string">"price"</span>: <span class="hljs-number">500</span> }
  ],
  <span class="hljs-string">"payment"</span>: {
    <span class="hljs-string">"mode"</span>: <span class="hljs-string">"CreditCard"</span>,
    <span class="hljs-string">"transactionId"</span>: <span class="hljs-string">"TXN12345"</span>
  }
}
</code></pre>
<hr />
<h2 id="heading-step-1-create-pojo-classes">🟢 <strong>Step 1: Create POJO Classes</strong></h2>
<h3 id="heading-addressjavahttpaddressjava"><a target="_blank" href="http://Address.java"><code>Address.java</code></a></h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Address</span> </span>{
    <span class="hljs-keyword">private</span> String street;
    <span class="hljs-keyword">private</span> String city;
    <span class="hljs-keyword">private</span> String pincode;

    <span class="hljs-comment">// Getters and Setters</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getStreet</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> street; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setStreet</span><span class="hljs-params">(String street)</span> </span>{ <span class="hljs-keyword">this</span>.street = street; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getCity</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> city; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setCity</span><span class="hljs-params">(String city)</span> </span>{ <span class="hljs-keyword">this</span>.city = city; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPincode</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> pincode; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPincode</span><span class="hljs-params">(String pincode)</span> </span>{ <span class="hljs-keyword">this</span>.pincode = pincode; }
}
</code></pre>
<h3 id="heading-customerjavahttpcustomerjava"><a target="_blank" href="http://Customer.java"><code>Customer.java</code></a></h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Customer</span> </span>{
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> String email;
    <span class="hljs-keyword">private</span> Address address;

    <span class="hljs-comment">// Getters and Setters</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> name; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{ <span class="hljs-keyword">this</span>.name = name; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getEmail</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> email; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setEmail</span><span class="hljs-params">(String email)</span> </span>{ <span class="hljs-keyword">this</span>.email = email; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Address <span class="hljs-title">getAddress</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> address; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAddress</span><span class="hljs-params">(Address address)</span> </span>{ <span class="hljs-keyword">this</span>.address = address; }
}
</code></pre>
<h3 id="heading-itemjavahttpitemjava"><a target="_blank" href="http://Item.java"><code>Item.java</code></a></h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Item</span> </span>{
    <span class="hljs-keyword">private</span> String itemName;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> quantity;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">double</span> price;

    <span class="hljs-comment">// Getters and Setters</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getItemName</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> itemName; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setItemName</span><span class="hljs-params">(String itemName)</span> </span>{ <span class="hljs-keyword">this</span>.itemName = itemName; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getQuantity</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> quantity; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setQuantity</span><span class="hljs-params">(<span class="hljs-keyword">int</span> quantity)</span> </span>{ <span class="hljs-keyword">this</span>.quantity = quantity; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">getPrice</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> price; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPrice</span><span class="hljs-params">(<span class="hljs-keyword">double</span> price)</span> </span>{ <span class="hljs-keyword">this</span>.price = price; }
}
</code></pre>
<h3 id="heading-paymentjavahttppaymentjava"><a target="_blank" href="http://Payment.java"><code>Payment.java</code></a></h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Payment</span> </span>{
    <span class="hljs-keyword">private</span> String mode;
    <span class="hljs-keyword">private</span> String transactionId;

    <span class="hljs-comment">// Getters and Setters</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getMode</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> mode; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setMode</span><span class="hljs-params">(String mode)</span> </span>{ <span class="hljs-keyword">this</span>.mode = mode; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getTransactionId</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> transactionId; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setTransactionId</span><span class="hljs-params">(String transactionId)</span> </span>{ <span class="hljs-keyword">this</span>.transactionId = transactionId; }
}
</code></pre>
<h3 id="heading-orderjavahttporderjava"><a target="_blank" href="http://Order.java"><code>Order.java</code></a></h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Order</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> orderId;
    <span class="hljs-keyword">private</span> Customer customer;
    <span class="hljs-keyword">private</span> List&lt;Item&gt; items;
    <span class="hljs-keyword">private</span> Payment payment;

    <span class="hljs-comment">// Getters and Setters</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getOrderId</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> orderId; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setOrderId</span><span class="hljs-params">(<span class="hljs-keyword">int</span> orderId)</span> </span>{ <span class="hljs-keyword">this</span>.orderId = orderId; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Customer <span class="hljs-title">getCustomer</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> customer; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setCustomer</span><span class="hljs-params">(Customer customer)</span> </span>{ <span class="hljs-keyword">this</span>.customer = customer; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;Item&gt; <span class="hljs-title">getItems</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> items; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setItems</span><span class="hljs-params">(List&lt;Item&gt; items)</span> </span>{ <span class="hljs-keyword">this</span>.items = items; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Payment <span class="hljs-title">getPayment</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> payment; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPayment</span><span class="hljs-params">(Payment payment)</span> </span>{ <span class="hljs-keyword">this</span>.payment = payment; }
}
</code></pre>
<hr />
<h2 id="heading-step-2-build-request-body-in-java-serialization">🟢 <strong>Step 2: Build Request Body in Java (Serialization)</strong></h2>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> io.restassured.RestAssured;
<span class="hljs-keyword">import</span> io.restassured.http.ContentType;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> java.util.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ComplexPostExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{

        RestAssured.baseURI = <span class="hljs-string">"https://api.testing.com"</span>; <span class="hljs-comment">// Replace with your API URL</span>

        <span class="hljs-comment">// Create Address</span>
        Address address = <span class="hljs-keyword">new</span> Address();
        address.setStreet(<span class="hljs-string">"MG Road"</span>);
        address.setCity(<span class="hljs-string">"Bangalore"</span>);
        address.setPincode(<span class="hljs-string">"560001"</span>);

        <span class="hljs-comment">// Create Customer</span>
        Customer customer = <span class="hljs-keyword">new</span> Customer();
        customer.setName(<span class="hljs-string">"Nini"</span>);
        customer.setEmail(<span class="hljs-string">"nini@test.com"</span>);
        customer.setAddress(address);

        <span class="hljs-comment">// Create Items</span>
        Item item1 = <span class="hljs-keyword">new</span> Item();
        item1.setItemName(<span class="hljs-string">"Laptop"</span>);
        item1.setQuantity(<span class="hljs-number">1</span>);
        item1.setPrice(<span class="hljs-number">75000</span>);

        Item item2 = <span class="hljs-keyword">new</span> Item();
        item2.setItemName(<span class="hljs-string">"Mouse"</span>);
        item2.setQuantity(<span class="hljs-number">2</span>);
        item2.setPrice(<span class="hljs-number">500</span>);

        List&lt;Item&gt; itemList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
        itemList.add(item1);
        itemList.add(item2);

        <span class="hljs-comment">// Create Payment</span>
        Payment payment = <span class="hljs-keyword">new</span> Payment();
        payment.setMode(<span class="hljs-string">"CreditCard"</span>);
        payment.setTransactionId(<span class="hljs-string">"TXN12345"</span>);

        <span class="hljs-comment">// Create Order</span>
        Order order = <span class="hljs-keyword">new</span> Order();
        order.setOrderId(<span class="hljs-number">101</span>);
        order.setCustomer(customer);
        order.setItems(itemList);
        order.setPayment(payment);

        <span class="hljs-comment">// Send POST request</span>
        given()
            .contentType(ContentType.JSON)
            .body(order)
        .when()
            .post(<span class="hljs-string">"/orders"</span>)
        .then()
            .statusCode(<span class="hljs-number">201</span>)
            .log().all();
    }
}
</code></pre>
<p>✅ <strong>Rest Assured automatically converts (serializes)</strong> the nested <code>Order</code> object into a complex JSON request body.</p>
<hr />
<h2 id="heading-step-3-validate-response-deserialization">🟢 <strong>Step 3: Validate Response (Deserialization)</strong></h2>
<p>Let’s say the API returns the same order details as response.</p>
<pre><code class="lang-java">Order orderResponse =
    given()
        .contentType(ContentType.JSON)
        .body(order)
    .when()
        .post(<span class="hljs-string">"/orders"</span>)
    .then()
        .statusCode(<span class="hljs-number">201</span>)
        .extract()
        .as(Order.class);   // ✅ JSON → <span class="hljs-function">Java <span class="hljs-title">object</span> <span class="hljs-params">(Deserialization)</span>

System.out.<span class="hljs-title">println</span><span class="hljs-params">(<span class="hljs-string">"Customer name: "</span> + orderResponse.getCustomer()</span>.<span class="hljs-title">getName</span><span class="hljs-params">()</span>)</span>;
System.out.println(<span class="hljs-string">"First item: "</span> + orderResponse.getItems().get(<span class="hljs-number">0</span>).getItemName());
</code></pre>
<hr />
<h2 id="heading-alternative-without-pojos-using-hashmap-amp-list">🟣 <strong>Alternative: Without POJOs (Using HashMap &amp; List)</strong></h2>
<p>If you don’t want to create multiple POJO classes, you can use Maps &amp; Lists:</p>
<pre><code class="lang-java">Map&lt;String, Object&gt; address = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();
address.put(<span class="hljs-string">"street"</span>, <span class="hljs-string">"MG Road"</span>);
address.put(<span class="hljs-string">"city"</span>, <span class="hljs-string">"Bangalore"</span>);
address.put(<span class="hljs-string">"pincode"</span>, <span class="hljs-string">"560001"</span>);

Map&lt;String, Object&gt; customer = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();
customer.put(<span class="hljs-string">"name"</span>, <span class="hljs-string">"Nini"</span>);
customer.put(<span class="hljs-string">"email"</span>, <span class="hljs-string">"nini@test.com"</span>);
customer.put(<span class="hljs-string">"address"</span>, address);

Map&lt;String, Object&gt; payment = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();
payment.put(<span class="hljs-string">"mode"</span>, <span class="hljs-string">"CreditCard"</span>);
payment.put(<span class="hljs-string">"transactionId"</span>, <span class="hljs-string">"TXN12345"</span>);

List&lt;Map&lt;String, Object&gt;&gt; items = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
Map&lt;String, Object&gt; item1 = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();
item1.put(<span class="hljs-string">"itemName"</span>, <span class="hljs-string">"Laptop"</span>);
item1.put(<span class="hljs-string">"quantity"</span>, <span class="hljs-number">1</span>);
item1.put(<span class="hljs-string">"price"</span>, <span class="hljs-number">75000</span>);
items.add(item1);

Map&lt;String, Object&gt; item2 = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();
item2.put(<span class="hljs-string">"itemName"</span>, <span class="hljs-string">"Mouse"</span>);
item2.put(<span class="hljs-string">"quantity"</span>, <span class="hljs-number">2</span>);
item2.put(<span class="hljs-string">"price"</span>, <span class="hljs-number">500</span>);
items.add(item2);

Map&lt;String, Object&gt; order = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();
order.put(<span class="hljs-string">"orderId"</span>, <span class="hljs-number">101</span>);
order.put(<span class="hljs-string">"customer"</span>, customer);
order.put(<span class="hljs-string">"items"</span>, items);
order.put(<span class="hljs-string">"payment"</span>, payment);

given()
    .contentType(ContentType.JSON)
    .body(order)
.when()
    .post(<span class="hljs-string">"/orders"</span>)
.then()
    .statusCode(<span class="hljs-number">201</span>)
    .log().body();
</code></pre>
<p>✅ This approach is faster for small test cases,<br />but POJO-based is <strong>recommended for frameworks</strong> (cleaner, reusable, and type-safe).</p>
<hr />
<h2 id="heading-interview-ready-summary-answer">🧠 <strong>Interview-Ready Summary Answer</strong></h2>
<blockquote>
<p>“A <strong>complex POST request</strong> in Rest Assured involves sending a nested JSON structure that includes objects, arrays, and lists.<br />We can achieve this by using <strong>POJO classes</strong> with proper relationships or by using <strong>HashMaps and Lists</strong>.<br />Rest Assured automatically performs <strong>serialization (object → JSON)</strong> and <strong>deserialization (JSON → object)</strong> using Jackson or Gson.<br />This approach makes test automation more scalable and maintainable for large enterprise APIs.”</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[04 Serialization and Deserialization in Java]]></title><description><![CDATA[🧩 Serialization and Deserialization in Java
🔹 Definition

Serialization → Converting a Java object into a data format (like JSON, XML, or byte stream) for transmission or storage.

Deserialization → Converting that data format back into a Java obje...]]></description><link>https://shreenibas-api-restassured.hashnode.dev/04-serialization-and-deserialization-in-java</link><guid isPermaLink="true">https://shreenibas-api-restassured.hashnode.dev/04-serialization-and-deserialization-in-java</guid><category><![CDATA[@shreenibas]]></category><dc:creator><![CDATA[Shreenibas Samal]]></dc:creator><pubDate>Wed, 15 Oct 2025 00:23:10 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-serialization-and-deserialization-in-java">🧩 <strong>Serialization and Deserialization in Java</strong></h2>
<h3 id="heading-definition">🔹 <strong>Definition</strong></h3>
<ul>
<li><p><strong>Serialization</strong> → Converting a <strong>Java object into a data format</strong> (like JSON, XML, or byte stream) for transmission or storage.</p>
</li>
<li><p><strong>Deserialization</strong> → Converting that <strong>data format back into a Java object</strong>.</p>
</li>
</ul>
<p>These are used widely in <strong>API testing (Rest Assured)</strong>, <strong>file storage</strong>, <strong>network communication</strong>, and <strong>Java object persistence</strong>.</p>
<hr />
<h2 id="heading-why-its-important-in-api-automation">🔹 <strong>Why It’s Important in API Automation</strong></h2>
<ul>
<li><p>To <strong>send</strong> Java objects as <strong>JSON/XML</strong> in the API request (Serialization).</p>
</li>
<li><p>To <strong>read</strong> API responses (JSON/XML) and map them back to <strong>Java POJOs</strong> for validation (Deserialization).</p>
</li>
<li><p>Makes tests <strong>type-safe</strong>, <strong>clean</strong>, and <strong>maintainable</strong>.</p>
</li>
</ul>
<hr />
<h2 id="heading-commonly-used-libraries-in-java">🔹 <strong>Commonly Used Libraries in Java</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Library</td><td>Description</td><td>Common Use</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Jackson (com.fasterxml.jackson)</strong></td><td>Most popular, default in Rest Assured</td><td>Converts between Java objects and JSON</td></tr>
<tr>
<td><strong>Gson (</strong><a target="_blank" href="http://com.google"><strong>com.google</strong></a><strong>.gson)</strong></td><td>Lightweight, easy to use</td><td>Used in Android and simple JSON APIs</td></tr>
<tr>
<td><strong>Json-B / Eclipse Yasson</strong></td><td>Jakarta EE (Java EE 8+) JSON binding</td><td>For enterprise Java apps</td></tr>
<tr>
<td><strong>org.json</strong></td><td>Simple JSON parser</td><td>Manual parsing (less common in automation)</td></tr>
<tr>
<td><strong>Jackson Databind</strong></td><td>Core of Jackson library</td><td>Handles both serialization and deserialization</td></tr>
</tbody>
</table>
</div><p>✅ <strong>Rest Assured uses Jackson by default</strong> if it’s on the classpath.</p>
<hr />
<h2 id="heading-universal-example-works-with-rest-assured-or-plain-java">🔹 <strong>Universal Example (Works with Rest Assured or Plain Java)</strong></h2>
<h3 id="heading-step-1-create-a-pojo-class">Step 1: Create a POJO class</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;
    <span class="hljs-keyword">private</span> String email;

    <span class="hljs-comment">// Getters and Setters</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> name; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{ <span class="hljs-keyword">this</span>.name = name; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> age; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age)</span> </span>{ <span class="hljs-keyword">this</span>.age = age; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getEmail</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> email; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setEmail</span><span class="hljs-params">(String email)</span> </span>{ <span class="hljs-keyword">this</span>.email = email; }
}
</code></pre>
<hr />
<h3 id="heading-step-2-serialization-object-json-using-jackson">Step 2: <strong>Serialization (Object → JSON)</strong> using Jackson</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> com.fasterxml.jackson.databind.ObjectMapper;

User user = <span class="hljs-keyword">new</span> User();
user.setName(<span class="hljs-string">"Nini"</span>);
user.setAge(<span class="hljs-number">25</span>);
user.setEmail(<span class="hljs-string">"nini@test.com"</span>);

ObjectMapper mapper = <span class="hljs-keyword">new</span> ObjectMapper();
String json = mapper.writeValueAsString(user);   <span class="hljs-comment">// ✅ Java → JSON</span>
System.out.println(json);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-java">{<span class="hljs-string">"name"</span>:<span class="hljs-string">"Nini"</span>,<span class="hljs-string">"age"</span>:<span class="hljs-number">25</span>,<span class="hljs-string">"email"</span>:<span class="hljs-string">"nini@test.com"</span>}
</code></pre>
<hr />
<h3 id="heading-step-3-deserialization-json-object">Step 3: <strong>Deserialization (JSON → Object)</strong></h3>
<pre><code class="lang-java">String jsonString = <span class="hljs-string">"{\"name\":\"Nini\",\"age\":25,\"email\":\"nini@test.com\"}"</span>;

User userObj = mapper.readValue(jsonString, User.class);  <span class="hljs-comment">// ✅ JSON → Java</span>
System.out.println(userObj.getEmail());
</code></pre>
<hr />
<h3 id="heading-step-4-using-in-rest-assured">Step 4: <strong>Using in Rest Assured</strong></h3>
<p><strong>Serialization (sending Java object as body):</strong></p>
<pre><code class="lang-java">given()
    .contentType(<span class="hljs-string">"application/json"</span>)
    .body(user)    <span class="hljs-comment">// Rest Assured automatically serializes using Jackson</span>
.when()
    .post(<span class="hljs-string">"/createUser"</span>)
.then()
    .statusCode(<span class="hljs-number">201</span>);
</code></pre>
<p><strong>Deserialization (converting response to POJO):</strong></p>
<pre><code class="lang-java">User userResponse = 
    given()
        .get(<span class="hljs-string">"/getUser/101"</span>)
    .then()
        .extract()
        .as(User.class);   <span class="hljs-comment">// Rest Assured uses Jackson to deserialize</span>
</code></pre>
<hr />
<h2 id="heading-advanced-notes-for-interviews">🔹 <strong>Advanced Notes for Interviews</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Concept</td><td>Explanation</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Default Mapper</strong></td><td>Rest Assured uses <strong>Jackson</strong> automatically if present in Maven dependencies.</td></tr>
<tr>
<td><strong>Switching Library</strong></td><td>You can switch to Gson: <code>RestAssured.config = RestAssured.config().objectMapperConfig(objectMapperConfig().defaultObjectMapperType(ObjectMapperType.GSON));</code></td></tr>
<tr>
<td><strong>Annotations</strong></td><td>Use <code>@JsonProperty</code>, <code>@JsonIgnore</code>, <code>@JsonInclude</code> to control JSON mapping.</td></tr>
<tr>
<td><strong>Custom Mapper</strong></td><td>You can create your own <code>ObjectMapper</code> for date formats or naming strategies.</td></tr>
<tr>
<td><strong>Serialization Exception</strong></td><td>Occurs if object contains unknown or unsupported types (e.g., circular references).</td></tr>
<tr>
<td><strong>Deserialization Exception</strong></td><td>Occurs if JSON fields do not match Java fields or are missing.</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-common-interview-questions-and-universal-answers">🔹 <strong>Common Interview Questions and Universal Answers</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Question</td><td>Universal Answer</td></tr>
</thead>
<tbody>
<tr>
<td><strong>1. What is Serialization?</strong></td><td>Converting a Java object into JSON/XML or byte stream format.</td></tr>
<tr>
<td><strong>2. What is Deserialization?</strong></td><td>Converting JSON/XML back into a Java object.</td></tr>
<tr>
<td><strong>3. Why do we use it in Rest Assured?</strong></td><td>To send Java POJOs as request bodies and to map responses back into objects for easy validation.</td></tr>
<tr>
<td><strong>4. Which library handles it by default?</strong></td><td>Jackson (in Rest Assured).</td></tr>
<tr>
<td><strong>5. Can you use other libraries?</strong></td><td>Yes, like Gson, Json-B, or org.json.</td></tr>
<tr>
<td><strong>6. What annotations are used for JSON mapping?</strong></td><td><code>@JsonProperty</code>, <code>@JsonIgnore</code>, <code>@JsonInclude</code>, <code>@JsonFormat</code>.</td></tr>
<tr>
<td><strong>7. How to handle mismatched field names?</strong></td><td>Use <code>@JsonProperty("actual_json_field")</code>.</td></tr>
<tr>
<td><strong>8. What is ObjectMapper?</strong></td><td>A class in Jackson used for manual serialization/deserialization.</td></tr>
<tr>
<td><strong>9. What happens if a field is missing in JSON?</strong></td><td>Jackson ignores it by default unless configured otherwise.</td></tr>
<tr>
<td><strong>10. Can we serialize nested objects or lists?</strong></td><td>Yes, Jackson handles nested and collection types automatically.</td></tr>
</tbody>
</table>
</div><hr />
<p>✅ <strong>In short (Universal 2-line Interview Answer):</strong></p>
<blockquote>
<p><em>“Serialization is converting a Java object into JSON or XML so it can be sent to an API, and Deserialization is converting JSON or XML back into a Java object. In Rest Assured, this happens automatically using Jackson or Gson libraries, which helps in sending clean requests and validating structured responses.”</em></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[jjdjjvjbvjs]]></title><description><![CDATA[fbfvfdgfdgg
fgdfgfdgdfgnfdvdg
dfgfdgdf
g
dfgdfg
dfg
gdfgdg
dg
dgd
g
g
dgdg
d
dgdgd
g]]></description><link>https://shreenibas-api-restassured.hashnode.dev/jjdjjvjbvjs</link><guid isPermaLink="true">https://shreenibas-api-restassured.hashnode.dev/jjdjjvjbvjs</guid><category><![CDATA[@shreenibas]]></category><dc:creator><![CDATA[Shreenibas Samal]]></dc:creator><pubDate>Wed, 15 Oct 2025 00:20:23 GMT</pubDate><content:encoded><![CDATA[<p>fbfvfdgfdgg</p>
<p>fgdfgfdgdfgnfdvdg</p>
<p>dfgfdgdf</p>
<p>g</p>
<p>dfgdfg</p>
<p>dfg</p>
<p>gdfgdg</p>
<p>dg</p>
<p>dgd</p>
<p>g</p>
<p>g</p>
<p>dgdg</p>
<p>d</p>
<p>dgdgd</p>
<p>g</p>
]]></content:encoded></item><item><title><![CDATA[01 Introduction To RestAssured]]></title><description><![CDATA[RestAssured is a Java-based library used for testing RESTful APIs.It supports all HTTP requests (GET, POST, PUT, PATCH, DELETE, etc.) and validate responses easily without writing a lot of boilerplate code.
Lets Assume as a tool that allows you to ac...]]></description><link>https://shreenibas-api-restassured.hashnode.dev/01-introduction-to-restassured</link><guid isPermaLink="true">https://shreenibas-api-restassured.hashnode.dev/01-introduction-to-restassured</guid><category><![CDATA[@shreenibas]]></category><dc:creator><![CDATA[Shreenibas Samal]]></dc:creator><pubDate>Tue, 14 Oct 2025 14:50:12 GMT</pubDate><content:encoded><![CDATA[<p><strong>RestAssured</strong> is a <strong>Java-based library</strong> used for <strong>testing RESTful APIs</strong>.<br />It supports all <strong>HTTP</strong> requests (GET, POST, PUT, PATCH, DELETE, etc.) and validate responses easily without writing a lot of boilerplate code.</p>
<p>Lets Assume as a tool that allows you to act like a browser or mobile app, but from your test scripts — so you can <strong>send API calls, receive responses, and verify them</strong>.</p>
<hr />
<h2 id="heading-key-points"><strong>Key Points</strong></h2>
<ul>
<li><p><strong>Purpose</strong> → Automates testing of REST APIs.</p>
</li>
<li><p><strong>Language</strong> → Java (can also be used in Kotlin, Groovy, etc.).</p>
</li>
<li><p><strong>Integration</strong> → Works well with TestNG, JUnit, Maven, and Jenkins.</p>
</li>
<li><p><strong>Data formats supported</strong> → JSON, XML, HTML, and plain text.</p>
</li>
<li><p><strong>Assertions</strong> → Built-in BDD-style syntax (<code>given-when-then</code>) and <strong>Hamcrest matchers</strong> for validation.</p>
</li>
</ul>
<hr />
<h2 id="heading-why-qa-amp-automation-testers-use-it"><strong>Why QA &amp; Automation Testers Use It</strong></h2>
<ol>
<li><p>No need to manually create <code>HttpURLConnection</code> or <code>HttpClient</code> code.</p>
</li>
<li><p>Supports <strong>BDD-style syntax</strong> → <code>given().when().then()</code> makes scripts easy to read.</p>
</li>
<li><p>Can send requests with:</p>
<ul>
<li><p>Query parameters</p>
</li>
<li><p>Path parameters</p>
</li>
<li><p>Headers</p>
</li>
<li><p>Cookies</p>
</li>
<li><p>Request body (JSON, XML, POJO)</p>
</li>
</ul>
</li>
<li><p>Can validate:</p>
<ul>
<li><p>Status codes</p>
</li>
<li><p>Response time</p>
</li>
<li><p>Headers</p>
</li>
<li><p>JSON/XML values</p>
</li>
</ul>
</li>
<li><p>Can handle authentication (Basic, OAuth, etc.).</p>
</li>
</ol>
<h2 id="heading-before-going-deep-we-need-to-know-some-of-concept-below">Before going Deep we need to know some of concept Below</h2>
<ul>
<li><h2 id="heading-static-import">Static import</h2>
</li>
<li><h2 id="heading-method-chaining">Method chaining</h2>
</li>
<li><h2 id="heading-restassured-class-daigram">RestAssured Class Daigram</h2>
</li>
</ul>
<h3 id="heading-static-import-in-java">Static import in java</h3>
<p>Java introduced the static import in JDK 1.5 . static import allows public and static members, i.e, fields and methods of a class to be used in java code without using specifying the class name.</p>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> packageName.ClassName.*;
</code></pre>
<p>let’s break down <strong>static import in Java</strong> with an example, especially in the context of <strong>RestAssured</strong>.</p>
<hr />
<h2 id="heading-1-what-is-static-import"><strong>1️⃣ What is Static Import?</strong></h2>
<ul>
<li>Normally, when you call a static method or use a static field from another class, you write the <strong>class name</strong> before it:</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">Math.sqrt(<span class="hljs-number">16</span>);
System.out.println(Math.PI);
</code></pre>
<ul>
<li><strong>Static import</strong> lets you use them <strong>directly</strong> without prefixing the class name:</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> java.lang.Math.sqrt;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> java.lang.Math.PI;

System.out.println(sqrt(<span class="hljs-number">16</span>));
System.out.println(PI);
</code></pre>
<p>It basically makes static members look like they are in your own class.</p>
<hr />
<h2 id="heading-2-static-import-in-restassured"><strong>2️⃣ Static Import in RestAssured</strong></h2>
<p>In RestAssured, methods like <code>given()</code>, <code>when()</code>, <code>then()</code>, <code>get()</code>, and matchers like <code>equalTo()</code> are <strong>static methods</strong> in their classes.</p>
<h3 id="heading-without-static-import">Without static import:</h3>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> io.restassured.RestAssured;
<span class="hljs-keyword">import</span> org.hamcrest.Matchers;

RestAssured.given()
    .when().get(<span class="hljs-string">"https://reqres.in/api/users/2"</span>)
    .then().statusCode(<span class="hljs-number">200</span>)
    .body(<span class="hljs-string">"data.first_name"</span>, Matchers.equalTo(<span class="hljs-string">"Janet"</span>));
</code></pre>
<h3 id="heading-with-static-import">With static import:</h3>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;

given()
    .when().get(<span class="hljs-string">"https://reqres.in/api/users/2"</span>)
    .then().statusCode(<span class="hljs-number">200</span>)
    .body(<span class="hljs-string">"data.first_name"</span>, equalTo(<span class="hljs-string">"Janet"</span>));
</code></pre>
<p>✅ <strong>Benefits:</strong></p>
<ul>
<li><p>Cleaner &amp; shorter code</p>
</li>
<li><p>More readable in BDD-style API tests</p>
</li>
<li><p>Matches natural language style:<br />  <code>given() → when() → then()</code></p>
</li>
</ul>
<hr />
<h2 id="heading-3-full-working-example"><strong>3️⃣ Full Working Example</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StaticImportExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        given()
            .baseUri(<span class="hljs-string">"https://reqres.in"</span>)
        .when()
            .get(<span class="hljs-string">"/api/users/2"</span>)
        .then()
            .statusCode(<span class="hljs-number">200</span>)
            .body(<span class="hljs-string">"data.first_name"</span>, equalTo(<span class="hljs-string">"Janet"</span>));
    }
}
</code></pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><p><strong>given()</strong> → Set up request (base URI, params, headers).</p>
</li>
<li><p><strong>when()</strong> → Send request (GET, POST, PUT, etc.).</p>
</li>
<li><p><strong>then()</strong> → Verify the response.</p>
</li>
</ul>
<h3 id="heading-method-chaining-in-java">Method Chaining in java.</h3>
<p>Suppose there is a java class and it contains 3 static/non-static methods and we call each method as below.</p>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">A a1 = <span class="hljs-keyword">new</span> A();

a1.a().b().c();
</code></pre>
<p><strong>NOTE: To acheive method chaining</strong></p>
<ol>
<li><p>A method return type should not void.</p>
</li>
<li><p>A method can return current class object.</p>
</li>
<li><p>A method can return other class object as well.</p>
</li>
<li><p>A method can return other interface reference object as well .</p>
</li>
</ol>
<p><strong>Advantage of method chaining is the code optimization.</strong></p>
<h3 id="heading-rest-assured-class-architecture">Rest Assured Class Architecture</h3>
<h2 id="heading-core-components-of-restassured">🧩 Core Components of RestAssured</h2>
<h3 id="heading-1-restassured-class">1. <strong>RestAssured (Class)</strong></h3>
<ul>
<li><p><strong>Role</strong>: Serves as the entry point for initiating API requests.</p>
</li>
<li><p><strong>Key Methods</strong>:</p>
<ul>
<li><p><code>given()</code>: Prepares a new request specification.</p>
</li>
<li><p><code>when()</code>: Specifies the HTTP method to be executed.</p>
</li>
<li><p><code>then()</code>: Validates the response and provides assertion methods.</p>
</li>
<li><p><code>baseUri()</code>, <code>basePath()</code>, <code>port()</code>: Set global configurations for the API base URI, path, and port.</p>
</li>
<li><p><code>auth()</code>: Configures authentication mechanisms.</p>
</li>
<li><p><code>proxy()</code>: Sets up proxy configurations.</p>
</li>
<li><p><code>config()</code>: Allows customization of the RestAssured configuration.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-2-requestspecification-interface">2. <strong>RequestSpecification (Interface)</strong></h3>
<ul>
<li><p><strong>Role</strong>: Defines the structure and configuration of an HTTP request.</p>
</li>
<li><p><strong>Key Methods</strong>:</p>
<ul>
<li><p><code>header()</code>, <code>queryParam()</code>, <code>formParam()</code>: Add headers and parameters to the request.</p>
</li>
<li><p><code>body()</code>: Sets the request body.</p>
</li>
<li><p><code>auth()</code>: Configures authentication for the request.</p>
</li>
<li><p><code>config()</code>: Sets specific configurations for this request.</p>
</li>
<li><p><code>spec()</code>: Allows reuse of existing request specifications.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-3-requestsender-interface">3. <strong>RequestSender (Interface)</strong></h3>
<ul>
<li><p><strong>Role</strong>: Represents the action of sending an HTTP request.</p>
</li>
<li><p><strong>Key Methods</strong>:</p>
<ul>
<li><p><code>get()</code>, <code>post()</code>, <code>put()</code>, <code>delete()</code>, <code>patch()</code>: Execute the corresponding HTTP methods.</p>
</li>
<li><p><code>then()</code>: Returns a <code>Response</code> object for further validation.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-4-response-interface">4. <strong>Response (Interface)</strong></h3>
<ul>
<li><p><strong>Role</strong>: Represents the HTTP response received after executing a request.</p>
</li>
<li><p><strong>Key Methods</strong>:</p>
<ul>
<li><p><code>getStatusCode()</code>, <code>getBody()</code>, <code>getHeader()</code>: Retrieve status code, body, and headers from the response.</p>
</li>
<li><p><code>jsonPath()</code>, <code>xmlPath()</code>: Parse the response body as JSON or XML.</p>
</li>
<li><p><code>then()</code>: Returns a <code>ValidatableResponse</code> for assertions.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-5-validatableresponse-interface">5. <strong>ValidatableResponse (Interface)</strong></h3>
<ul>
<li><p><strong>Role</strong>: Provides methods to validate and assert the response.</p>
</li>
<li><p><strong>Key Methods</strong>:</p>
<ul>
<li><p><code>statusCode()</code>, <code>body()</code>, <code>header()</code>: Assert specific aspects of the response.</p>
</li>
<li><p><code>log()</code>: Logs the response for debugging purposes.</p>
</li>
<li><p><code>extract()</code>: Extracts data from the response for further use.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-6-authenticationspecification-interface">6. <strong>AuthenticationSpecification (Interface)</strong></h3>
<ul>
<li><p><strong>Role</strong>: Defines methods for configuring authentication mechanisms.</p>
</li>
<li><p><strong>Key Methods</strong>:</p>
<ul>
<li><p><code>basic()</code>, <code>certificate()</code>, <code>oauth2()</code>: Configure different authentication methods.</p>
</li>
<li><p><code>preemptive()</code>: Sets up preemptive authentication.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-7-filter-interface">7. <strong>Filter (Interface)</strong></h3>
<ul>
<li><p><strong>Role</strong>: Allows interception and modification of requests and responses.</p>
</li>
<li><p><strong>Key Implementations</strong>:</p>
<ul>
<li><p><code>RequestLoggingFilter</code>, <code>ResponseLoggingFilter</code>: Log request and response details.</p>
</li>
<li><p><code>AuthenticationFilter</code>: Handles authentication during request execution.</p>
</li>
<li><p><code>LoggingFilter</code>: Provides logging capabilities for requests and responses.</p>
</li>
</ul>
</li>
</ul>
<hr />
<h2 id="heading-method-chaining-flow">🔄 Method Chaining Flow</h2>
<p>RestAssured's design supports method chaining through interfaces that return the same type or compatible types, enabling a fluent API. For example:</p>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">given()
    .baseUri(<span class="hljs-string">"https://api.example.com"</span>)
    .header(<span class="hljs-string">"Authorization"</span>, <span class="hljs-string">"Bearer token"</span>)
    .body(<span class="hljs-string">"{ \"name\": \"John\" }"</span>)
.when()
    .post(<span class="hljs-string">"/users"</span>)
.then()
    .statusCode(<span class="hljs-number">201</span>)
    .body(<span class="hljs-string">"name"</span>, equalTo(<span class="hljs-string">"John"</span>));
</code></pre>
<p>In this example:</p>
<ul>
<li><p><code>given()</code> returns a <code>RequestSpecification</code>.</p>
</li>
<li><p>Methods like <code>baseUri()</code>, <code>header()</code>, and <code>body()</code> return the same <code>RequestSpecification</code>, allowing further configuration.</p>
</li>
<li><p><code>when()</code> returns a <code>RequestSender</code>.</p>
</li>
<li><p><code>post()</code> executes the HTTP POST method and returns a <code>Response</code>.</p>
</li>
<li><p><code>then()</code> returns a <code>ValidatableResponse</code> for assertions.</p>
</li>
</ul>
<hr />
<h2 id="heading-summary-table">🧩 Summary Table</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Component</strong></td><td><strong>Type</strong></td><td><strong>Role</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>RestAssured</code></td><td>Class</td><td>Entry point for initiating requests</td></tr>
<tr>
<td><code>RequestSpecification</code></td><td>Interface</td><td>Defines request structure and configuration</td></tr>
<tr>
<td><code>RequestSender</code></td><td>Interface</td><td>Represents the action of sending a request</td></tr>
<tr>
<td><code>Response</code></td><td>Interface</td><td>Represents the HTTP response</td></tr>
<tr>
<td><code>ValidatableResponse</code></td><td>Interface</td><td>Provides methods for response validation</td></tr>
<tr>
<td><code>AuthenticationSpecification</code></td><td>Interface</td><td>Configures authentication mechanisms</td></tr>
<tr>
<td><code>Filter</code></td><td>Interface</td><td>Allows interception and modification of requests and responses</td></tr>
</tbody>
</table>
</div><h2 id="heading-1-overview-of-restassured-class"><strong>1️⃣ Overview of</strong> <code>RestAssured</code> Class</h2>
<ul>
<li><p><strong>Package</strong>: <code>io.restassured.RestAssured</code></p>
</li>
<li><p><strong>Type</strong>: Public class</p>
</li>
<li><p><strong>Role</strong>:<br />  The <code>RestAssured</code> class is the <strong>entry point</strong> for creating requests in RestAssured.<br />  It provides <strong>static methods</strong> to configure requests, set authentication, base URIs, logging, and more.</p>
</li>
</ul>
<hr />
<h2 id="heading-2-key-static-fields"><strong>2️⃣ Key Static Fields</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Field</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>baseURI</code></td><td>String</td><td>Base URI for all requests (e.g., <a target="_blank" href="https://reqres.in/"><code>https://reqres.in</code></a>)</td></tr>
<tr>
<td><code>basePath</code></td><td>String</td><td>Base path appended to the base URI</td></tr>
<tr>
<td><code>port</code></td><td>int</td><td>Port number for requests</td></tr>
<tr>
<td><code>authenticationScheme</code></td><td>AuthenticationScheme</td><td>Default authentication scheme (basic, oauth, etc.)</td></tr>
<tr>
<td><code>filters</code></td><td>List&lt;Filter&gt;</td><td>Default request/response filters applied globally</td></tr>
<tr>
<td><code>config</code></td><td>RestAssuredConfig</td><td>Global configuration object (timeouts, encoder, decoder, SSL, etc.)</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-3-key-static-methods"><strong>3️⃣ Key Static Methods</strong></h2>
<h3 id="heading-request-initialization"><strong>Request Initialization</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Return Type</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>given()</code></td><td>RequestSpecification</td><td>Start building a request; the most common entry point</td></tr>
<tr>
<td><code>when()</code></td><td>RequestSender</td><td>Start defining the HTTP method to execute</td></tr>
<tr>
<td><code>then()</code></td><td>ValidatableResponse</td><td>Starts response validation directly from a request</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-configuration-methods"><strong>Configuration Methods</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>baseURI(String uri)</code></td><td>Set the global base URI</td></tr>
<tr>
<td><code>basePath(String path)</code></td><td>Set the global base path</td></tr>
<tr>
<td><code>port(int port)</code></td><td>Set the global port</td></tr>
<tr>
<td><code>rootPath(String rootPath)</code></td><td>Default JSON/XML root path for response validation</td></tr>
<tr>
<td><code>config(RestAssuredConfig config)</code></td><td>Apply global configuration</td></tr>
<tr>
<td><code>filters(List&lt;Filter&gt; filters)</code></td><td>Add filters globally</td></tr>
<tr>
<td><code>authentication = AuthenticationScheme</code></td><td>Set default authentication globally</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-authentication-methods"><strong>Authentication Methods</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>auth().basic(user, pass)</code></td><td>Basic authentication</td></tr>
<tr>
<td><code>auth().digest(user, pass)</code></td><td>Digest authentication</td></tr>
<tr>
<td><code>auth().oauth2(token)</code></td><td>OAuth2 authentication</td></tr>
<tr>
<td><code>auth().preemptive().basic(user, pass)</code></td><td>Preemptive authentication</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-logging-amp-filters"><strong>Logging &amp; Filters</strong></h3>
<ul>
<li><p><code>filters()</code> – Apply global filters (logging, reporting)</p>
</li>
<li><p>Common filters:</p>
<ul>
<li><p><code>RequestLoggingFilter</code></p>
</li>
<li><p><code>ResponseLoggingFilter</code></p>
</li>
<li><p><code>CustomFilter</code> (user-defined)</p>
</li>
</ul>
</li>
</ul>
<hr />
<h3 id="heading-example-usage"><strong>Example Usage</strong></h3>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestAssuredExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Global configuration</span>
        baseURI = <span class="hljs-string">"https://reqres.in"</span>;
        port = <span class="hljs-number">443</span>;
        basePath = <span class="hljs-string">"/api"</span>;

        <span class="hljs-comment">// Sending a POST request</span>
        given()
            .header(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>)
            .body(<span class="hljs-string">"{\"name\":\"John\", \"job\":\"Developer\"}"</span>)
        .when()
            .post(<span class="hljs-string">"/users"</span>)
        .then()
            .statusCode(<span class="hljs-number">201</span>)
            .log().all();
    }
}
</code></pre>
<p><strong>Explanation</strong>:</p>
<ul>
<li><p><code>given()</code> – Starts the request specification.</p>
</li>
<li><p><code>when().post("/users")</code> – Sends the HTTP POST request.</p>
</li>
<li><p><code>then()</code> – Validates the response.</p>
</li>
<li><p><code>baseURI</code>, <code>basePath</code>, and <code>port</code> are global static fields of <code>RestAssured</code>.</p>
</li>
</ul>
<hr />
<h3 id="heading-4-internal-architecture-of-restassured-class"><strong>4️⃣ Internal Architecture of RestAssured Class</strong></h3>
<ol>
<li><p><strong>Static entry points</strong>: <code>given()</code>, <code>when()</code>, <code>then()</code></p>
</li>
<li><p><strong>Global configurations</strong>: Base URI, base path, port, filters, and authentication.</p>
</li>
<li><p><strong>Delegation</strong>:</p>
<ul>
<li><p><code>given()</code> returns <code>RequestSpecificationImpl</code></p>
</li>
<li><p><code>when()</code> returns <code>RequestSender</code></p>
</li>
<li><p><code>then()</code> returns <code>ValidatableResponseImpl</code></p>
</li>
</ul>
</li>
<li><p><strong>Filters &amp; logging</strong> are applied either globally (via <code>RestAssured.filters()</code>) or per request (via <code>RequestSpecification.filters()</code>).</p>
</li>
</ol>
<hr />
<h3 id="heading-key-points-1">✅ <strong>Key Points</strong></h3>
<ul>
<li><p><code>RestAssured</code> is a <strong>static utility class</strong>; you rarely instantiate it.</p>
</li>
<li><p>Most operations use <strong>method chaining</strong> starting from <code>given()</code>.</p>
</li>
<li><p>It acts as a <strong>facade</strong> hiding the internal request/response objects.</p>
</li>
<li><p>Supports <strong>global configuration</strong> and <strong>per-request customization</strong>.</p>
</li>
</ul>
<h2 id="heading-1-overview-of-requestspecification"><strong>1️⃣ Overview of RequestSpecification</strong></h2>
<ul>
<li><p><strong>Package:</strong> <code>io.restassured.specification</code></p>
</li>
<li><p><strong>Type:</strong> Interface</p>
</li>
<li><p><strong>Role:</strong><br />  <code>RequestSpecification</code> represents a <strong>request configuration</strong> in RestAssured.<br />  It contains <strong>headers, query/form parameters, body, cookies, authentication, and more</strong>.</p>
</li>
<li><p>Returned by <code>RestAssured.given()</code> and acts as the starting point for building a request.</p>
</li>
</ul>
<hr />
<h2 id="heading-2-key-methods-of-requestspecification"><strong>2️⃣ Key Methods of RequestSpecification</strong></h2>
<h3 id="heading-a-base-configuration"><strong>A. Base Configuration</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>baseUri(String uri)</code></td><td>Sets the base URI for the request.</td></tr>
<tr>
<td><code>basePath(String path)</code></td><td>Sets the base path to append to the URI.</td></tr>
<tr>
<td><code>port(int port)</code></td><td>Sets the port for the request.</td></tr>
<tr>
<td><code>rootPath(String path)</code></td><td>Sets a default root path for JSON/XML response validation.</td></tr>
<tr>
<td><code>config(RestAssuredConfig config)</code></td><td>Apply request-specific configuration (timeouts, encoder/decoder, SSL).</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-b-headers-and-cookies"><strong>B. Headers and Cookies</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>header(String name, Object value)</code></td><td>Adds a single header.</td></tr>
<tr>
<td><code>headers(Map&lt;String,Object&gt;)</code></td><td>Add multiple headers at once.</td></tr>
<tr>
<td><code>cookie(String name, Object value)</code></td><td>Add a single cookie.</td></tr>
<tr>
<td><code>cookies(Map&lt;String,Object&gt;)</code></td><td>Add multiple cookies.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-c-query-form-path-parameters"><strong>C. Query, Form, Path Parameters</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>queryParam(String name, Object value)</code></td><td>Add a query parameter to the URL.</td></tr>
<tr>
<td><code>queryParams(Map&lt;String,Object&gt;)</code></td><td>Add multiple query parameters.</td></tr>
<tr>
<td><code>pathParam(String name, Object value)</code></td><td>Add path parameter for dynamic URL segments.</td></tr>
<tr>
<td><code>formParam(String name, Object value)</code></td><td>Add form parameters for <code>application/x-www-form-urlencoded</code> POST requests.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-d-request-body"><strong>D. Request Body</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>body(Object object)</code></td><td>Set the request body as string, JSON, or POJO.</td></tr>
<tr>
<td><code>body(String body)</code></td><td>Set the raw string body.</td></tr>
<tr>
<td><code>body(byte[] bytes)</code></td><td>Set binary data as body.</td></tr>
<tr>
<td><code>multiPart(String controlName, Object file)</code></td><td>Add file or form parts for multipart requests.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-e-authentication"><strong>E. Authentication</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>auth()</code></td><td>Returns <code>AuthenticationSpecification</code> for configuring authentication.</td></tr>
<tr>
<td><code>auth().basic(user, pass)</code></td><td>Basic auth.</td></tr>
<tr>
<td><code>auth().digest(user, pass)</code></td><td>Digest auth.</td></tr>
<tr>
<td><code>auth().oauth2(token)</code></td><td>OAuth2 token auth.</td></tr>
<tr>
<td><code>auth().preemptive().basic(user, pass)</code></td><td>Preemptive authentication.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-f-logging-and-filters"><strong>F. Logging and Filters</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>log().all()</code></td><td>Log all request details.</td></tr>
<tr>
<td><code>log().headers()</code></td><td>Log only headers.</td></tr>
<tr>
<td><code>filters(List&lt;Filter&gt; filters)</code></td><td>Apply filters (logging, reporting, custom).</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-g-miscellaneous"><strong>G. Miscellaneous</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>accept(String mimeType)</code></td><td>Set the Accept header.</td></tr>
<tr>
<td><code>contentType(String mimeType)</code></td><td>Set the Content-Type header.</td></tr>
<tr>
<td><code>spec(RequestSpecification spec)</code></td><td>Reuse an existing request specification.</td></tr>
<tr>
<td><code>sessionId(String sessionId)</code></td><td>Set session ID for request.</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-3-example-usage"><strong>3️⃣ Example Usage</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> io.restassured.specification.RequestSpecification;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RequestSpecExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        RequestSpecification request = given()
            .baseUri(<span class="hljs-string">"https://reqres.in"</span>)
            .basePath(<span class="hljs-string">"/api"</span>)
            .header(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>)
            .queryParam(<span class="hljs-string">"page"</span>, <span class="hljs-number">2</span>)
            .body(<span class="hljs-string">"{\"name\":\"John\",\"job\":\"Developer\"}"</span>)
            .auth().basic(<span class="hljs-string">"user"</span>, <span class="hljs-string">"pass"</span>);

        request
            .when().post(<span class="hljs-string">"/users"</span>)
            .then().statusCode(<span class="hljs-number">201</span>)
            .log().all();
    }
}
</code></pre>
<p><strong>Explanation</strong>:</p>
<ol>
<li><p><code>given()</code> → Returns <code>RequestSpecification</code>.</p>
</li>
<li><p><code>.baseUri()</code>, <code>.basePath()</code>, <code>.header()</code>, <code>.body()</code> → Configure request.</p>
</li>
<li><p><code>.auth()</code> → Add authentication.</p>
</li>
<li><p><code>request.when().post()</code> → Send request.</p>
</li>
<li><p><code>.then()</code> → Validate response.</p>
</li>
</ol>
<hr />
<h2 id="heading-4-internal-flow"><strong>4️⃣ Internal Flow</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">RestAssured.given() → RequestSpecificationImpl
    └─ Stores all headers, params, body, cookies, authentication
    └─ Can attach filters and logging
    └─ Supports method chaining
RequestSpecification → RequestSender (when()) → Response → ValidatableResponse (then())
</code></pre>
<hr />
<h2 id="heading-5-key-points"><strong>5️⃣ Key Points</strong></h2>
<ul>
<li><p><code>RequestSpecification</code> is <strong>chainable</strong>; most methods return the same object.</p>
</li>
<li><p>Can be <strong>global or reusable</strong> by defining a <code>RequestSpecification</code> and passing it via <code>.spec()</code>.</p>
</li>
<li><p>Encapsulates <strong>all aspects of an HTTP request</strong>: headers, params, body, cookies, authentication, logging.</p>
</li>
<li><p>Core interface in <strong>all RestAssured tests</strong>.</p>
</li>
</ul>
<h2 id="heading-1-overview-of-requestsender"><strong>1️⃣ Overview of</strong> <code>RequestSender</code></h2>
<ul>
<li><p><strong>Package:</strong> <code>io.restassured.specification</code></p>
</li>
<li><p><strong>Type:</strong> Interface</p>
</li>
<li><p><strong>Role:</strong><br />  <code>RequestSender</code> is responsible for <strong>sending the HTTP request</strong> built via <code>RequestSpecification</code>.<br />  It provides the HTTP method calls like <code>get()</code>, <code>post()</code>, <code>put()</code>, <code>delete()</code>, <code>patch()</code>, etc.</p>
</li>
<li><p>Typically returned by <code>.when()</code> in RestAssured:</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">given()            <span class="hljs-comment">// RequestSpecification</span>
.when()            <span class="hljs-comment">// returns RequestSender</span>
    .get(<span class="hljs-string">"/users"</span>) <span class="hljs-comment">// executes request</span>
.then();           <span class="hljs-comment">// ValidatableResponse</span>
</code></pre>
<hr />
<h2 id="heading-2-key-methods-of-requestsender"><strong>2️⃣ Key Methods of RequestSender</strong></h2>
<h3 id="heading-a-http-methods"><strong>A. HTTP Methods</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>get(String path, Object... pathParams)</code></td><td>Sends an HTTP GET request to the specified path.</td></tr>
<tr>
<td><code>post(String path, Object... pathParams)</code></td><td>Sends an HTTP POST request to the specified path.</td></tr>
<tr>
<td><code>put(String path, Object... pathParams)</code></td><td>Sends an HTTP PUT request to the specified path.</td></tr>
<tr>
<td><code>delete(String path, Object... pathParams)</code></td><td>Sends an HTTP DELETE request to the specified path.</td></tr>
<tr>
<td><code>patch(String path, Object... pathParams)</code></td><td>Sends an HTTP PATCH request to the specified path.</td></tr>
<tr>
<td><code>head(String path, Object... pathParams)</code></td><td>Sends an HTTP HEAD request to the specified path.</td></tr>
<tr>
<td><code>options(String path, Object... pathParams)</code></td><td>Sends an HTTP OPTIONS request to the specified path.</td></tr>
</tbody>
</table>
</div><blockquote>
<p><strong><em>All HTTP methods return a</em></strong> <code>Response</code> object.</p>
</blockquote>
<hr />
<h3 id="heading-b-formatted-requests"><strong>B. Formatted Requests</strong></h3>
<ul>
<li>Methods also exist to <strong>send requests with dynamic path parameters</strong>:</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">get(<span class="hljs-string">"/users/{id}"</span>, <span class="hljs-number">2</span>)       <span class="hljs-comment">// id=2 will replace {id} in path</span>
post(<span class="hljs-string">"/users/{id}"</span>, <span class="hljs-number">3</span>)      <span class="hljs-comment">// id=3 will replace {id} in path</span>
</code></pre>
<ul>
<li>This supports <strong>path templating</strong>.</li>
</ul>
<hr />
<h3 id="heading-c-asynchronous-and-specialized-requests"><strong>C. Asynchronous and Specialized Requests</strong></h3>
<ul>
<li><p>Some versions/extensions of RestAssured support <strong>async requests</strong> using <code>async()</code> (advanced usage).</p>
</li>
<li><p>Multipart requests are typically configured via <code>RequestSpecification</code> rather than <code>RequestSender</code>.</p>
</li>
</ul>
<hr />
<h2 id="heading-3-example-usage-1"><strong>3️⃣ Example Usage</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RequestSenderExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        given()
            .baseUri(<span class="hljs-string">"https://reqres.in"</span>)
            .basePath(<span class="hljs-string">"/api"</span>)
            .queryParam(<span class="hljs-string">"page"</span>, <span class="hljs-number">2</span>)
        .when()
            .get(<span class="hljs-string">"/users"</span>)  <span class="hljs-comment">// RequestSender executes GET</span>
        .then()
            .statusCode(<span class="hljs-number">200</span>)
            .log().all();
    }
}
</code></pre>
<p><strong>Flow Explained:</strong></p>
<ol>
<li><p><code>given()</code> → Returns <code>RequestSpecification</code>.</p>
</li>
<li><p><code>.when()</code> → Returns <code>RequestSender</code>.</p>
</li>
<li><p><code>.get("/users")</code> → Sends HTTP GET, returns <code>Response</code>.</p>
</li>
<li><p><code>.then()</code> → Converts <code>Response</code> to <code>ValidatableResponse</code> for assertions.</p>
</li>
</ol>
<hr />
<h2 id="heading-4-internal-flow-1"><strong>4️⃣ Internal Flow</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">RequestSpecification → when() → RequestSender
    └─ Executes HTTP request via Apache HttpClient / Java HTTP client
    └─ Applies headers, body, params, cookies, filters
    └─ Returns Response
Response → then() → ValidatableResponse
</code></pre>
<hr />
<h2 id="heading-5-key-points-1"><strong>5️⃣ Key Points</strong></h2>
<ul>
<li><p><code>RequestSender</code> is <strong>stateless</strong>; it simply executes the request built by <code>RequestSpecification</code>.</p>
</li>
<li><p>Supports <strong>all HTTP methods</strong> (<code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code>, <code>PATCH</code>, <code>HEAD</code>, <code>OPTIONS</code>).</p>
</li>
<li><p>Integrates <strong>path parameters</strong> and <strong>query parameters</strong> during execution.</p>
</li>
<li><p>Works with <strong>filters</strong>, <strong>authentication</strong>, and <strong>logging</strong> applied in <code>RequestSpecification</code>.</p>
</li>
</ul>
<hr />
<p>If you want, I can prepare a <strong>full RestAssured architecture diagram</strong> showing <strong>RequestSpecification → RequestSender → Response → ValidatableResponse</strong>, including <strong>filters and authentication flow</strong> — it’s perfect for interview prep.</p>
<h2 id="heading-1-overview-of-response"><strong>1️⃣ Overview of</strong> <code>Response</code></h2>
<ul>
<li><p><strong>Package:</strong> <code>io.restassured.response</code></p>
</li>
<li><p><strong>Type:</strong> Interface</p>
</li>
<li><p><strong>Role:</strong><br />  <code>Response</code> encapsulates all the information received from the server after an HTTP request.<br />  It provides <strong>methods to access status codes, headers, cookies, body content</strong>, and allows <strong>parsing JSON/XML responses</strong>.</p>
</li>
<li><p>Returned by <code>RequestSender</code> methods like <code>get()</code>, <code>post()</code>, <code>put()</code>, <code>delete()</code>, etc.</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">Response response = given()
                        .baseUri(<span class="hljs-string">"https://reqres.in"</span>)
                        .basePath(<span class="hljs-string">"/api"</span>)
                    .when()
                        .get(<span class="hljs-string">"/users/2"</span>);
</code></pre>
<hr />
<h2 id="heading-2-key-methods-of-response"><strong>2️⃣ Key Methods of Response</strong></h2>
<h3 id="heading-a-status-and-line"><strong>A. Status and Line</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>getStatusCode()</code></td><td>Returns HTTP status code (e.g., 200, 404).</td></tr>
<tr>
<td><code>getStatusLine()</code></td><td>Returns the full HTTP status line (e.g., "HTTP/1.1 200 OK").</td></tr>
<tr>
<td><code>getDetailedCookies()</code></td><td>Returns cookies as a map.</td></tr>
<tr>
<td><code>getContentType()</code></td><td>Returns the Content-Type header.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-b-headers"><strong>B. Headers</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>getHeader(String name)</code></td><td>Returns the value of a specific header.</td></tr>
<tr>
<td><code>getHeaders()</code></td><td>Returns all headers as <code>Headers</code> object.</td></tr>
<tr>
<td><code>hasHeaderWithName(String name)</code></td><td>Checks if a header exists.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-c-cookies"><strong>C. Cookies</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>getCookie(String name)</code></td><td>Get a specific cookie.</td></tr>
<tr>
<td><code>getCookies()</code></td><td>Returns all cookies as a <code>Map&lt;String, String&gt;</code>.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-d-response-body"><strong>D. Response Body</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>getBody()</code></td><td>Returns the body as a <code>ResponseBody</code> object.</td></tr>
<tr>
<td><code>asString()</code></td><td>Returns body as a raw string.</td></tr>
<tr>
<td><code>asByteArray()</code></td><td>Returns body as bytes.</td></tr>
<tr>
<td><code>as(InputStream.class)</code></td><td>Returns body as input stream.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-e-jsonxml-parsing"><strong>E. JSON/XML Parsing</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>jsonPath()</code></td><td>Returns <code>JsonPath</code> object to query JSON body using GPath expressions.</td></tr>
<tr>
<td><code>xmlPath()</code></td><td>Returns <code>XmlPath</code> object to query XML body using GPath expressions.</td></tr>
</tbody>
</table>
</div><p><strong>Example:</strong></p>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">String firstName = response.jsonPath().getString(<span class="hljs-string">"data.first_name"</span>);
String lastName = response.jsonPath().getString(<span class="hljs-string">"data.last_name"</span>);
</code></pre>
<hr />
<h3 id="heading-f-validations"><strong>F. Validations</strong></h3>
<ul>
<li><p><code>then()</code> → Converts <code>Response</code> into <code>ValidatableResponse</code> for assertions.</p>
</li>
<li><p>Example:</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">response.then().statusCode(<span class="hljs-number">200</span>).body(<span class="hljs-string">"data.id"</span>, equalTo(<span class="hljs-number">2</span>));
</code></pre>
<hr />
<h3 id="heading-g-miscellaneous-1"><strong>G. Miscellaneous</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>prettyPrint()</code></td><td>Prints response body in readable format.</td></tr>
<tr>
<td><code>prettyPeek()</code></td><td>Prints response and returns it for chaining.</td></tr>
<tr>
<td><code>peek()</code></td><td>Prints a summary of the response (status, headers).</td></tr>
<tr>
<td><code>path(String path)</code></td><td>Extracts value from body using GPath.</td></tr>
<tr>
<td><code>as(Class&lt;T&gt; cls)</code></td><td>Deserialize response body into a POJO.</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-3-example-usage-2"><strong>3️⃣ Example Usage</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> io.restassured.response.Response;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ResponseExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Response response = given()
                                .baseUri(<span class="hljs-string">"https://reqres.in"</span>)
                                .basePath(<span class="hljs-string">"/api"</span>)
                            .when()
                                .get(<span class="hljs-string">"/users/2"</span>);

        <span class="hljs-comment">// Status and headers</span>
        System.out.println(response.getStatusCode());
        System.out.println(response.getHeader(<span class="hljs-string">"Content-Type"</span>));

        <span class="hljs-comment">// Body as string</span>
        System.out.println(response.asString());

        <span class="hljs-comment">// Extract JSON value</span>
        String firstName = response.jsonPath().getString(<span class="hljs-string">"data.first_name"</span>);
        System.out.println(firstName);

        <span class="hljs-comment">// Validatable</span>
        response.then().statusCode(<span class="hljs-number">200</span>).body(<span class="hljs-string">"data.id"</span>, equalTo(<span class="hljs-number">2</span>));
    }
}
</code></pre>
<hr />
<h2 id="heading-4-internal-flow-2"><strong>4️⃣ Internal Flow</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">RequestSpecification → RequestSender (when()) → Response
    └─ Captures HTTP status code, headers, cookies, body
    └─ <span class="hljs-function">Provides methods <span class="hljs-keyword">for</span> <span class="hljs-title">parsing</span> <span class="hljs-params">(JSON, XML)</span>
    └─ Supports logging and validation via <span class="hljs-title">then</span><span class="hljs-params">()</span></span>
</code></pre>
<hr />
<h2 id="heading-5-key-points-2"><strong>5️⃣ Key Points</strong></h2>
<ul>
<li><p><code>Response</code> is <strong>immutable</strong>; it reflects the server’s returned data.</p>
</li>
<li><p>Works seamlessly with <strong>JSON/XML parsing</strong>, <strong>POJO deserialization</strong>, and <strong>GPath expressions</strong>.</p>
</li>
<li><p>Enables <strong>method chaining</strong> by converting into <code>ValidatableResponse</code>.</p>
</li>
<li><p>Supports both <strong>raw data access</strong> (asString(), asByteArray()) and <strong>structured access</strong> (jsonPath(), xmlPath()).</p>
</li>
</ul>
<hr />
<p>If you want, I can continue with a <strong>detailed deep dive into</strong> <code>ValidatableResponse</code> next, completing the RestAssured <strong>core interface chain</strong> from <code>RequestSpecification → RequestSender → Response → ValidatableResponse</code>.</p>
<h2 id="heading-1-overview-of-validatableresponse"><strong>1️⃣ Overview of</strong> <code>ValidatableResponse</code></h2>
<ul>
<li><p><strong>Package:</strong> <code>io.restassured.response</code></p>
</li>
<li><p><strong>Type:</strong> Interface</p>
</li>
<li><p><strong>Role:</strong><br />  <code>ValidatableResponse</code> represents a <strong>response after execution</strong> that can be <strong>validated/asserted</strong>.<br />  It is returned by <code>Response.then()</code> and supports <strong>method chaining</strong> for fluent assertions.</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">ValidatableResponse validatable = 
    given().when().get(<span class="hljs-string">"/users/2"</span>).then();
</code></pre>
<hr />
<h2 id="heading-2-key-methods-of-validatableresponse"><strong>2️⃣ Key Methods of ValidatableResponse</strong></h2>
<h3 id="heading-a-status-code-amp-line-validation"><strong>A. Status Code &amp; Line Validation</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>statusCode(int expected)</code></td><td>Validate exact HTTP status code.</td></tr>
<tr>
<td><code>statusLine(String expected)</code></td><td>Validate the full status line.</td></tr>
<tr>
<td><code>statusCode(Matcher&lt;Integer&gt; matcher)</code></td><td>Use Hamcrest matcher for status code validation.</td></tr>
</tbody>
</table>
</div><p><strong>Example:</strong></p>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">response.then().statusCode(<span class="hljs-number">200</span>).statusLine(<span class="hljs-string">"HTTP/1.1 200 OK"</span>);
</code></pre>
<hr />
<h3 id="heading-b-header-validation"><strong>B. Header Validation</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>header(String name, Matcher&lt;?&gt; matcher)</code></td><td>Validate a specific header with a matcher.</td></tr>
<tr>
<td><code>headers(String name1, Matcher&lt;?&gt; m1, String name2, Matcher&lt;?&gt; m2, ...)</code></td><td>Validate multiple headers at once.</td></tr>
<tr>
<td><code>contentType(String expected)</code></td><td>Validate Content-Type header.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-c-body-validation"><strong>C. Body Validation</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>body(String path, Matcher&lt;?&gt; matcher)</code></td><td>Validate JSON/XML response body using GPath.</td></tr>
<tr>
<td><code>body(Matcher&lt;?&gt; matcher)</code></td><td>Validate full body content.</td></tr>
<tr>
<td><code>body(String path, Object... expectedValues)</code></td><td>Validate body values at given path.</td></tr>
</tbody>
</table>
</div><p><strong>Example:</strong></p>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">response.then()
        .body(<span class="hljs-string">"data.id"</span>, equalTo(<span class="hljs-number">2</span>))
        .body(<span class="hljs-string">"data.first_name"</span>, equalTo(<span class="hljs-string">"Janet"</span>));
</code></pre>
<hr />
<h3 id="heading-d-cookie-validation"><strong>D. Cookie Validation</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>cookie(String name, Matcher&lt;?&gt; matcher)</code></td><td>Validate a specific cookie.</td></tr>
<tr>
<td><code>cookies(Matcher&lt;Map&lt;String, ?&gt;&gt; matcher)</code></td><td>Validate all cookies.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-e-logging"><strong>E. Logging</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>log().all()</code></td><td>Log status, headers, body.</td></tr>
<tr>
<td><code>log().headers()</code></td><td>Log only headers.</td></tr>
<tr>
<td><code>log().body()</code></td><td>Log only body.</td></tr>
<tr>
<td><code>log().ifValidationFails()</code></td><td>Log only if a validation fails.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-f-extracting-data"><strong>F. Extracting Data</strong></h3>
<ul>
<li><p><code>extract()</code> returns <code>ExtractableResponse&lt;Response&gt;</code> to extract data for later use.</p>
</li>
<li><p>Example:</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">String firstName = response.then()
                           .extract()
                           .path(<span class="hljs-string">"data.first_name"</span>);
</code></pre>
<hr />
<h3 id="heading-g-advanced-validation"><strong>G. Advanced Validation</strong></h3>
<ul>
<li>Supports <strong>Hamcrest matchers</strong> for complex assertions:</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">response.then()
        .body(<span class="hljs-string">"data.id"</span>, allOf(greaterThan(<span class="hljs-number">0</span>), lessThan(<span class="hljs-number">10</span>)))
        .body(<span class="hljs-string">"data.first_name"</span>, startsWith(<span class="hljs-string">"J"</span>));
</code></pre>
<ul>
<li>Supports <strong>multiple path assertions</strong> in a single call.</li>
</ul>
<hr />
<h2 id="heading-3-example-usage-3"><strong>3️⃣ Example Usage</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ValidatableResponseExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        given()
            .baseUri(<span class="hljs-string">"https://reqres.in"</span>)
            .basePath(<span class="hljs-string">"/api"</span>)
        .when()
            .get(<span class="hljs-string">"/users/2"</span>)
        .then()
            .statusCode(<span class="hljs-number">200</span>)
            .contentType(<span class="hljs-string">"application/json; charset=utf-8"</span>)
            .body(<span class="hljs-string">"data.id"</span>, equalTo(<span class="hljs-number">2</span>))
            .body(<span class="hljs-string">"data.first_name"</span>, equalTo(<span class="hljs-string">"Janet"</span>))
            .log().all();
    }
}
</code></pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><p><code>then()</code> → Converts <code>Response</code> into <code>ValidatableResponse</code>.</p>
</li>
<li><p><code>.statusCode()</code>, <code>.body()</code> → Validate status code and response body.</p>
</li>
<li><p><code>.log().all()</code> → Logs response details.</p>
</li>
</ul>
<hr />
<h2 id="heading-4-internal-flow-3"><strong>4️⃣ Internal Flow</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">RequestSpecification → RequestSender → Response → then() → ValidatableResponse
    └─ Provides assertion methods
    └─ Supports logging
    └─ Allows extraction <span class="hljs-keyword">for</span> further processing
</code></pre>
<hr />
<h2 id="heading-5-key-points-3"><strong>5️⃣ Key Points</strong></h2>
<ul>
<li><p><code>ValidatableResponse</code> is <strong>immutable</strong> and <strong>chainable</strong>.</p>
</li>
<li><p>Supports <strong>status, headers, body, cookies, and content-type validation</strong>.</p>
</li>
<li><p>Works seamlessly with <strong>Hamcrest matchers</strong> for flexible and readable assertions.</p>
</li>
<li><p><code>.extract()</code> allows you to <strong>reuse response data</strong> for subsequent requests or assertions.</p>
</li>
<li><p>Usually the <strong>last step in RestAssured chain</strong> for validation.</p>
</li>
</ul>
<hr />
<p>✅ After this, we have fully covered <strong>the RestAssured core chain</strong>:</p>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">RequestSpecification → RequestSender → Response → ValidatableResponse
</code></pre>
<h2 id="heading-1-overview-of-responsespecification"><strong>1️⃣ Overview of</strong> <code>ResponseSpecification</code></h2>
<ul>
<li><p><strong>Package:</strong> <code>io.restassured.specification</code></p>
</li>
<li><p><strong>Type:</strong> Interface</p>
</li>
<li><p><strong>Role:</strong><br />  <code>ResponseSpecification</code> defines <strong>reusable response expectations</strong>.<br />  Instead of writing the same assertions repeatedly, you can define a <strong>response specification</strong> and reuse it across multiple requests.</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">ResponseSpecification responseSpec = <span class="hljs-keyword">new</span> ResponseSpecBuilder()
                                        .expectStatusCode(<span class="hljs-number">200</span>)
                                        .expectContentType(<span class="hljs-string">"application/json"</span>)
                                        .build();
</code></pre>
<ul>
<li>Returned by <code>Response.then()</code> after applying a <code>ResponseSpecification</code>.</li>
</ul>
<hr />
<h2 id="heading-2-key-methods"><strong>2️⃣ Key Methods</strong></h2>
<h3 id="heading-a-status-amp-headers"><strong>A. Status &amp; Headers</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>expectStatusCode(int statusCode)</code></td><td>Expect a specific status code.</td></tr>
<tr>
<td><code>expectStatusLine(String statusLine)</code></td><td>Expect a full status line.</td></tr>
<tr>
<td><code>expectHeader(String name, Matcher&lt;?&gt; matcher)</code></td><td>Expect a header with a specific value.</td></tr>
<tr>
<td><code>expectHeaders(Map&lt;String, ?&gt; headers)</code></td><td>Expect multiple headers.</td></tr>
<tr>
<td><code>expectContentType(String contentType)</code></td><td>Expect Content-Type of response.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-b-body-validation"><strong>B. Body Validation</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>expectBody(String path, Matcher&lt;?&gt; matcher)</code></td><td>Expect JSON/XML path value using GPath.</td></tr>
<tr>
<td><code>expectBody(Matcher&lt;?&gt; matcher)</code></td><td>Expect full body content to match.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-c-cookies-1"><strong>C. Cookies</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>expectCookie(String name, Matcher&lt;?&gt; matcher)</code></td><td>Expect a specific cookie.</td></tr>
<tr>
<td><code>expectCookies(Map&lt;String, ?&gt; cookies)</code></td><td>Expect multiple cookies.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-d-miscellaneous"><strong>D. Miscellaneous</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>apply(Response response)</code></td><td>Apply the specification to a <code>Response</code>.</td></tr>
<tr>
<td><code>log()</code></td><td>Logging of response validation.</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-3-example-usage-4"><strong>3️⃣ Example Usage</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;
<span class="hljs-keyword">import</span> io.restassured.builder.ResponseSpecBuilder;
<span class="hljs-keyword">import</span> io.restassured.specification.ResponseSpecification;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ResponseSpecExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Define a reusable response specification</span>
        ResponseSpecification responseSpec = <span class="hljs-keyword">new</span> ResponseSpecBuilder()
            .expectStatusCode(<span class="hljs-number">200</span>)
            .expectContentType(<span class="hljs-string">"application/json; charset=utf-8"</span>)
            .expectBody(<span class="hljs-string">"data.id"</span>, equalTo(<span class="hljs-number">2</span>))
            .build();

        <span class="hljs-comment">// Use it in a request</span>
        given()
            .baseUri(<span class="hljs-string">"https://reqres.in"</span>)
            .basePath(<span class="hljs-string">"/api"</span>)
        .when()
            .get(<span class="hljs-string">"/users/2"</span>)
        .then()
            .spec(responseSpec)
            .log().all();
    }
}
</code></pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><p><code>ResponseSpecBuilder</code> → Builds a reusable <code>ResponseSpecification</code>.</p>
</li>
<li><p><code>.expectStatusCode()</code>, <code>.expectBody()</code> → Define assertions.</p>
</li>
<li><p><code>.spec(responseSpec)</code> → Applies specification to the current response.</p>
</li>
<li><p><code>.log().all()</code> → Logs the validated response.</p>
</li>
</ul>
<hr />
<h2 id="heading-4-benefits-of-responsespecification"><strong>4️⃣ Benefits of ResponseSpecification</strong></h2>
<ol>
<li><p><strong>Reusability:</strong> Define common expectations once, use in multiple tests.</p>
</li>
<li><p><strong>Readability:</strong> Keeps test code clean.</p>
</li>
<li><p><strong>Maintainability:</strong> Update the spec once, all tests using it reflect changes.</p>
</li>
<li><p><strong>Integration with ValidatableResponse:</strong> Applied via <code>.spec()</code> after <code>then()</code>.</p>
</li>
</ol>
<hr />
<h2 id="heading-5-flow-in-restassured-chain"><strong>5️⃣ Flow in RestAssured Chain</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">RequestSpecification → RequestSender → Response → then() → ValidatableResponse
                                                                │
                                                                └─ spec(ResponseSpecification)
</code></pre>
<ul>
<li><code>ResponseSpecification</code> is <strong>not mandatory</strong>, but it’s great for <strong>reusable validations</strong>.</li>
</ul>
<h2 id="heading-1-overview-of-responsespecification-1"><strong>1️⃣ Overview of</strong> <code>ResponseSpecification</code></h2>
<ul>
<li><p><strong>Package:</strong> <code>io.restassured.specification</code></p>
</li>
<li><p><strong>Type:</strong> Interface</p>
</li>
<li><p><strong>Role:</strong><br />  <code>ResponseSpecification</code> defines <strong>reusable response expectations</strong>.<br />  Instead of writing the same assertions repeatedly, you can define a <strong>response specification</strong> and reuse it across multiple requests.</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">ResponseSpecification responseSpec = <span class="hljs-keyword">new</span> ResponseSpecBuilder()
                                        .expectStatusCode(<span class="hljs-number">200</span>)
                                        .expectContentType(<span class="hljs-string">"application/json"</span>)
                                        .build();
</code></pre>
<ul>
<li>Returned by <code>Response.then()</code> after applying a <code>ResponseSpecification</code>.</li>
</ul>
<hr />
<h2 id="heading-2-key-methods-1"><strong>2️⃣ Key Methods</strong></h2>
<h3 id="heading-a-status-amp-headers-1"><strong>A. Status &amp; Headers</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>expectStatusCode(int statusCode)</code></td><td>Expect a specific status code.</td></tr>
<tr>
<td><code>expectStatusLine(String statusLine)</code></td><td>Expect a full status line.</td></tr>
<tr>
<td><code>expectHeader(String name, Matcher&lt;?&gt; matcher)</code></td><td>Expect a header with a specific value.</td></tr>
<tr>
<td><code>expectHeaders(Map&lt;String, ?&gt; headers)</code></td><td>Expect multiple headers.</td></tr>
<tr>
<td><code>expectContentType(String contentType)</code></td><td>Expect Content-Type of response.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-b-body-validation-1"><strong>B. Body Validation</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>expectBody(String path, Matcher&lt;?&gt; matcher)</code></td><td>Expect JSON/XML path value using GPath.</td></tr>
<tr>
<td><code>expectBody(Matcher&lt;?&gt; matcher)</code></td><td>Expect full body content to match.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-c-cookies-2"><strong>C. Cookies</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>expectCookie(String name, Matcher&lt;?&gt; matcher)</code></td><td>Expect a specific cookie.</td></tr>
<tr>
<td><code>expectCookies(Map&lt;String, ?&gt; cookies)</code></td><td>Expect multiple cookies.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-d-miscellaneous-1"><strong>D. Miscellaneous</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>apply(Response response)</code></td><td>Apply the specification to a <code>Response</code>.</td></tr>
<tr>
<td><code>log()</code></td><td>Logging of response validation.</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-3-example-usage-5"><strong>3️⃣ Example Usage</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;
<span class="hljs-keyword">import</span> io.restassured.builder.ResponseSpecBuilder;
<span class="hljs-keyword">import</span> io.restassured.specification.ResponseSpecification;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ResponseSpecExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Define a reusable response specification</span>
        ResponseSpecification responseSpec = <span class="hljs-keyword">new</span> ResponseSpecBuilder()
            .expectStatusCode(<span class="hljs-number">200</span>)
            .expectContentType(<span class="hljs-string">"application/json; charset=utf-8"</span>)
            .expectBody(<span class="hljs-string">"data.id"</span>, equalTo(<span class="hljs-number">2</span>))
            .build();

        <span class="hljs-comment">// Use it in a request</span>
        given()
            .baseUri(<span class="hljs-string">"https://reqres.in"</span>)
            .basePath(<span class="hljs-string">"/api"</span>)
        .when()
            .get(<span class="hljs-string">"/users/2"</span>)
        .then()
            .spec(responseSpec)
            .log().all();
    }
}
</code></pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><p><code>ResponseSpecBuilder</code> → Builds a reusable <code>ResponseSpecification</code>.</p>
</li>
<li><p><code>.expectStatusCode()</code>, <code>.expectBody()</code> → Define assertions.</p>
</li>
<li><p><code>.spec(responseSpec)</code> → Applies specification to the current response.</p>
</li>
<li><p><code>.log().all()</code> → Logs the validated response.</p>
</li>
</ul>
<hr />
<h2 id="heading-4-benefits-of-responsespecification-1"><strong>4️⃣ Benefits of ResponseSpecification</strong></h2>
<ol>
<li><p><strong>Reusability:</strong> Define common expectations once, use in multiple tests.</p>
</li>
<li><p><strong>Readability:</strong> Keeps test code clean.</p>
</li>
<li><p><strong>Maintainability:</strong> Update the spec once, all tests using it reflect changes.</p>
</li>
<li><p><strong>Integration with ValidatableResponse:</strong> Applied via <code>.spec()</code> after <code>then()</code>.</p>
</li>
</ol>
<hr />
<h2 id="heading-5-flow-in-restassured-chain-1"><strong>5️⃣ Flow in RestAssured Chain</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">RequestSpecification → RequestSender → Response → then() → ValidatableResponse
                                                                │
                                                                └─ spec(ResponseSpecification)
</code></pre>
<ul>
<li><code>ResponseSpecification</code> is <strong>not mandatory</strong>, but it’s great for <strong>reusable validations</strong>.</li>
</ul>
<h2 id="heading-1-overview-of-responsespecbuilder"><strong>1️⃣ Overview of</strong> <code>ResponseSpecBuilder</code></h2>
<ul>
<li><p><strong>Package:</strong> <code>io.restassured.builder</code></p>
</li>
<li><p><strong>Type:</strong> Class</p>
</li>
<li><p><strong>Role:</strong><br />  <code>ResponseSpecBuilder</code> helps you <strong>create reusable</strong> <code>ResponseSpecification</code> objects.<br />  Instead of writing the same assertions for multiple tests, you define them once with a builder.</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">ResponseSpecification responseSpec = <span class="hljs-keyword">new</span> ResponseSpecBuilder()
                                        .expectStatusCode(<span class="hljs-number">200</span>)
                                        .expectContentType(<span class="hljs-string">"application/json"</span>)
                                        .build();
</code></pre>
<ul>
<li><code>build()</code> → Returns a <code>ResponseSpecification</code> object.</li>
</ul>
<hr />
<h2 id="heading-2-key-methods-of-responsespecbuilder"><strong>2️⃣ Key Methods of ResponseSpecBuilder</strong></h2>
<h3 id="heading-a-status-and-line-1"><strong>A. Status and Line</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>expectStatusCode(int statusCode)</code></td><td>Expect a specific HTTP status code.</td></tr>
<tr>
<td><code>expectStatusLine(String statusLine)</code></td><td>Expect a full HTTP status line.</td></tr>
<tr>
<td><code>expectStatusCode(Matcher&lt;Integer&gt; matcher)</code></td><td>Use Hamcrest matcher for status code.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-b-headers-1"><strong>B. Headers</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>expectHeader(String name, Matcher&lt;?&gt; matcher)</code></td><td>Expect a specific header value.</td></tr>
<tr>
<td><code>expectHeaders(Map&lt;String, ?&gt; headers)</code></td><td>Expect multiple headers at once.</td></tr>
<tr>
<td><code>expectContentType(String contentType)</code></td><td>Expect a specific Content-Type header.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-c-body-validation-1"><strong>C. Body Validation</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>expectBody(String path, Matcher&lt;?&gt; matcher)</code></td><td>Validate JSON/XML response body at a given path using GPath.</td></tr>
<tr>
<td><code>expectBody(Matcher&lt;?&gt; matcher)</code></td><td>Validate entire response body.</td></tr>
<tr>
<td><code>expectBody(String path, Object... expectedValues)</code></td><td>Validate body values for given path.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-d-cookies"><strong>D. Cookies</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>expectCookie(String name, Matcher&lt;?&gt; matcher)</code></td><td>Expect a specific cookie.</td></tr>
<tr>
<td><code>expectCookies(Map&lt;String, ?&gt; cookies)</code></td><td>Expect multiple cookies.</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-e-logging-1"><strong>E. Logging</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>log()</code></td><td>Enable logging for response validation (optional).</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-f-build"><strong>F. Build</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>build()</code></td><td>Builds the <code>ResponseSpecification</code> object.</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-3-example-usage-6"><strong>3️⃣ Example Usage</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.hamcrest.Matchers.*;
<span class="hljs-keyword">import</span> io.restassured.builder.ResponseSpecBuilder;
<span class="hljs-keyword">import</span> io.restassured.specification.ResponseSpecification;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ResponseSpecBuilderExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Build reusable response specification</span>
        ResponseSpecification responseSpec = <span class="hljs-keyword">new</span> ResponseSpecBuilder()
            .expectStatusCode(<span class="hljs-number">200</span>)
            .expectContentType(<span class="hljs-string">"application/json; charset=utf-8"</span>)
            .expectBody(<span class="hljs-string">"data.id"</span>, equalTo(<span class="hljs-number">2</span>))
            .build();

        <span class="hljs-comment">// Apply the response spec in a request</span>
        given()
            .baseUri(<span class="hljs-string">"https://reqres.in"</span>)
            .basePath(<span class="hljs-string">"/api"</span>)
        .when()
            .get(<span class="hljs-string">"/users/2"</span>)
        .then()
            .spec(responseSpec)   <span class="hljs-comment">// Apply reusable spec</span>
            .log().all();
    }
}
</code></pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><p><code>ResponseSpecBuilder</code> → Define common response expectations once.</p>
</li>
<li><p><code>.build()</code> → Returns <code>ResponseSpecification</code>.</p>
</li>
<li><p><code>.spec(responseSpec)</code> → Apply the specification to a response.</p>
</li>
</ul>
<hr />
<h2 id="heading-4-benefits"><strong>4️⃣ Benefits</strong></h2>
<ol>
<li><p><strong>Reusability:</strong> Define common response validations once and reuse.</p>
</li>
<li><p><strong>Readability:</strong> Keeps test code clean and avoids repeated assertions.</p>
</li>
<li><p><strong>Maintainability:</strong> Update the spec once, all tests reflect changes.</p>
</li>
<li><p><strong>Supports Method Chaining:</strong> Fluent API for building complex validation rules.</p>
</li>
</ol>
<hr />
<p>✅ After this, we have covered all <strong>builders in RestAssured</strong>:</p>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">RequestSpecBuilder → RequestSpecification → RequestSender → Response → ValidatableResponse → ResponseS
</code></pre>
<h2 id="heading-1-overview-of-authenticationscheme"><strong>1️⃣ Overview of</strong> <code>AuthenticationScheme</code></h2>
<ul>
<li><p><strong>Package:</strong> <code>io.restassured.authentication</code></p>
</li>
<li><p><strong>Type:</strong> Interface</p>
</li>
<li><p><strong>Role:</strong><br />  <code>AuthenticationScheme</code> is the <strong>base interface</strong> for all authentication types in RestAssured.<br />  It allows <strong>RequestSpecification</strong> to set authentication when sending requests.</p>
</li>
<li><p>Implemented by classes like:</p>
<ul>
<li><p><code>BasicAuthScheme</code> → Basic Authentication</p>
</li>
<li><p><code>DigestAuthScheme</code> → Digest Authentication</p>
</li>
<li><p><code>OAuth2Scheme</code> → OAuth2 Authentication</p>
</li>
<li><p><code>PreemptiveBasicAuthScheme</code> → Preemptive Basic Auth</p>
</li>
</ul>
</li>
<li><p>Typically used via <code>RequestSpecification.auth()</code>:</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">given().auth().basic(<span class="hljs-string">"username"</span>, <span class="hljs-string">"password"</span>);
</code></pre>
<p>Internally, <code>basic()</code> creates a <code>BasicAuthScheme</code> object implementing <code>AuthenticationScheme</code>.</p>
<hr />
<h2 id="heading-2-key-methods-of-authenticationscheme"><strong>2️⃣ Key Methods of AuthenticationScheme</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>void authenticate(RequestSpecification requestSpec)</code></td><td>Applies the authentication to the request.</td></tr>
<tr>
<td><code>String getUsername()</code></td><td>Returns username (for Basic/Digest).</td></tr>
<tr>
<td><code>String getPassword()</code></td><td>Returns password (for Basic/Digest).</td></tr>
<tr>
<td><code>String getAccessToken()</code></td><td>Returns access token (for OAuth2).</td></tr>
</tbody>
</table>
</div><blockquote>
<p><strong><em>Note: Exact methods depend on the implementing class. The interface ensures any authentication scheme can be applied to a request.</em></strong></p>
</blockquote>
<hr />
<h2 id="heading-3-common-implementations"><strong>3️⃣ Common Implementations</strong></h2>
<h3 id="heading-a-basicauthscheme"><strong>A. BasicAuthScheme</strong></h3>
<ul>
<li><p>Implements <code>AuthenticationScheme</code>.</p>
</li>
<li><p>Adds <strong>Basic HTTP authentication header</strong>.</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">given().auth().basic(<span class="hljs-string">"user"</span>, <span class="hljs-string">"pass"</span>);
</code></pre>
<h3 id="heading-b-digestauthscheme"><strong>B. DigestAuthScheme</strong></h3>
<ul>
<li><p>Implements <code>AuthenticationScheme</code>.</p>
</li>
<li><p>Handles <strong>Digest authentication</strong> challenge-response.</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">given().auth().digest(<span class="hljs-string">"user"</span>, <span class="hljs-string">"pass"</span>);
</code></pre>
<h3 id="heading-c-oauth2scheme"><strong>C. OAuth2Scheme</strong></h3>
<ul>
<li><p>Implements <code>AuthenticationScheme</code>.</p>
</li>
<li><p>Adds <strong>Bearer token</strong> to <code>Authorization</code> header.</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">given().auth().oauth2(<span class="hljs-string">"token"</span>);
</code></pre>
<h3 id="heading-d-preemptivebasicauthscheme"><strong>D. PreemptiveBasicAuthScheme</strong></h3>
<ul>
<li><p>Implements <code>AuthenticationScheme</code>.</p>
</li>
<li><p>Sends <strong>Basic Auth header immediately</strong> without waiting for server challenge.</p>
</li>
</ul>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">given().auth().preemptive().basic(<span class="hljs-string">"user"</span>, <span class="hljs-string">"pass"</span>);
</code></pre>
<hr />
<h2 id="heading-4-usage-example"><strong>4️⃣ Usage Example</strong></h2>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AuthenticationExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        given()
            .baseUri(<span class="hljs-string">"https://reqres.in"</span>)
            .basePath(<span class="hljs-string">"/api"</span>)
            .auth().basic(<span class="hljs-string">"user"</span>, <span class="hljs-string">"pass"</span>)   <span class="hljs-comment">// BasicAuthScheme applied</span>
        .when()
            .get(<span class="hljs-string">"/users/2"</span>)
        .then()
            .statusCode(<span class="hljs-number">200</span>)
            .log().all();
    }
}
</code></pre>
<p><strong>Explanation:</strong></p>
<ol>
<li><p><code>auth().basic()</code> → Creates a <code>BasicAuthScheme</code>.</p>
</li>
<li><p><code>AuthenticationScheme.authenticate()</code> → Internally adds header to the request.</p>
</li>
<li><p>Request is executed with authentication.</p>
</li>
</ol>
<hr />
<h2 id="heading-5-key-points-4"><strong>5️⃣ Key Points</strong></h2>
<ul>
<li><p><code>AuthenticationScheme</code> is <strong>an interface</strong>, so new authentication types can be added.</p>
</li>
<li><p>Used by <strong>RequestSpecification</strong> to apply authentication before sending requests.</p>
</li>
<li><p>Supports multiple types:</p>
<ul>
<li><p>Basic</p>
</li>
<li><p>Digest</p>
</li>
<li><p>OAuth1/OAuth2</p>
</li>
<li><p>Preemptive authentication</p>
</li>
</ul>
</li>
<li><p>Works seamlessly with <strong>RequestSpecBuilder</strong> or <strong>RequestSpecification</strong> for reusable authentication.</p>
</li>
</ul>
<hr />
<p>If you want, I can now create a <strong>complete UML class/interface diagram for RestAssured</strong> showing:</p>
<p><strong>Copy</strong></p>
<pre><code class="lang-java">RestAssured → RequestSpecification → RequestSender → Response → ValidatableResponse → ResponseSpecification
+ RequestSpecBuilder, ResponseSpecBuilder
+ AuthenticationScheme → Basic/Digest/OAuth
+ Filters &amp; Logging
</code></pre>
<h3 id="heading-sample-test-using-method-chaining">Sample Test Using Method chaining.</h3>
<h3 id="heading-before-static-import">Before static import»»»</h3>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> sampleTest;

<span class="hljs-keyword">import</span> org.testng.annotations.Test;

<span class="hljs-keyword">import</span> io.restassured.RestAssured;
<span class="hljs-keyword">import</span> io.restassured.response.Response;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SampleTsetUsingMethodChaning</span> </span>{
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getAllEmployeesAvailable</span><span class="hljs-params">()</span> </span>{

    Response resp = RestAssured.get(<span class="hljs-string">"http://49.249.28.218:8091/all-employees"</span>);
    resp.prettyPeek();
    }

}
</code></pre>
<p>Here we use the class name to use the <strong>get()</strong> method.</p>
<h3 id="heading-after-static-import">After static import»»»</h3>
<p><strong>Copy</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> sampleTest;

<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> io.restassured.RestAssured.*;

<span class="hljs-keyword">import</span> org.testng.annotations.Test;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SampleTsetUsingMethodChaning2</span> </span>{
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getAllEmployeesAvailable</span><span class="hljs-params">()</span> </span>{

    get(<span class="hljs-string">"http://49.249.28.218:8091/all-employees"</span>)
    .prettyPeek();
    }

}
</code></pre>
<p>Here we not using the class name as reference ,this is the magic of <strong>static</strong> import.</p>
<p>ok</p>
]]></content:encoded></item></channel></rss>