API Testing · Beginner to job‑ready
API in Software Testing: What, Why, How — Complete Tutorial
A student portal's web page shows the right marks, but the mobile app shows yesterday's marks for some students. The screens are different, yet both get their data from the same place: an API (application programming interface) on the server. Testing that API directly, without any screen, finds this kind of bug faster and more reliably than clicking through two apps. That is API testing.
What "API" means for a tester
For testing purposes, an API is a set of URLs (endpoints) that accept a request and return a response, usually JSON over HTTP. A request has four parts you control, and a response has three parts you check:
| Request | Example | Response | Example |
|---|---|---|---|
| Method | GET, POST, PUT, PATCH, DELETE | Status code | 200, 201, 400, 404 |
| URL and parameters | /api/students/1?term=2 | Headers | Content-Type: application/json |
| Headers | Authorization: Bearer <token> | Body | {"id": 1, "name": "Asha"} |
| Body | {"name": "Ravi"} | Response time is also measured | |
If you are new to REST itself, read REST API with a simple example first.
Why test at the API level
- Earlier: the API is often ready before the UI, so testing can start sooner.
- Faster and more stable: an API test runs in milliseconds and does not break when a button moves.
- Closer to the business rules: validation, calculations and permissions live on the server; the UI only displays them.
- One test, many clients: the web app, mobile app and partner integrations all use the same API.
UI tests are still needed for layout and user flows. Most teams aim for many API tests and fewer, slower UI tests. More on this in why API testing matters in real projects.
Designing test cases for one endpoint
Take two endpoints: GET /api/students/{id} and POST /api/students. Good test design covers the happy path and, more importantly, what happens when things go wrong:
| # | Test | Expected result |
|---|---|---|
| 1 | GET an existing id | 200, JSON content type, fields id, name, course |
| 2 | GET an id that does not exist | 404 with a clear error message, not 500 |
| 3 | GET with a non-numeric id, such as abc | 400 or 404, never a server crash |
| 4 | POST without the required name | 400 with a message naming the missing field |
| 5 | POST valid data | 201 and the new record with an id |
| 6 | POST with malformed JSON | 400 "Invalid JSON" |
| 7 | Any call without a token (on a protected API) | 401; with another user's token, 403 |
| 8 | Response time under normal load | Within the agreed limit, for example 500 ms |
A longer set of sample test cases is in API testing interview questions and sample test cases.
A runnable example with Node.js
This example needs only Node.js 18 or later, which includes fetch and a built-in test runner. First, a tiny API to test, saved as server.js:
const http = require("node:http");
const students = [{ id: 1, name: "Asha", course: "Python" }];
function createServer() {
return http.createServer((req, res) => {
const send = (code, body) => {
res.writeHead(code, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
const m = req.url.match(/^\/api\/students\/(\d+)$/);
if (req.method === "GET" && m) {
const s = students.find(x => x.id === Number(m[1]));
return s ? send(200, s) : send(404, { error: "Student not found" });
}
if (req.method === "POST" && req.url === "/api/students") {
let data = "";
req.on("data", c => (data += c));
req.on("end", () => {
let body;
try { body = JSON.parse(data); } catch { return send(400, { error: "Invalid JSON" }); }
if (!body.name) return send(400, { error: "name is required" });
const s = { id: students.length + 1, name: body.name, course: body.course ?? null };
students.push(s);
send(201, s);
});
return;
}
send(404, { error: "Not found" });
});
}
module.exports = { createServer };Then the tests, saved as students.test.js. They start the server on a free port, run test cases 1, 2, 4 and 5 from the table, and stop the server:
const test = require("node:test");
const assert = require("node:assert/strict");
const { createServer } = require("./server");
let server, base;
test.before(async () => {
server = createServer().listen(0);
await new Promise(r => server.once("listening", r));
base = `http://localhost:${server.address().port}`;
});
test.after(() => server.close());
test("GET existing student returns 200 and the right fields", async () => {
const res = await fetch(`${base}/api/students/1`);
assert.equal(res.status, 200);
assert.match(res.headers.get("content-type"), /application\/json/);
const body = await res.json();
assert.deepEqual(Object.keys(body).sort(), ["course", "id", "name"]);
assert.equal(body.name, "Asha");
});
test("GET unknown student returns 404 with an error message", async () => {
const res = await fetch(`${base}/api/students/999`);
assert.equal(res.status, 404);
assert.equal((await res.json()).error, "Student not found");
});
test("POST without name is rejected with 400", async () => {
const res = await fetch(`${base}/api/students`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ course: "Java" }),
});
assert.equal(res.status, 400);
});
test("POST valid student returns 201 and a new id", async () => {
const res = await fetch(`${base}/api/students`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ravi", course: "Java" }),
});
assert.equal(res.status, 201);
const body = await res.json();
assert.equal(body.id, 2);
assert.equal(body.name, "Ravi");
});Run node --test --test-reporter=spec students.test.js. Output on Node 22 (your timings will differ):
✔ GET existing student returns 200 and the right fields (62.9404ms)
✔ GET unknown student returns 404 with an error message (5.1988ms)
✔ POST without name is rejected with 400 (8.0382ms)
✔ POST valid student returns 201 and a new id (4.4163ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 284.4639Notice that the last test depends on the data: it expects id 2 because the store starts with one student. Real test suites reset or seed the data before each run so tests do not depend on each other's order.
The same checks in Postman and REST Assured
In Postman, checks are written in the request's Tests (post-response script) tab:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Student has the expected fields", function () {
const s = pm.response.json();
pm.expect(s).to.have.property("id");
pm.expect(s).to.have.property("name");
pm.expect(s).to.have.property("course");
});A full walkthrough of collections and environments is in API testing with Postman, step by step. In Java teams, REST Assured is common:
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
@Test
public void getStudentReturnsFields() {
given()
.header("Authorization", "Bearer " + token)
.when()
.get("https://api.example.com/api/students/1")
.then()
.statusCode(200)
.body("id", equalTo(1))
.body("name", notNullValue())
.time(lessThan(500L));
}Types of API testing
- Functional: correct responses for valid and invalid input (everything above).
- Contract or schema: the response structure matches the agreed specification, often an OpenAPI document or JSON Schema.
- Security: authentication, authorisation (can user A read user B's data by changing the id?), input injection and rate limits.
- Performance: response times and errors under load, with tools such as JMeter or k6.
- Integration: a chain of calls, such as create order, pay, then check order status.
Bugs API testing commonly finds
- A 500 error where the API should return 400 for bad input.
- A 200 status with an error message inside the body, which breaks client logic.
- Missing permission checks: changing
/students/1to/students/2returns someone else's record. - Fields that change type, such as a number returned as a string in some responses.
- Duplicate records when a POST is retried after a timeout.
FAQs
Does API testing need coding?
You can start with Postman and little code. For automation in a project, you will write tests in JavaScript, Java or Python, so basic programming is needed.
What is the difference between API testing and unit testing?
Unit tests check individual functions inside the code, usually written by developers. API tests send real HTTP requests to a running service and check its behaviour from the outside.
Which tool should a beginner learn first?
Postman, to understand requests and responses. Then one code-based tool that matches your team's language, such as REST Assured for Java or a JavaScript test runner.