What You'll Learn
- What API testing is, precisely
- Why API testing is more valuable than UI testing
- The major types of API tests
- What a typical API test scenario looks like
Why This Matters
Most bugs in modern apps come from the API layer — wrong data, missing fields, broken authentication, race conditions. UI tests catch the symptoms; API tests catch the cause. Testing at the API level is faster, more stable, and finds bugs earlier in the development cycle. If you are not testing your APIs, you are shipping bugs to production.
Simple Explanation
API testing is the practice of sending requests to an API and verifying that the responses are correct. You test the API directly — without a UI, without a database inspector, without a browser. Just request in, response out, did it match expectations?
Real-World Analogy — Testing a Kitchen
Imagine testing a restaurant. You could test the dining experience (UI): sit at a table, order, eat, see if the food is good. Or you could test the kitchen directly (API): hand the chef an order, see what comes back. The kitchen test is faster, more reliable, and catches problems at the source. If the chef burns every steak, the dining experience will be bad no matter how nice the table setting.
API testing is kitchen testing. UI testing is dining experience testing. Both have value, but the kitchen test is where you catch real bugs.
Why API Testing Beats UI Testing
| Aspect | API testing | UI testing |
|---|---|---|
| Speed | Fast (milliseconds per test) | Slow (seconds per test) |
| Stability | Stable — APIs rarely change layout | Fragile — UI changes break tests |
| Coverage | Easy to test edge cases | Hard — must navigate UI |
| Cost | Low — no browser, no rendering | High — browser, screenshots, wait times |
| Catches bugs | At the source | At the symptom |
| Stage in pipeline | Early — unit/integration | Late — end-to-end |
The Major Types of API Tests
1. Positive testing
Send valid input, verify the API returns the expected success response.
// Test: create a user with valid data
POST /users {"name": "Anita", "email": "anita@example.com"}
Expected: 201, response contains id, name matches, email matches
2. Negative testing
Send invalid input, verify the API rejects it gracefully.
// Test: create a user with invalid email
POST /users {"name": "Anita", "email": "not-an-email"}
Expected: 422, error message mentions email field
3. Boundary testing
Test values at the edge of allowed ranges.
// Test: age field accepts 0, 1, 99, 100 but not -1 or 101
POST /users {"name": "Anita", "age": 0} → 201
POST /users {"name": "Anita", "age": -1} → 422
POST /users {"name": "Anita", "age": 150} → 422
4. Schema validation
Verify the response matches the expected structure (fields, types).
// Test: GET /users/123 returns an object with id (number), name (string), email (string)
Expected: response matches UserSchema
5. Status code validation
Verify the API returns the right status code for each scenario.
GET /users/123 → 200
GET /users/999999 → 404
POST /users (no auth) → 401
DELETE /users/123 (as non-admin) → 403
6. Authentication testing
Verify the API correctly authenticates requests.
No token → 401
Expired token → 401
Valid token, wrong user → 403
Valid token, right user → 200
7. Authorization testing
Verify the API enforces permission checks.
// User A tries to read User B's private data
GET /users/B/private (as User A) → 403
8. Error handling
Verify errors are returned in a consistent format with useful messages.
// Test: malformed JSON
POST /users "{invalid json"
Expected: 400, error body has code + message + details
9. Business rule validation
Verify the API enforces domain-specific rules.
// Test: cannot transfer more than account balance
POST /transfer {"from": "A", "to": "B", "amount": 1000000}
Expected: 422, error: "insufficient funds"
10. Data persistence
Verify that POST/PUT/DELETE actually changed the data.
// Test: create a user, then GET them
POST /users {...} → 201, id=123
GET /users/123 → 200, name matches the POSTed value
11. API chaining
Use the output of one request as the input to the next.
POST /users → captures the returned id
GET /users/{id} → uses the captured id
DELETE /users/{id} → uses the captured id
12. Contract testing
Verify the API matches its documented contract (OpenAPI spec).
13. Smoke testing
A small set of critical-path tests run after every deploy to confirm the API is up.
14. Regression testing
Re-run all tests after a change to ensure nothing broke.
The Testing Pyramid for APIs
/ /e2e\ ← few, slow, full system
/------ /integration\ ← moderate, multiple endpoints
/-------------- / contract \ ← many, schema validation
/------------------ / unit \ ← many, individual functions
/------------------------
Most of your tests should be at the unit and contract level. Few should be at the e2e level. This gives you fast, stable, comprehensive coverage.
What a Single API Test Looks Like
A typical API test has four parts:
// Test: creating a user with valid data returns 201 and the user
// 1. Setup — prepare the request
const request = {
method: "POST",
url: "/users",
headers: {"Content-Type": "application/json"},
body: {name: "Anita", email: "anita@example.com"}
};
// 2. Action — send the request
const response = await sendRequest(request);
// 3. Assertion — verify the response
expect(response.status).toBe(201);
expect(response.body.id).toBeDefined();
expect(response.body.name).toBe("Anita");
expect(response.body.email).toBe("anita@example.com");
// 4. Teardown — clean up
await deleteUser(response.body.id);
Common Mistakes
- Testing only the happy path. "It works when everything is right" is not testing. Most bugs are in edge cases.
- Not cleaning up test data. Each test run leaves users, orders, and posts in the database. Eventually the test environment becomes unusable.
- Tests that depend on each other. If test B depends on test A creating data, the suite breaks when run in a different order.
- Testing the implementation, not the contract. "The response is exactly this JSON" breaks when the API adds a new field. Test the fields you care about, not the entire response.
- Skipping auth tests. "Anyone can call this" is the most common API security bug. Test that auth is enforced.
Practical Exercise (10 minutes)
Pick any endpoint from JSONPlaceholder. Write 5 test scenarios for it:
- One positive test (valid request).
- One negative test (invalid input).
- One boundary test (edge of allowed range).
- One status code test (e.g., 404 for non-existent ID).
- One schema test (response has the expected fields).
Mini Challenge
Design a complete test plan for a "user registration" endpoint. List at least 10 test scenarios covering positive, negative, boundary, auth, business rule, and persistence cases. For each, write the input and expected result.
Key Takeaways
- API testing verifies the API directly — without UI, without browser. Faster and more stable than UI testing.
- Major types: positive, negative, boundary, schema, status code, auth, authz, error handling, business rules, persistence, chaining, contract, smoke, regression.
- Most tests should be at the unit/contract level. Few should be e2e.
- Every test has: setup, action, assertion, teardown.
- Test edge cases, not just the happy path. Most bugs live there.
Previously: Module 5 (lessons 26–31) covered authentication.
Today: You learned what API testing is and the major test types.
Next: Lesson 33 dives into positive vs negative testing in detail.
FAQ
Do I need to test the UI if I test the API?
Yes, but far less. API tests catch data and logic bugs. UI tests catch presentation and interaction bugs. A healthy test suite has ~70% API tests and ~30% UI tests, not the other way around.
Should API tests use a real database?
Yes, ideally a dedicated test database. Mocking the database hides integration bugs. Each test should clean up after itself so the database stays pristine.
Comments
Comments
Post a Comment