Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
API testing APIs APIs From Zero to Real-World API Testing & Automation Module 6 — API Testing

What Is API Testing and Why It Matters

Reviewed & accurate
AI Summary

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

AspectAPI testingUI testing
SpeedFast (milliseconds per test)Slow (seconds per test)
StabilityStable — APIs rarely change layoutFragile — UI changes break tests
CoverageEasy to test edge casesHard — must navigate UI
CostLow — no browser, no renderingHigh — browser, screenshots, wait times
Catches bugsAt the sourceAt the symptom
Stage in pipelineEarly — unit/integrationLate — 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

  1. Testing only the happy path. "It works when everything is right" is not testing. Most bugs are in edge cases.
  2. Not cleaning up test data. Each test run leaves users, orders, and posts in the database. Eventually the test environment becomes unusable.
  3. Tests that depend on each other. If test B depends on test A creating data, the suite breaks when run in a different order.
  4. 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.
  5. 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:

  1. One positive test (valid request).
  2. One negative test (invalid input).
  3. One boundary test (edge of allowed range).
  4. One status code test (e.g., 404 for non-existent ID).
  5. 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.
Course continuity
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.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments