API/SOAP UI/REST

🔹 Topic 1: What is an API? – Explained with Real-Life Nepali Examples

API भनेको के हो? दैनिक जीवनबाट सजिलो उदाहरणसहितको व्याख्या


📖 Introduction

API को full form हो — Application Programming Interface
तर डराउनु पर्दैन, यसको मतलब के भने तपाईंको एउटा application (app) ले अर्को application सँग डाटा शेयर गर्ने तरिका हो — एकदमै मिलेको भाषा जस्तै।

🔁 “API भनेको दुई software बीचको कुराकानी गर्ने तरिका हो।”


🧱 Technical Meaning in Simple Words

  • एक software ले अर्को software सँग के काम गर भनिन्छ — त्यो काम API ले गर्छ।
  • API ले “Request पठाउँछ” र “Response ल्याउँछ” — जस्तै तपाईंले restaurant मा waiter पठाउनु भयो।

🍽️ Real-Life Nepali Analogy: Hotel र Waiter

ElementAPI Example Equivalent
तपाईं (User)Mobile App/Web Browser
WaiterAPI
KitchenBackend Server
Menu र OrderAPI Request (GET, POST)
खानाAPI Response (JSON/XML)

जस्तै तपाईंले waiter लाई menu बाट खाना order गर्नुभयो, waiter ले kitchen मा त्यो request पुर्‍यायो र तपाईंलाई plate मा ल्याएर दियो — यही हो API


📱 Daily Life API Examples (Nepali Context)

ExampleAPI Behind It
Esewa बाट balance check गर्नुEsewa’s REST API
Foodmandu बाट momo order गर्नुOrder API + Payment API
HamroPatro मा weather हेर्नुOpenWeather API
Khalti मा mobile recharge गर्नुRecharge API
Bank को mobile app login गर्नुAuth API (OAuth/JWT)

🧠 What Happens Technically?

  1. App बाट request जान्छ:

http

CopyEdit

GET https://example.com/api/v1/momo/menu

  1. Server ले JSON format मा reply गर्छ:

json

CopyEdit

{

  “item”: “Buff Momo”,

  “price”: “120”

}

  1. UI मा data देखिन्छ।

🔍 Types of API

TypeDescription
REST APIURL-based, JSON/XML, most common
SOAP APIXML-based, strict format, used in legacy systems
GraphQL APIQuery-specific, returns only needed data

✅ Why QA/Testers Should Learn API

ReasonWhy It Matters
🔍 Backend test गर्न सकिन्छबिना UI, response validate गर्न सकिन्छ
🧪 Faster defect detectionLogic level मा error तुरुन्त पत्ता लाग्छ
🔁 Automation संभव हुन्छPostman, RestAssured बाट quick regression

📌 Conclusion: API is everywhere — मोबाइल app, browser, payment, weather, everything runs through it. Tester को हैसियतले तपाईंले UI बाहेकको world बुझ्न API बाट सुरु गर्नुपर्छ।

🔹 Topic 2: REST vs SOAP – What’s the Difference with Practical Use?

REST र SOAP API बीच के फरक छ? Real-life प्रयोगका साथ बुझौँ।


📖 Introduction

API testing गर्ने बेला सबैभन्दा धेरै सोधिने प्रश्न हो —
“SOAP API हो कि REST API?”

दुवै communication protocol हुन् जसले client-server बीच डेटा पठाउने काम गर्छ, तर तिनीहरूको structure, flexibility, र प्रयोगको तरिका फरक हुन्छ।

🔍 “REST सरल र modern हो, SOAP strict र structured हो।”


🧪 Real-Life Analogy (Nepali Context)

ScenarioREST APISOAP API
चिया स्टलमा जानु – menu हेरेर order गर्नु
होटलमा proper form भरेर खाना order गर्नु

➡️ REST सजिलो र fast interaction हो, SOAP formal process हो।


🧠 Key Differences: REST vs SOAP

CriteriaREST APISOAP API
🔤 Protocol FormatHTTP methods (GET, POST, PUT, DELETE)Only XML via HTTP, SMTP, or TCP
🧾 Data FormatJSON (also supports XML)Strictly XML
⚙️ SimplicityEasy to implement, lightweightComplex, heavyweight
🔐 SecurityBasic auth, OAuthBuilt-in WS-Security (enterprise level)
🧪 Used in TestingWeb apps, mobile APIsBanking, finance, insurance systems
📚 SpecificationNo official standard (open design)WSDL-based (Web Service Definition Language)
⚡ SpeedFasterSlower

📦 Practical QA Examples

🔸 REST API Testing Example:

http

CopyEdit

GET https://api.foodmandu.com/v1/items

Response:

json

CopyEdit

{

  “item”: “Chicken Momo”,

  “price”: 150

}

✅ Simple, readable, faster.


🔸 SOAP API Testing Example (XML Request):

xml

CopyEdit

<soapenv:Envelope>

  <soapenv:Body>

    <getWeather>

      <city>Kathmandu</city>

    </getWeather>

  </soapenv:Body>

</soapenv:Envelope>

Response: full XML format with nested tags.

✅ Structured, verbose, mostly used in legacy systems.


⚙️ Tools Used for Testing

PurposeREST APISOAP API
Manual testingPostman, InsomniaSOAP UI
AutomationRestAssured, KarateApache CXF, JAX-WS
Contract fileOpenAPI (Swagger)WSDL (XML-based)

🧪 When to Use What?

ScenarioUse RESTUse SOAP
Modern Web/Mobile App Testing
Strict enterprise rule required
Fast JSON-based API response
Working with legacy government/banking APIs

📌 Conclusion

  • REST: Lightweight, fast, user-friendly → Ideal for web/mobile testing.
  • SOAP: Secure, structured, standard-heavy → Best for enterprise/financial APIs.

🤖 As a QA tester, knowing the difference helps you test smartly — depending on the system you’re working with.

🔹 Topic 3: Understanding API Methods – GET, POST, PUT, DELETE with Nepali Examples

CRUD को आधारमा API method हरू बुझौँ — Nepali प्रयोग केसहरूसहित


📖 Introduction

REST API मा हामी प्राय: चार मुख्य HTTP methods प्रयोग गर्छौं:
GET, POST, PUT, र DELETE

यी method हरूले backend server सँग कुन काम गर्नुपर्छ भन्ने कुरा बताउँछ।
यिनलाई हामी database operation को CRUD (Create, Read, Update, Delete) संग पनि जोड्न सक्छौँ।

🔄 “API methods भनेको client-server बीचको काम गर्ने instruction हो।”


🧱 CRUD vs HTTP Methods

CRUD OperationHTTP MethodWhat It Does
🔨 CreatePOSTनयाँ data बनाउँछ
📖 ReadGETData पढ्छ / देखाउँछ
✏️ UpdatePUTपुरानो data update गर्छ
DeleteDELETEData हटाउँछ

🧪 Nepali Real-Life API Use Cases

1️⃣ GET – पढ्ने काम

काम: Existing momo menu list हेर्ने

http

CopyEdit

GET /api/momo/menu

📦 Response:

json

CopyEdit

[

  { “item”: “Chicken Momo”, “price”: 150 },

  { “item”: “Buff Momo”, “price”: 130 }

]

✅ Safe method – केही change हुँदैन, data मात्र ल्याउँछ।


2️⃣ POST – नयाँ बनाउने काम

काम: User ले feedback दिनु

http

CopyEdit

POST /api/feedback

📨 Request body:

json

CopyEdit

{

  “name”: “Ramesh”,

  “message”: “Great momo!”

}

✅ Server मा नयाँ feedback create हुन्छ।


3️⃣ PUT – पुरानो update गर्ने काम

काम: Existing order को item update गर्नु

http

CopyEdit

PUT /api/orders/123

📨 Request body:

json

CopyEdit

{

  “item”: “Veg Momo”,

  “quantity”: 2

}

✅ Order ID 123 को item change हुन्छ।


4️⃣ DELETE – हटाउने काम

काम: User ले आफ्नो account हटाउने

http

CopyEdit

DELETE /api/users/45

✅ ID 45 भएको user permanently हटाइन्छ।


🔧 Summary Table

MethodCRUD TaskIdempotent?Requires Body?Common Tool for QA
GETRead✅ Yes❌ NoPostman, RestAssured
POSTCreate❌ No✅ YesPostman, Swagger UI
PUTUpdate✅ Yes✅ YesPostman, RestAssured
DELETEDelete✅ Yes✅/❌Postman, SoapUI

🎯 Tester Tips

  • GET test गर्दा: Status code 200, JSON structure check गर्नुहोस्
  • POST test गर्दा: Response मा नया ID create भएको check गर्नुहोस्
  • PUT test गर्दा: Old value replace भयो कि verify गर्नुहोस्
  • DELETE test गर्दा: दुबारा GET गर्दा data आउँदैन भन्ने check गर्नुहोस्

📌 Conclusion: GET, POST, PUT, DELETE को ज्ञान भएपछि तपाईंले CRUD level बाट API test गर्न सिक्नुहुन्छ — यो API QA को foundation हो।

🔹 Topic 4: API Status Codes – What Does 200, 404, 500 Mean?

HTTP Status Code के हो? 100 देखि 599 सम्मको meaning र QA परिप्रेक्ष्यमा उपयोग


📖 Introduction

जब तपाईंले API call गर्नुहुन्छ (GET, POST, आदि), server ले एक status code फर्काउँछ — जसले success, error, redirect आदि को जानकारी दिन्छ।

⚙️ “Status code भन्नाले server ले तपाईंको request स्वीकार गर्‍यो कि होइन भन्ने संकेत दिन्छ।”


🔢 HTTP Status Code Ranges (100–599)

Code RangeCategoryMeaning
100–199InformationalRequest received, processing continues
200–299SuccessEverything OK ✅
300–399RedirectionClient must take additional action
400–499Client ErrorMistake from user/request side ❌
500–599Server ErrorServer failed to handle valid request 🚨

✅ Most Common Status Codes (Explained with Nepali Use Case)

CodeMeaningDescription (Nepali Context)
200OKSuccess response (e.g., momo menu fetched)
201CreatedNew user/feedback successfully created
204No ContentRequest OK, but no data returned (e.g., delete success)
301Moved PermanentlyOld API URL permanently redirected
302Found / RedirectTemporary redirect (login → dashboard)
400Bad RequestMalformed JSON / Missing field
401UnauthorizedAPI token/login required but missing
403ForbiddenValid login, but no permission (e.g., QA can’t delete admin)
404Not FoundURL गलत या resource छैन
409ConflictDuplicate entry or data mismatch
415Unsupported MediaContent-Type not accepted (e.g., expecting JSON, got text)
422Unprocessable EntityValid JSON but semantic error (e.g., negative price)
500Internal Server ErrorServer crashed or unhandled exception
502Bad GatewayUpstream server (like database) failed
503Service UnavailableServer busy or down for maintenance

🧪 How Testers Use Status Codes

Test ScenarioExpected Status Code
Valid login credentials200 OK
Invalid login401 Unauthorized
Valid POST with full data201 Created
Invalid JSON format400 Bad Request
Deleting valid object204 No Content
Accessing missing endpoint404 Not Found
Sending invalid content type415 Unsupported
Duplicate record submission409 Conflict

🧠 Bonus Tip for Testers

In Postman or RestAssured, always verify:

  • Status code
  • Response body
  • Header fields (like Content-Type)
  • Time taken

Example (Postman):

lua

CopyEdit

pm.test(“Status code is 200”, function () {

  pm.response.to.have.status(200);

});


📌 Conclusion

Status code testing is one of the most important validation layers for API QA.
By understanding what 200, 404, 500 or even 422 means — you can easily detect backend logic issues, access problems, or malformed request handling.


🔹 Topic 5: Understanding API Headers, Body, Params, and Authentication

API को Header, Body, Params र Auth भनेको के हो? Testing मा कसरी बुझ्ने?


📖 Introduction

जब तपाईं API call गर्नुहुन्छ, त्यो request को form structure हुन्छ — जसमा headers, body, parameters, र authentication जानकारी मिसिएको हुन्छ।

📦 “API भनेको केवल URL मात्र होइन — त्यसको साथमा आउँछ structure, data, र security पनि।”


🔑 1. API Headers

Header ले API को meta-information दिन्छ: content type, auth token, version आदि।

🔸 Example:

http

CopyEdit

Content-Type: application/json

Authorization: Bearer eyJhbGciOiJIUzI1…

🧪 Why Important for QA?

  • Without proper headers, API fails
  • Content-type गलत भयो भने response 415 आउन सक्छ
  • Authorization token बिना 401 error आउँछ

📨 2. API Body

Body भनेको request को main payload हो – जस्तो कि user data, form info, या JSON object।

🔸 Example (POST):

json

CopyEdit

{

  “username”: “lok123”,

  “password”: “testpass”

}

🧪 Tester Tips:

  • Always test for missing fields, empty values, and special characters
  • Validate that API accepts correct format and rejects invalid ones

🔍 3. Query Parameters (params)

Query parameter भनेको URL मा नै attach हुने dynamic key/value pair हो।

🔸 Example:

http

CopyEdit

GET /api/products?category=electronics&sort=price

  • यहाँ category र sort भनेको parameter हो

🧪 QA Scenario:

  • Check if API filters properly
  • Try sending unexpected values like ?category=<> or blank ?sort=

🧾 4. Path Parameters (path variables)

Path parameters भनेको dynamic parts हो जुन URL को structure भित्र change हुन्छ।

🔸 Example:

http

CopyEdit

GET /api/user/45

➡️ Here, 45 is user ID (path variable)


🔐 5. API Authentication

Authentication ले ensure गर्छ कि तपाईंको request authorized छ कि छैन।

🧰 Types:

TypeDescription
🧾 API KeyStatic key passed in header or param
🔐 Bearer TokenJWT or OAuth2 token (usually via login API)
🛡️ Basic AuthUsername-password base64 encoded
🔒 OAuth2Secure token flow (used in modern systems)

🧪 What to Test:

  • Valid & invalid tokens
  • Expired token behavior
  • Unauthorized access to protected endpoints

📦 Complete Example

POST Request to Create New User:

http

CopyEdit

POST /api/user

Headers:

  Content-Type: application/json

  Authorization: Bearer <token>

Body:

{

  “name”: “Rita”,

  “email”: “rita@test.com”

}

➡️ Response: 201 Created if successful, else 400/401/409 based on validation


🧠 QA Checklist

ItemWhat to Check
HeadersContent-Type, Auth token, Accept version
BodyRequired fields, formats, edge cases
ParamsFiltering, sorting, null handling
AuthenticationToken validity, scope, expiry
ResponseStatus code + message consistency

📌 Conclusion

API testing केवल status code हेर्ने काम होइन — testers लाई headers, body, params, र auth structure राम्रोसँग बुझ्न जरुरी छ।
यो understanding ले तपाईंको API test case लाई secure, stable, र smart बनाउँछ।

🔹 Topic 6: API Testing with Postman – Step-by-Step for Beginners

Postman बाट API Testing कसरी गर्ने? सुरुवातदेखि step-by-step guide


📖 Introduction

Postman एक powerful and beginner-friendly tool हो जसले testers लाई API request बनाउने, test चलाउने, र result verify गर्ने सजिलो interface दिन्छ।
कोड लेख्न जरुरी छैन — सिर्फ request configure गरेर test run गर्न सकिन्छ।

🧪 “Postman भनेको QA को लागि API testing को playground हो।”


🧰 Step-by-Step: Postman मा Testing कसरी गर्ने?


🔸 Step 1: Install Postman

👉 Download from https://www.postman.com/downloads/
✅ Free version बाट सुरु गर्न सकिन्छ।


