Cross_Column

Monday, 26 October 2026

API Testing Fundamentals



API Testing Fundamentals: A Beginner's Guide | Way2Testing
Way2Testing · API Testing Tutorial Series

API Testing Fundamentals: A Beginner’s Guide

Learn what APIs are, how applications communicate, how REST APIs work, and how testers check that APIs return the correct results. This guide starts with the basics and prepares you for hands-on API automation with Java and Rest Assured.

What you will learn
  • What an API is and why API testing matters.
  • How REST APIs, HTTP requests, and responses work.
  • The purpose of common HTTP methods and status codes.
  • How JSON, XML, headers, parameters, cookies, and tokens are used.
  • Which tools are useful for learning and testing APIs.

Prerequisites: No programming experience is required for this introductory lesson.

1. Introduction to API Testing

API testing is the process of checking whether an Application Programming Interface works as expected. A tester sends requests to an API and verifies the response, returned data, status code, headers, and other expected behavior.

For example, when a shopping application displays a product list, the application may call an API to retrieve product information. An API test can check that the service returns a successful response, that each product has a name and price, and that unavailable products are handled correctly.

Why is API testing important?

  • Find defects early: APIs can be tested before the complete user interface is ready.
  • Test business rules: Check calculations, validation, permissions, and data processing.
  • Automate repeatable checks: Run the same tests after code changes or deployments.
  • Test faster than many UI workflows: API tests usually avoid browser rendering and screen interactions.
  • Check integration: Verify that different applications and services exchange data correctly.
Simple example: If a registration API requires an email address, test a valid email, a missing email, an invalid email format, and a duplicate email. Verify both the response and whether the user record was created correctly.

2. What Is an API? Understanding APIs with Real-Life Examples

API stands for Application Programming Interface. It defines how one software application can request data or actions from another application. An API acts as a defined point of communication between software systems.

A real-life example: Ordering food

Imagine using a food delivery application. You choose a restaurant, view its menu, and place an order. The application may call different APIs to retrieve restaurants, fetch menu items, calculate the total, submit the order, and check delivery status.

Common examples of APIs

  • A weather application retrieves current weather from a weather service.
  • A payment gateway lets a shopping website initiate and verify payments.
  • An HR system retrieves employee details from an employee service.
  • A login service verifies credentials and may issue an access token.

What does an API tester check?

An API tester checks that the correct request produces the expected response, invalid requests are handled safely, users can access only permitted data, and the service behaves correctly when errors occur.

3. What Is a REST API? REST vs SOAP

REST stands for Representational State Transfer. It is an architectural style for designing network-based services. REST APIs commonly use HTTP methods and often exchange data in JSON format. REST is not a programming language or a specific protocol.

A REST-style API commonly exposes resources through URLs. For example, /users may represent a collection of users, while /users/42 may represent the user whose ID is 42.

What is SOAP?

SOAP stands for Simple Object Access Protocol. It is a messaging protocol with a defined XML message structure. SOAP services often use a WSDL document to describe available operations and message formats.

FeatureRESTSOAP
NatureArchitectural styleMessaging protocol
Common data formatOften JSON; XML is also possibleXML envelope
TransportCommonly HTTP/HTTPSCan use HTTP and other transports
Interface descriptionOften documented with OpenAPIOften described using WSDL
Typical useWeb, mobile, and microservice APIsEnterprise integrations that need SOAP contracts and features

Neither approach is automatically better for every situation. The right choice depends on the system, interoperability requirements, existing contracts, security needs, and organizational standards.

4. What Is Rest Assured? Why Do We Use It?

REST Assured is a Java library that makes it easier to test REST APIs. It provides a readable syntax for sending HTTP requests and validating responses, so testers do not have to build every request and assertion from scratch.

Rest Assured is especially useful when you want API tests written in Java and integrated with tools such as Maven, TestNG, JUnit, and reporting systems.

A simple Rest Assured example

The following example illustrates the basic structure. Replace the sample endpoint with a test API that you are authorized to use, and add the Rest Assured dependency to your Java project before running it.

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

import org.junit.jupiter.api.Test;

class GetUserTest {

    @Test
    void shouldReturnUserList() {
        given()
        .when()
            .get("https://api.example.com/users")
        .then()
            .statusCode(200)
            .body("size()", greaterThan(0));
    }
}

Note: api.example.com is a placeholder, not a real test service. The endpoint must exist and return a JSON array for this particular assertion to work. The example uses JUnit 5; a TestNG version can also be used.

Understanding the three main steps

  • given() — configure the request, such as headers, parameters, authentication, or body.
  • when() — send the HTTP request.
  • then() — validate the response using assertions.

Benefits of Rest Assured

  • Readable request and response validation syntax.
  • Support for common HTTP methods, authentication, headers, and parameters.
  • JSON and XML response validation.
  • Integration with Java test frameworks and build tools.
  • Support for reusable specifications and framework utilities.

5. API Testing vs UI Testing vs Manual Testing

These terms describe different aspects of testing. API testing focuses on the service interface. UI testing focuses on what users see and interact with. Manual testing describes testing performed by a person rather than being fully automated; manual testing can cover both APIs and user interfaces.

AspectAPI TestingUI Testing
Main focusRequests, responses, business rules, data and accessPages, controls, layouts and user workflows
Typical toolsPostman, Rest Assured, cURLPlaywright, Selenium, Cypress
ExecutionOften fast because no browser UI is requiredOften slower due to browser rendering and interactions
Can validateStatus codes, payloads, headers, authorizationVisibility, navigation, layout and user interactions
LimitationsDoes not by itself prove that the UI works correctlyMay not directly isolate every backend rule or error case

A strong test strategy usually combines API tests and UI tests. For example, test a discount calculation thoroughly through the API, then use a smaller number of UI tests to verify that the discount appears correctly during checkout.

6. Understanding Client, Server, Request and Response

A client is the software that makes a request, such as a browser, mobile application, or test script. A server receives the request, performs the required processing, and sends a response.

  • Request: What the client sends to the server.
  • Response: What the server sends back to the client.
  • Endpoint: The URL or route used to access an API operation.
  • Payload: Data sent in a request body or returned in a response body.

Example request

GET /users/42 HTTP/1.1
Host: api.example.com
Accept: application/json

Example response

HTTP/1.1 200 OK
Content-Type: application/json

{
  "id": 42,
  "name": "Asha",
  "active": true
}

In this example, the client asks for user 42. The server returns status code 200 and a JSON object. A test can check the status code, the user ID, the name, and whether the user is active.

7. Understanding HTTP and HTTPS

HTTP (Hypertext Transfer Protocol) is a common protocol for communication between clients and web servers. APIs frequently use HTTP to send requests and return responses.

HTTPS is HTTP protected by TLS. TLS helps encrypt traffic in transit and allows the client to verify the server's identity when certificate validation is performed correctly.

HTTPHTTPS
Traffic is not encrypted by HTTP itself.Traffic is encrypted in transit using TLS.
Does not provide TLS server certificate verification.Uses certificates to help authenticate the server.
Not appropriate for transmitting sensitive data over untrusted networks without additional protection.The standard choice for public and private APIs that transmit data over networks.

When testing an HTTPS API, do not disable certificate validation just to make a test pass. Investigate expired certificates, incorrect hostnames, or missing trusted certificates in the test environment.

8. HTTP Methods Explained: GET, POST, PUT, PATCH and DELETE

HTTP methods communicate the action the client wants to perform on a resource. In API testing, the method, endpoint, request data, permissions, and expected response should all be validated.

MethodCommon purposeExampleTypical success response
GETRetrieve informationGET /users/42200 OK
POSTCreate a resource or submit an operationPOST /users201 Created or another documented success code
PUTCreate or replace the state of a resource at a known URI, depending on the API contractPUT /users/42200 OK or 204 No Content
PATCHApply a partial modificationPATCH /users/42200 OK or 204 No Content
DELETERemove a resource or request its deletionDELETE /users/42204 No Content or another documented success code

Example: Create a user with POST

POST /users
Content-Type: application/json

{
  "name": "Asha",
  "email": "asha@example.com"
}

The API might respond with 201 Created and the new user's ID. The exact response depends on the API contract.

What should you test?

  • Does the endpoint accept the correct method?
  • Does it return the expected status code?
  • Is the returned data correct?
  • Are missing or invalid fields handled properly?
  • Does the operation have the documented effect on the resource?
Remember: PUT is generally intended to be idempotent, meaning repeating the same request should have the same intended effect. POST is not generally idempotent. Always verify the specific API contract.

9. HTTP Status Codes Explained

A status code is a three-digit number in the HTTP response. It gives a broad indication of the result of the request. The response body may provide additional details.

StatusMeaningWhat a tester should verify
200 OKThe request succeeded.Validate the response body and business result.
201 CreatedA resource was created.Check the created resource and its ID or location, when provided.
204 No ContentThe request succeeded with no response content.Confirm the status and that no response body is expected.
400 Bad RequestThe server could not process the request because it was invalid or malformed.Check validation errors and ensure no unintended change occurred.
401 UnauthorizedValid authentication credentials are missing or not accepted.Verify the authentication challenge or error response.
403 ForbiddenThe server refuses the operation, commonly because permission is insufficient.Verify access control and ensure protected data is not exposed.
404 Not FoundThe requested resource was not found, or the server does not expose that route.Check invalid IDs, routes, and the API's documented behavior.
500 Internal Server ErrorThe server encountered an unexpected condition.Capture diagnostic details and report the failure without exposing sensitive data.

Status codes must be interpreted according to the API's documented contract. For example, a successful DELETE may return 200 or 204, and some APIs deliberately return 404 for a resource that does not exist.

Status code categories

  • 1xx: Informational responses.
  • 2xx: Successful responses.
  • 3xx: Redirection responses.
  • 4xx: Client-error responses.
  • 5xx: Server-error responses.

10. Understanding HTTP Headers, Request Body and Response Body

An HTTP request can contain a method, URL, headers, and sometimes a body. The response contains a status code and headers and may also contain a body.

Headers

Headers provide metadata about a request or response. Common examples include:

  • Content-Type: application/json — describes the format of the body being sent.
  • Accept: application/json — tells the server which response format the client prefers.
  • Authorization: Bearer <token> — sends a bearer access token when the API uses this authentication scheme.

Request body

A request body contains data sent to the API, often with POST, PUT, or PATCH. GET requests generally do not use a body; API designs should use the documented parameters and conventions instead.

{
  "name": "Asha",
  "email": "asha@example.com"
}

Response body

The response body contains the result returned by the API. It might contain a JSON object, an array, XML, a file, an error message, or no content at all.

During testing, verify that the body matches the expected structure and business rules—not just that the status code is successful.

11. JSON Basics for API Testers

JSON stands for JavaScript Object Notation. It is a text-based format widely used to exchange structured data between applications. JSON supports objects, arrays, strings, numbers, booleans, and null.

Example JSON response

{
  "id": 42,
  "name": "Asha",
  "active": true,
  "department": null,
  "skills": ["Java", "API Testing"],
  "address": {
    "city": "Pune",
    "country": "India"
  }
}

In this example:

  • id is a number.
  • name is a string.
  • active is a boolean.
  • department is null, meaning no value is supplied.
  • skills is an array.
  • address is a nested object.

What should you validate in JSON?

  • Required keys are present.
  • Values and data types are correct.
  • Arrays contain the expected records.
  • Nested objects have correct values.
  • Optional and null values follow the API specification.
  • Sensitive fields are not returned to unauthorized users.

JSON object key order should not normally be treated as significant. Validate the values and structure rather than relying on the order of keys in the response text.

12. XML Basics for API Testing

XML stands for Extensible Markup Language. It represents data using nested, named elements. XML is used by SOAP services and by some REST APIs and enterprise integrations.

Example XML response

<user>
  <id>42</id>
  <name>Asha</name>
  <active>true</active>
</user>

The XML above represents a user with an ID, name, and active status. Unlike JSON, XML uses opening and closing tags for elements.

JSONXML
Uses objects and arrays.Uses nested elements and attributes.
Common in modern REST APIs.Common in SOAP and some enterprise APIs.
Can be queried using JSONPath in supported tools.Can be queried using XPath in supported tools.

For XML API tests, verify required elements, values, namespaces where applicable, and the expected structure. Do not assume that every API accepts both JSON and XML; check its documentation.

13. Query Parameters vs Path Parameters

Path parameters and query parameters both help identify what data an API should return, but they appear in different parts of the URL.

Path parameter

A path parameter is part of the URL path and commonly identifies a particular resource.

GET https://api.example.com/users/42

Here, 42 identifies the user. The API route may be described as /users/{id}.

Query parameter

A query parameter appears after a question mark (?). It commonly controls filtering, searching, sorting, or pagination.

GET https://api.example.com/users?department=IT&active=true

Here, department=IT and active=true are query parameters. Multiple query parameters are separated by an ampersand (&).

FeaturePath parameterQuery parameter
LocationWithin the URL pathAfter ?
Typical useIdentify a resourceFilter, sort, search, paginate or modify a query
Example/products/15/products?category=books

Test valid values, missing values, invalid formats, boundary values, URL encoding, and combinations of parameters according to the API contract.

14. What Are Cookies, Sessions and Authentication Tokens?

APIs often need to identify a user or verify that the user is allowed to perform an operation. Cookies, server-side sessions, and tokens are common mechanisms, but they work differently.

Cookies

A cookie is a small piece of data stored by a client and sent with later requests when its scope and rules allow it. Cookies are often used for browser sessions, preferences, or other state. Security attributes such as Secure, HttpOnly, and SameSite matter for browser-based applications.

Sessions

In a session-based design, the server commonly stores session state and the client sends a session identifier, often through a cookie. The server uses that identifier to associate requests with a session.

Authentication tokens

A token is a value used to represent or prove authorization or authentication, depending on the system. A common pattern is to send an access token in the Authorization header:

GET /profile
Authorization: Bearer YOUR_ACCESS_TOKEN

The placeholder YOUR_ACCESS_TOKEN must be replaced by a valid token issued by the relevant authentication service. Do not publish real tokens in blog examples, source control, screenshots, or reports.

What is API chaining?

API chaining means using information returned by one request in a later request. For example, a test may authenticate, extract an access token, use it to retrieve a profile, create a record, and then verify the record using its ID.

Security reminder: Keep credentials and tokens out of source code. Use environment variables or a secrets manager, limit token permissions, and avoid logging secrets in plain text.

15. API Testing Tools: Postman, Swagger, cURL and Rest Assured

Different tools serve different purposes. Beginners often start with a visual tool to understand requests and responses, then use a code-based library to automate repeatable tests.

ToolWhat it is useful forGood starting point
PostmanManually send API requests, inspect responses, and organize collections.Learn request methods, headers, parameters, bodies and basic assertions.
Swagger UIExplore and try APIs when an OpenAPI definition is available and the interface is enabled.Understand endpoints, required fields, schemas and documented responses.
cURLSend HTTP requests from a terminal or command line.Learn how method, headers and payloads can be sent without a graphical interface.
Rest AssuredAutomate API tests in Java and integrate them into a test framework.Write repeatable tests with assertions and run them through Maven and a test runner.

Example cURL request

curl -i -X GET "https://api.example.com/users/42" \
  -H "Accept: application/json"

This command sends a GET request and asks for a JSON response. The endpoint is illustrative; use a real, authorized test endpoint when practicing.

Other useful tools include browser developer tools, API documentation generators, mock servers, database clients, CI/CD platforms, and reporting tools. Choose tools based on the test objective rather than trying to use every tool for every task.

16. Types of API Testing

API testing includes several test types. A complete strategy combines them according to the risks and requirements of the application.

1. Functional testing

Checks whether an API performs the required business function. For example, a create-order API should create an order with the correct items and total.

2. Positive testing

Sends valid requests and checks that the API behaves as expected. For example, retrieving an existing user with a valid ID and valid authorization.

3. Negative testing

Sends invalid, incomplete, or unauthorized requests and verifies that the API handles them safely. Examples include missing required fields, invalid IDs, malformed JSON, and expired tokens.

4. Integration testing

Checks communication between services or components. For example, submitting an order may involve order, inventory, and payment services.

5. Security testing

Checks authentication, authorization, input handling, sensitive-data exposure, and other security requirements. Specialized security assessment may require additional tools and expertise.

6. Performance testing

Examines behavior under expected or heavy workloads, including throughput, latency, and error rates. Rest Assured can check individual response times, but dedicated load-testing tools are generally better for sustained load and stress tests.

7. Contract testing

Checks that an API's request and response structures match an agreed contract, such as an OpenAPI specification or a consumer-provider contract.

8. Regression testing

Re-runs existing tests after code changes to identify unintended effects on previously working behavior.

9. Smoke testing

Runs a small set of important checks to determine whether a deployed API is available and its critical functions work.

10. Data validation testing

Checks the accuracy, completeness, format, and consistency of returned or stored data, sometimes comparing API results with a database or another trusted source.

Summary

API testing checks the behavior of software interfaces by sending requests and validating responses. Before automating tests, learn how HTTP works, understand common methods and status codes, and become comfortable reading JSON and XML.

Postman, Swagger UI, and cURL are useful for exploring APIs. Rest Assured helps you turn those checks into repeatable Java tests that can run as part of a larger automation framework.

What to learn next

Continue with “How to Set Up Java, Eclipse, Maven and Rest Assured”. In that tutorial, you can install the required tools, create a Maven project, add dependencies, and run your first automated GET request.

Practice Questions

  1. What is an API, and why do applications use APIs?
  2. What is the difference between REST and SOAP?
  3. Which HTTP method is commonly used to retrieve a resource?
  4. What is the difference between status codes 401 and 403?
  5. What is the difference between a path parameter and a query parameter?
  6. Why should an API test validate the response body as well as the status code?
  7. What is the difference between cookies, sessions and tokens?
  8. When should you use Rest Assured instead of manually sending requests?
  9. What is the difference between functional testing and performance testing?
  10. Why should real access tokens and passwords never be hardcoded in test code?

No comments:

Post a Comment

Few More

How to Set Up Java, Eclipse, Maven and REST Assured

How to Set Up Java, Eclipse, Maven and REST Assured | Way2Testing Way2Testing · API Testing Tutorial Series · Part 2 ...

Popular Posts