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 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.
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.
Illustration: a simplified request-and-response flow. Real systems may contain several services and databases.
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.
| Feature | REST | SOAP |
|---|---|---|
| Nature | Architectural style | Messaging protocol |
| Common data format | Often JSON; XML is also possible | XML envelope |
| Transport | Commonly HTTP/HTTPS | Can use HTTP and other transports |
| Interface description | Often documented with OpenAPI | Often described using WSDL |
| Typical use | Web, mobile, and microservice APIs | Enterprise 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.
| Aspect | API Testing | UI Testing |
|---|---|---|
| Main focus | Requests, responses, business rules, data and access | Pages, controls, layouts and user workflows |
| Typical tools | Postman, Rest Assured, cURL | Playwright, Selenium, Cypress |
| Execution | Often fast because no browser UI is required | Often slower due to browser rendering and interactions |
| Can validate | Status codes, payloads, headers, authorization | Visibility, navigation, layout and user interactions |
| Limitations | Does not by itself prove that the UI works correctly | May 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.
Simplified HTTP communication between a test client and an API server.
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.
| HTTP | HTTPS |
|---|---|
| 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.
| Method | Common purpose | Example | Typical success response |
|---|---|---|---|
| GET | Retrieve information | GET /users/42 | 200 OK |
| POST | Create a resource or submit an operation | POST /users | 201 Created or another documented success code |
| PUT | Create or replace the state of a resource at a known URI, depending on the API contract | PUT /users/42 | 200 OK or 204 No Content |
| PATCH | Apply a partial modification | PATCH /users/42 | 200 OK or 204 No Content |
| DELETE | Remove a resource or request its deletion | DELETE /users/42 | 204 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?
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.
| Status | Meaning | What a tester should verify |
|---|---|---|
200 OK | The request succeeded. | Validate the response body and business result. |
201 Created | A resource was created. | Check the created resource and its ID or location, when provided. |
204 No Content | The request succeeded with no response content. | Confirm the status and that no response body is expected. |
400 Bad Request | The server could not process the request because it was invalid or malformed. | Check validation errors and ensure no unintended change occurred. |
401 Unauthorized | Valid authentication credentials are missing or not accepted. | Verify the authentication challenge or error response. |
403 Forbidden | The server refuses the operation, commonly because permission is insufficient. | Verify access control and ensure protected data is not exposed. |
404 Not Found | The 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 Error | The 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:
idis a number.nameis a string.activeis a boolean.departmentis null, meaning no value is supplied.skillsis an array.addressis 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.
| JSON | XML |
|---|---|
| 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 (&).
| Feature | Path parameter | Query parameter |
|---|---|---|
| Location | Within the URL path | After ? |
| Typical use | Identify a resource | Filter, 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.
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.
| Tool | What it is useful for | Good starting point |
|---|---|---|
| Postman | Manually send API requests, inspect responses, and organize collections. | Learn request methods, headers, parameters, bodies and basic assertions. |
| Swagger UI | Explore and try APIs when an OpenAPI definition is available and the interface is enabled. | Understand endpoints, required fields, schemas and documented responses. |
| cURL | Send HTTP requests from a terminal or command line. | Learn how method, headers and payloads can be sent without a graphical interface. |
| Rest Assured | Automate 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.
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
- What is an API, and why do applications use APIs?
- What is the difference between REST and SOAP?
- Which HTTP method is commonly used to retrieve a resource?
- What is the difference between status codes 401 and 403?
- What is the difference between a path parameter and a query parameter?
- Why should an API test validate the response body as well as the status code?
- What is the difference between cookies, sessions and tokens?
- When should you use Rest Assured instead of manually sending requests?
- What is the difference between functional testing and performance testing?
- Why should real access tokens and passwords never be hardcoded in test code?
No comments:
Post a Comment