🔸 Step 2: Create New Request

  1. Postman खोल्नुहोस्
  2. Click + New Tab
  3. Select method → GET, POST, etc.
  4. Enter API URL (e.g. https://api.example.com/user/45)

🔸 Step 3: Add Headers (if needed)

http

CopyEdit

Content-Type: application/json

Authorization: Bearer <token>

✅ बिना header, केही API ले काम गर्दैन।


🔸 Step 4: Add Request Body (for POST/PUT)

Click Body tab → select raw → choose JSON

json

CopyEdit

{

  “username”: “lok123”,

  “password”: “test123”

}


🔸 Step 5: Click “Send” and Observe Response

👉 Postman ले status code (200, 201, 404) र JSON/XML body देखाउँछ
✅ Logs हेरेर data validate गर्नुहोस्


🧪 Step 6: Write Test Scripts (Optional)

Go to Tests tab and add:

javascript

CopyEdit

pm.test(“Status code is 200”, function () {

  pm.response.to.have.status(200);

});

✅ यसले response code check गर्छ — failed/pass देखाउँछ।


📦 Example Test Cases to Try in Postman

Test CaseMethodExpected Code
Valid loginPOST200
Invalid email/passwordPOST401
Get list of usersGET200
Delete existing userDELETE204
Send invalid JSONPOST400

🎯 Why Postman is Best for QA Beginners

FeatureBenefit
📋 No coding neededEasy for manual testers
🧪 Pre-built testingScript tab for quick test
🔁 Reusable requestsSave collections & environments
📈 Visual logsEasy to understand response
🚀 Fast feedbackImmediate validation after Send

🧠 Bonus: Collections and Environments

  • Collections: Save and organize multiple API requests
  • Environments: Store variable like {{base_url}}, {{auth_token}}

📌 Conclusion

Postman is one of the best tools for learning, running, and automating API tests — without needing a complex setup.
Once you’re comfortable, you can integrate it with Newman (CLI) or export test suites into your CI pipeline.

🌱 “Mastering Postman is the first confident step in becoming a strong API tester.”


🔹 Topic 7: API Automation Using RestAssured (Java)

Java को RestAssured Framework प्रयोग गरेर API automation कसरी गर्ने? Beginner देखि Advance Guide


📖 Introduction

RestAssured एक widely-used Java-based library हो जसले testers लाई API endpoints verify गर्न, status code check गर्न, response validate गर्न, र test automation pipeline मा राख्न allow गर्छ।

🤖 “RestAssured + Java = Code-level API testing power for automation-focused QA testers.”


🛠️ Prerequisites

  • Java 8 or higher
  • Maven installed
  • IDE (Eclipse / IntelliJ)
  • Basic knowledge of HTTP methods (GET, POST, etc.)

📦 Step-by-Step: RestAssured Setup


🔸 Step 1: Create Maven Project

Add the following to your pom.xml:

xml

CopyEdit

<dependency>

  <groupId>io.rest-assured</groupId>

  <artifactId>rest-assured</artifactId>

  <version>5.4.0</version>

  <scope>test</scope>

</dependency>

(Optional for JSON parsing):

xml

CopyEdit

<dependency>

  <groupId>org.hamcrest</groupId>

  <artifactId>hamcrest</artifactId>

  <version>2.2</version>

</dependency>


🔸 Step 2: Write Basic GET Test

java

CopyEdit

import io.restassured.RestAssured;

import org.testng.annotations.Test;

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;

public class GetUserTest {

    @Test

    public void getUserInfo() {

        given()

            .baseUri(“https://reqres.in”)

        .when()

            .get(“/api/users/2”)

        .then()

            .statusCode(200)

            .body(“data.first_name”, equalTo(“Janet”));

    }

}

✅ statusCode(200) check गर्छ
✅ body() validator ले JSON response को key-value match confirm गर्छ


🧪 Other API Methods in RestAssured

🔹 POST Example:

java

CopyEdit

@Test

public void createUser() {

    given()

        .baseUri(“https://reqres.in”)

        .header(“Content-Type”, “application/json”)

        .body(“{ \”name\”: \”lok\”, \”job\”: \”tester\” }”)

    .when()

        .post(“/api/users”)

    .then()

        .statusCode(201)

        .body(“name”, equalTo(“lok”));

}


🔹 PUT Example:

java

CopyEdit

@Test

public void updateUser() {

    given()

        .baseUri(“https://reqres.in”)

        .header(“Content-Type”, “application/json”)

        .body(“{ \”name\”: \”lok\”, \”job\”: \”senior tester\” }”)

    .when()

        .put(“/api/users/2”)

    .then()

        .statusCode(200);

}


🔹 DELETE Example:

java

CopyEdit

@Test

public void deleteUser() {

    given()

        .baseUri(“https://reqres.in”)

    .when()

        .delete(“/api/users/2”)

    .then()

        .statusCode(204);

}


🎯 Why RestAssured for QA Testers?

FeatureBenefit
✅ Full Java supportReusable logic in frameworks
🧪 Built for testersTestNG/JUnit integration easy
🔍 Deep JSON/XML validationHamcrest + response parsing
⚙️ CI-readyEasy to plug into Jenkins, GitHub Actions

🧠 Best Practices

  • Keep base URI in a config file
  • Use POJO or builder pattern for large JSON
  • Modularize tests into reusable methods
  • Use @BeforeMethod for common setup

📌 Conclusion

RestAssured is a powerful skill for any automation QA working with APIs.
Java testers can use their existing skills to write flexible, readable, and maintainable API test cases — beyond manual tools like Postman.

🚀 “From exploratory to regression – RestAssured makes your API testing efficient and enterprise-ready.”

🔹 Topic 8: API Security Testing Basics for QA + How to Prepare Test Data for API Testing

QA Tester को लागि API Security Testing को मूल ज्ञान + Test Data कसरी तयार गर्ने?


📖 Part 1: API Security Testing Basics for QA

API को functionality मात्रै test गर्नु पर्याप्त हुँदैन — tester को रूपमा तपाईंले security validate गर्न पनि जान्नुपर्छ।
Unauthorized access, data leakage, token misuse, आदि रोक्नको लागि API Security Testing अनिवार्य हुन्छ।

🔐 “Secure API = Trusted Application. Testing is your firewall.”


🛡️ Why API Security Matters?

  • Sensitive user data (password, card info) exposed हुन सक्छ
  • Token चोरी भयो भने unauthorized user ले system access गर्न सक्छ
  • Broken authentication/validation ले system vulnerable बनाउँछ

🔍 Common API Security Test Cases for QA

Test ScenarioExpected Behavior
🔐 No token providedReturn 401 Unauthorized
🔐 Invalid/expired token usedReturn 401 or 403
🚫 Accessing another user’s dataReturn 403 Forbidden
🛡️ Injection attack via parametersSanitize input or reject 400
🔄 Repeated login attempt (brute force)Rate limit or block
🔍 Direct access to restricted endpointsDeny access or redirect
🔎 Improper CORS headersBlock unauthorized cross-domain access

🛠️ Tools for API Security Testing

ToolPurpose
🔍 PostmanManual token validation and header checks
🧪 OWASP ZAPAPI scanning for vulnerabilities
💉 Burp SuiteIntercept and manipulate API requests
🧾 Newman + ScriptingAutomate token expiry, fuzzing

✅ Best Practices for Security Testing in QA

  • Always test APIs without authentication
  • Try broken tokens, replayed tokens, or expired headers
  • Check HTTPS usage and correct Content-Type headers
  • Use boundary testing and injection attempts
  • Validate role-based access control (admin vs user)

📖 Part 2: How to Prepare Test Data for API Testing

API testing मा सही test data नभए सम्म meaningful validation हुँदैन।
Data-driven testing ले test case लाई dynamic बनाउँछ र edge case cover गर्न सजिलो हुन्छ।


🗃️ Types of API Test Data

TypeExample
✅ Valid InputCorrect email/password, valid user ID
❌ Invalid InputWrong email format, special characters
🧪 Boundary DataMin/max length input, negative numbers
🔁 Duplicate DataSame email used twice in POST
🔓 Unauthorized DataToken missing, expired session
🌐 International DataUnicode characters, non-ASCII names

🛠️ Test Data Sources

SourceHow it helps
JSON file (testdata.json)Static input for test cases
Excel or CSVEasily maintained and shared
Faker libraryAuto-generate realistic random data
Environment variablesStore tokens, base URLs, etc. securely

🧪 Example (RestAssured + JSON)

java

CopyEdit

@DataProvider(name = “userData”)

public Object[][] getUserData() {

    return new Object[][] {

        { “lok123”, “Test@123” },

        { “testuser”, “abc@456” }

    };

}

Use in test:

java

CopyEdit

@Test(dataProvider = “userData”)

public void loginTest(String username, String password) {

    // API call logic using parameterized data

}


✅ Best Practices for API Test Data

  • Separate valid vs invalid input clearly
  • Use different environments (dev, test, staging) with dynamic tokens
  • Store JSON payloads in reusable templates
  • Maintain one test data strategy per project
  • Do not hardcode sensitive values (tokens, passwords)

📌 Conclusion

Security testing and structured test data preparation are both critical layers of API quality assurance.
Without security, data is at risk. Without realistic data, your API may pass tests but fail in production.

🔐 “Good API testing is not just about hitting endpoints — it’s about protecting them and knowing what to hit them with.”

🔹 Topic 9: API Automation Framework Structure (TestNG + RestAssured + Maven)

TestNG, RestAssured र Maven को उपयोग गरेर API Automation Framework कसरी बनाउने? Step-by-step Guide


📖 Introduction

Scripting मात्रले automation complete हुँदैन — एक proper framework चाहिन्छ जसले maintainability, scalability, र CI/CD integration सुनिश्चित गर्छ।
API automation framework बनाउँदा RestAssured (for API calls), TestNG (for test execution), र Maven (for dependency & build) को combo best मानिन्छ।

🏗️ “Framework भनेको foundation हो — जसले testing लाई production-ready बनाउँछ।”


🧱 Basic Project Structure

plaintext

CopyEdit

/ApiAutomationFramework

 ├── /src

 │   └── /test/java

 │       ├── /base        → BaseTest, Config setup

 │       ├── /tests       → Actual API test classes

 │       ├── /utils       → Helper methods, JSON parser, tokens

 │       ├── /data        → Test data provider classes

 ├── /testdata           → JSON/XML files

 ├── /resources

 │   └── config.properties → baseURI, tokens, etc.

 ├── testng.xml          → Test suite execution

 └── pom.xml             → Maven dependency and build file


🔧 Technologies Used

ToolPurpose
✅ RestAssuredFor API request and response validation
✅ TestNGFor organizing and running test cases
✅ MavenFor managing dependencies and building project
✅ Log4jFor logging
✅ ExtentReports or AllureFor reporting

🔸 Sample BaseTest.java (Reusable Setup)

java

CopyEdit

public class BaseTest {

    public static RequestSpecification requestSpec;

    @BeforeMethod

    public void setup() {

        requestSpec = new RequestSpecBuilder()

                .setBaseUri(“https://reqres.in”)

                .setContentType(ContentType.JSON)

                .build();

    }

}


🔸 Sample LoginTest.java (Test Layer)

java

CopyEdit

public class LoginTest extends BaseTest {

    @Test

    public void verifySuccessfulLogin() {

        given()

            .spec(requestSpec)

            .body(“{\”email\”: \”eve.holt@reqres.in\”, \”password\”: \”cityslick\”}”)

        .when()

            .post(“/api/login”)

        .then()

            .statusCode(200)

            .body(“token”, notNullValue());

    }

}


🔸 Sample testng.xml

xml

CopyEdit

<suite name=”APITestSuite”>

  <test name=”Login Tests”>

    <classes>

      <class name=”tests.LoginTest”/>

    </classes>

  </test>

</suite>


🔸 Sample pom.xml Dependencies

xml

CopyEdit

<dependencies>

  <dependency>

    <groupId>io.rest-assured</groupId>

    <artifactId>rest-assured</artifactId>

    <version>5.4.0</version>

    <scope>test</scope>

  </dependency>

  <dependency>

    <groupId>org.testng</groupId>

    <artifactId>testng</artifactId>

    <version>7.7.0</version>

    <scope>test</scope>

  </dependency>

  <dependency>

    <groupId>com.aventstack</groupId>

    <artifactId>extentreports</artifactId>

    <version>5.0.9</version>

  </dependency>

</dependencies>


🎯 Benefits of This Framework

BenefitDescription
🔁 ReusableBase class, request spec reused everywhere
🧪 Data-DrivenEasy to plug with Excel, JSON, or DataProvider
🚀 CI/CD ReadyCan integrate with Jenkins/GitHub Actions
🧾 Reporting + LogsGenerate HTML/Allure reports
🛠️ MaintainableScalable with more APIs/modules over time

📌 Conclusion

A well-structured API automation framework using TestNG, RestAssured, and Maven boosts confidence in delivery, keeps your QA process modular, and ready for CI/CD.
This setup is perfect for testers shifting from manual Postman testing to full-stack Java-based automation.

🔗 “Framework makes your scripts testable, readable, and dependable.”

🔹 Topic 10: API Mocking, Virtualization, and Testing Without Backend

Backend बिना API कसरी test गर्ने? Mock server र API virtualization को practical प्रयोग


📖 Introduction

धेरै जसो अवस्थामा tester लाई backend तयार नभएको अवस्थामा पनि testing गर्नुपर्छ।
यस्तो अवस्थामा API mocking वा virtualization प्रयोग गरिन्छ — जसले real backend को simulation तयार गर्छ।

🧪 “Mock API भनेको movie trailer जस्तै हो — पुरा system नभइकन behavior को experience दिन्छ।”


🧠 What is API Mocking?

API mocking भनेको एक dummy API endpoint तयार गर्नु हो जुन predefined data फर्काउँछ — just like the real server would.

  • No real logic
  • No actual database
  • Just request-response simulation

🧰 What is API Virtualization?

Virtualization ले mocking भन्दा detailed behavior simulate गर्छ:

  • Dynamic response
  • Delay simulation
  • Different responses based on input (logic emulation)

Used for complex system integration testing, partner system simulation, etc.


🧪 Real-World QA Scenario (Nepali Context)

ScenarioMocking Used?
Insurance app को policy API तयार छैन✅ Yes
Login API live छैन, but UI तयार छ✅ Yes
Integration partner को API week पछि आउनेछ✅ Yes

🔧 Mocking Tools for QA

ToolFeature
Postman Mock ServerCreate dummy endpoints easily
WireMockLocal mock server for Java testers
MockoonDesktop app to create mock APIs
BeeceptorOnline public mock endpoint
SwaggerHubAuto-mock from OpenAPI definition
Parasoft VirtualizeEnterprise-grade API virtualization

📦 Example: Postman Mock Server

  1. Create collection → Add request + example response
  2. Go to “Mocks” → Create mock server
  3. Postman ले एक URL generate गर्छ:

http

CopyEdit

https://mock-server-url.com/user/123

Now when you send a request, it will return predefined JSON.


🧪 Example: WireMock in Java (QA Automation)

java

CopyEdit

WireMockServer wireMockServer = new WireMockServer(8080);

wireMockServer.start();

stubFor(get(urlEqualTo(“/api/user/45”))

  .willReturn(aResponse()

    .withStatus(200)

    .withHeader(“Content-Type”, “application/json”)

    .withBody(“{ \”name\”: \”Lok\”, \”id\”: 45 }”)));

➡️ Now your test can hit http://localhost:8080/api/user/45 without a real backend.


🎯 Benefits of Mocking & Virtualization in QA

BenefitWhy It Matters
🚫 No backend dependencyTesting starts early
⚡ Fast & isolated test casesStable, repeatable environment
🧪 Negative/edge case simulationReal backend ले allow नगर्ने error हरू check गर्न सकिन्छ
🔁 Works with CI/CDFaster pipeline validation

📌 Conclusion

API mocking and virtualization allow QA teams to test early, test smart, and test independent of backend readiness.
It’s a must-have skill when working in microservices, DevOps, or agile sprints.

🔍 “Mock it until you build it — smart testers never wait for real systems.”

Scroll to Top