GUIDE / api
API Testing Tutorial: A Beginner's Complete Guide
API testing tutorial for beginners: learn REST API checks, CRUD test cases, tools, status codes, and a practical checklist for reliable API quality.
This API testing tutorial is for QA engineers and developers who need a practical path from "I can send a request" to "I can design reliable coverage for REST services." API testing checks the service layer directly: endpoints, methods, headers, authentication, payloads, status codes, and business rules. Done well, it finds defects earlier and more cheaply than driving every rule through a browser.
You will learn what API testing is, how to test REST APIs step by step, how to design CRUD test cases, which tools fit which job, how functional and non-functional checks differ, and a checklist you can reuse on real projects. For hands-on Postman mechanics, pair this guide with the Postman tutorial.
What Is API Testing?
API testing is the practice of verifying that application programming interfaces meet functional and quality expectations. For web systems, that usually means HTTP APIs, often REST style JSON services, sometimes GraphQL, SOAP, or event driven endpoints.
Instead of clicking through a UI, you send requests such as:
POST /api/orders
Authorization: Bearer <token>
Content-Type: application/json
{
"productId": "sku-100",
"quantity": 2
}
Then you evaluate the response:
HTTP/1.1 201 Created
Content-Type: application/json
{
"id": "ord_9f3a",
"status": "pending",
"quantity": 2
}
You care about more than "it returned 200." You care whether the body is correct, whether unauthorized users are rejected, whether invalid data is validated, and whether side effects happened in the system.
Why API Testing Matters
- Frontends change more often than business contracts.
- Mobile, web, and partners may share one API.
- Failures at the API layer cascade to every client.
- API checks are usually faster and less flaky than UI flows.
- Security and authorization bugs often appear first at the API.
If your product has a UI and an API, testing only the UI is leaving the foundation under verified.
API Testing vs UI Testing vs Unit Testing
| Layer | Proves | Speed | Stability | Blind spots |
|---|---|---|---|---|
| Unit | Function logic in isolation | Fastest | High | Integration and real transport issues |
| API | Service contracts and business rules over HTTP | Fast | High when isolated | Visual UX, full browser journeys |
| UI / E2E | Real user journeys through the client | Slowest | More fragile | Can miss deep API matrix coverage |
A healthy strategy uses all three. API testing is often the highest leverage middle layer for product QA teams.
Core Concepts You Must Know
HTTP Methods
| Method | Typical use | Idempotent? |
|---|---|---|
| GET | Read resource | Yes |
| POST | Create or trigger action | Often no |
| PUT | Replace resource | Yes |
| PATCH | Partial update | Usually yes by design intent |
| DELETE | Remove resource | Yes |
Status Codes
Status codes are part of the contract. Learn the common families deeply in REST API status codes. A short map:
| Range | Meaning | Examples |
|---|---|---|
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirect | 301, 304 |
| 4xx | Client error | 400, 401, 403, 404, 409, 422 |
| 5xx | Server error | 500, 502, 503 |
Headers
Important headers often include:
AuthorizationContent-TypeAcceptIdempotency-KeyX-Request-Id- Caching headers
Payload Contracts
JSON fields have types, required rules, enums, formats, and nested objects. Your tests should validate both presence and meaning, not only that the response parses.
Authentication and Authorization
Authentication answers who you are. Authorization answers what you may do. API testing must cover both. Dedicated patterns appear in API authentication testing.
How to Test REST APIs Step by Step
Step 1: Gather the Contract
Sources:
- OpenAPI or Swagger docs
- API gateway docs
- Producer team README files
- Example requests from frontend code
- Recorded traffic from a working UI
If docs are missing or wrong, write down observed behavior and questions. Testing an undocumented API is possible, but riskier. Always distinguish confirmed contract from reverse engineered guesses.
Step 2: Set Up Environments
Create separate configs for local, staging, and any protected environments:
- Base URL
- Auth tokens or credential flow
- Test tenant ids
- Feature flags
- Timeout settings
Never hardcode production secrets into collections committed to git.
Step 3: Establish Auth
Common modes:
- API key
- Basic auth
- Session cookie
- Bearer token
- OAuth2 / JWT flows
Automate token acquisition when possible so humans are not copying tokens every hour.
Step 4: Map Resources and Risks
List resources:
- Users
- Products
- Orders
- Payments
- Admin settings
For each, note risks:
- Data loss
- Money impact
- Permission escape
- Idempotency
- Validation holes
- Breaking changes for clients
Step 5: Design Test Cases Before Mass Automation
Write cases for:
- Happy path
- Validation failures
- Auth failures
- Permission denials
- Not found paths
- Conflict states
- Boundary values
- State transitions
If you need a deeper case design method, see how to write API test cases.
Step 6: Execute Exploratory Requests
Use Postman, Bruno, curl, or a REST client to learn real behavior. Note mismatches between docs and runtime. Capture sample payloads.
Step 7: Automate the Stable, High Value Checks
Automate:
- Critical CRUD flows
- Authz rules
- Regression for past bugs
- Contract validation for consumer critical fields
Do not automate every exploratory experiment on day one.
Step 8: Run in CI
API suites belong in pull request pipelines because they are fast. Failures should print request id, endpoint, status, and relevant body excerpts.
Step 9: Maintain With the Contract
When fields are added, removed, or made required, update tests in the same change set whenever possible. Orphaned assertions become noise.
API Test Cases for CRUD Endpoints
Assume a simple resource:
POST /api/products
GET /api/products/{id}
GET /api/products
PATCH /api/products/{id}
DELETE /api/products/{id}
Create
| ID | Case | Expected |
|---|---|---|
| C01 | Create with valid payload | 201, body contains id and stored fields |
| C02 | Missing required name | 400 or 422 with clear error |
| C03 | Invalid price type | 400 or 422 |
| C04 | No auth token | 401 |
| C05 | Authenticated but not allowed | 403 |
| C06 | Duplicate SKU if unique | 409 or documented conflict behavior |
Read
| ID | Case | Expected |
|---|---|---|
| R01 | Get existing id | 200 and correct body |
| R02 | Get unknown id | 404 |
| R03 | List with default pagination | 200, array, pagination metadata |
| R04 | List with page size boundary | Honors limit rules |
| R05 | No auth on private resource | 401 |
Update
| ID | Case | Expected |
|---|---|---|
| U01 | Patch valid field | 200 or 204, changed field persists on GET |
| U02 | Patch unknown id | 404 |
| U03 | Patch with empty body | Documented behavior, no corruption |
| U04 | Patch forbidden field | 400/403/422 according to contract |
| U05 | Concurrent update conflict if supported | 409 or version rules |
Delete
| ID | Case | Expected |
|---|---|---|
| D01 | Delete existing id | 200 or 204, later GET is 404 |
| D02 | Delete unknown id | 404 or idempotent 204 if documented |
| D03 | Delete without permission | 403 |
| D04 | Delete already deleted id | Stable documented behavior |
This matrix is a REST API testing checklist starter for one resource. Multiply by roles and states for real systems.
What to Assert in an API Test
A strong API assertion set often includes:
- Status code
- Response time under a soft threshold when relevant
- Content type
- Required fields present
- Field types and formats
- Business values equal expected results
- Error shape for negative cases
- Side effects through a follow up GET
- Headers such as location on create
- Non leakage of sensitive data
Example with Playwright request style:
import { test, expect } from "@playwright/test";
test("creates product and reads it back", async ({ request }) => {
const create = await request.post("/api/products", {
data: { name: "Trail Runner", price: 12000, sku: `sku-${Date.now()}` },
});
expect(create.status()).toBe(201);
const body = await create.json();
expect(body.id).toBeTruthy();
expect(body.name).toBe("Trail Runner");
const read = await request.get(`/api/products/${body.id}`);
expect(read.status()).toBe(200);
expect(await read.json()).toMatchObject({
id: body.id,
name: "Trail Runner",
price: 12000,
});
});
Notice the follow up read. Create tests that only check 201 without persistence checks miss storage bugs.
Functional vs Non-Functional API Testing
Functional API Testing
Focus:
- Correctness of business rules
- Validation logic
- CRUD integrity
- Role based access
- Workflow state changes
Example: an order cannot transition from cancelled to shipped.
Non-Functional API Testing
Focus:
- Performance and load
- Reliability under retries
- Security hardening
- Scalability limits
- Availability behavior during dependency failure
Example: p95 latency stays under an agreed budget at a target RPS, or 429 responses appear with retry guidance when rate limited.
| Type | Question answered | Typical tools |
|---|---|---|
| Functional | Does it behave correctly? | Postman, REST Assured, Playwright, Supertest |
| Performance | Can it handle expected load? | k6, JMeter, Gatling |
| Security | Can it be abused? | ZAP, Burp, custom authz suites |
| Contract | Do producer and consumer agree? | Pact, OpenAPI validators |
Most beginners should master functional coverage first, then add performance and contract testing as the system matures.
Tools Used for API Testing
| Tool | Best for | Notes |
|---|---|---|
| Postman | Exploratory + team collections | Easy entry, Newman for CI |
| Bruno / Insomnia | Local first collections | Good alternatives |
| REST Assured | Java coded suites | Strong in JVM shops |
| Supertest | Node HTTP assertions | Great with Express style apps |
| Playwright request | Hybrid UI + API setups | Useful in end to end repos |
| Karate | Gherkin style API tests | All in one style |
| Pact | Consumer driven contracts | Prevents integration surprises |
| k6 / JMeter | Load and stress | Non-functional focus |
Tool choice is secondary to test design. A weak checklist in a fancy tool still yields weak confidence.
Auth and Permission Testing Essentials
Minimum auth matrix for a protected endpoint:
| Actor | Token state | Expected |
|---|---|---|
| Anonymous | None | 401 |
| Valid user | Own resource | 200 |
| Valid user | Someone else's resource | 403 or 404 by design |
| Expired token | Expired | 401 |
| Malformed token | Garbage | 401 |
| Admin | Admin only action | 200 |
| Non admin | Admin only action | 403 |
Never assume the UI is the only enforcement point. Always hit the API directly with alternate tokens.
Data Setup and Teardown Strategies
Good API suites create the data they need.
Patterns:
- Factory endpoints in test environments
- Admin setup APIs
- Direct test database seeding in private envs
- Idempotent create helpers with unique keys
Prefer unique emails, SKUs, and names:
const sku = `sku-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
Clean up when resources are expensive or shared. In fully disposable environments, recreation can be cheaper than perfect teardown, but do not pollute shared staging endlessly.
Contract Awareness Without Over Formality
Even before full contract testing, validate the fields consumers rely on.
Example critical fields for a login response:
accessTokenexpiresInuser.iduser.role
A response that returns 200 with a renamed token field still breaks clients. Schema checks catch that class of bug. Later you can deepen this with contract testing with Pact.
REST API Testing Checklist for QA
Use this checklist per endpoint or resource group:
- Happy path documented and automated
- Required field validation covered
- Optional field behavior covered
- Boundary values covered
- Auth missing and invalid covered
- Role permissions covered
- Not found behavior covered
- Conflict and duplicate rules covered
- Pagination filtering sorting covered if present
- Error response shape consistent
- Sensitive fields not leaked
- Idempotency verified where claimed
- Side effects verified with follow up calls
- Performance smoke threshold noted if relevant
- CI runs the stable pack on every PR
Common Mistakes in API Testing
Mistake 1: Only Checking Status Codes
200 with the wrong body is still a bug. Assert meaningful content.
Mistake 2: Testing Only Happy Paths
Attackers and clumsy clients send bad input constantly. Negative cases are not optional.
Mistake 3: Sharing One Mutable Record
Parallel CI will collide. Unique data is mandatory for scale.
Mistake 4: Ignoring Authorization
Many severe defects are IDOR style access problems. Direct object reference checks belong in your default pack.
Mistake 5: Hardcoding Tokens in Collections
Tokens expire and leak. Use environment vaults and scripted auth.
Mistake 6: Duplicating UI End to End Through API Noise
If you already proved a calculation at unit and API layers, maybe the UI only needs to prove wiring once.
Mistake 7: No Environment Parity Notes
Staging may use fake payments and looser rate limits. Document differences so failures are interpreted correctly.
Worked Example: Order Creation Flow
Business rules:
- Authenticated buyer can create an order for an in stock product.
- Quantity must be at least 1.
- Out of stock products are rejected.
- Buyers cannot create orders for other buyers.
- Created orders start as
pending.
High Value Cases
- Valid create returns 201 with
pending. - Quantity
0returns 422. - Unknown product returns 404 or 422.
- Out of stock returns 409 or 422.
- No token returns 401.
- Another user's account id in payload is ignored or rejected.
- GET order by id returns the same totals.
- List orders for buyer includes the new order.
Example Negative Assertion
const res = await request.post("/api/orders", {
headers: { Authorization: `Bearer ${buyerToken}` },
data: { productId: "sku-1", quantity: 0 },
});
expect(res.status()).toBe(422);
const error = await res.json();
expect(error.message).toMatch(/quantity/i);
How Much Automation Is Enough?
Enough means:
- Critical money and auth paths are covered
- Past production API incidents have regression tests
- Contract fields consumers need are protected
- Suite runs fast enough for PR use
- Failures are trusted
A hundred shallow tests can be weaker than thirty sharp ones. Depth on risk beats vanity counts.
Bringing API Testing Into Team Practice
Practical rollout:
- Pick the top five endpoints by business risk.
- Build a readable collection or coded suite.
- Add CI on pull requests.
- Expand CRUD matrices and auth matrices.
- Add contract checks for consumer critical payloads.
- Only then invest heavily in load testing.
Train manual testers to use API tools so bugs found in UI are reproduced at the service layer when relevant. That skill shortens debugging for everyone.
Practice Path
- Choose a public training API or local project.
- Document three endpoints by hand.
- Write CRUD and auth cases in a table.
- Execute them in Postman.
- Automate the top ten checks.
- Break a validation rule on purpose and confirm the suite catches it.
Then sharpen service layer instincts with QA challenges in QABattle. The best API testers think in contracts, states, and risks, not only in green checkmarks.
If you are preparing for hiring rounds, practice explaining this workflow with API testing interview questions.
Pagination, Filtering, and Sorting Checks
List endpoints hide many defects.
Minimum cases:
- Default page returns expected shape
pageandlimitboundaries are enforced- Out of range pages return empty lists or documented errors
- Filters combine correctly
- Sort order is stable for equal keys
- Total counts match data when claimed
Example assertions:
const res = await request.get("/api/products?limit=2&page=1");
expect(res.status()).toBe(200);
const body = await res.json();
expect(body.items).toHaveLength(2);
expect(body.page).toBe(1);
expect(body.limit).toBe(2);
expect(typeof body.total).toBe("number");
If clients depend on deterministic sort, prove it with seeded data rather than assuming database defaults.
Idempotency and Retries
Payment and order APIs often claim idempotency keys.
Test ideas:
- Same idempotency key with same payload returns the same resource.
- Same key with different payload is rejected or documented carefully.
- Client retries after timeout do not double charge.
- Missing key behavior matches docs.
These cases protect real money paths and are hard to cover thoroughly through UI alone.
Versioning and Breaking Changes
If your API uses /v1 and /v2 or header versioning, include:
- Old clients still work on supported versions
- Deprecated fields remain until the documented sunset
- New required fields do not break old payloads unexpectedly
- Error bodies stay parseable across versions consumers still use
API testing is part of release governance, not only feature QA.
Observability Hooks for Better Failures
When tests fail, request correlation ids make debugging human.
Assert or log:
const requestId = res.headers()["x-request-id"];
console.log("requestId", requestId);
Store those ids in CI logs. Backend engineers can jump straight to matching server traces.
Sample Beginner Project Plan
Week 1:
- Choose one service
- Document five endpoints
- Manual happy paths in a client
Week 2:
- Add negative and auth cases
- Build CRUD matrix for one resource
Week 3:
- Automate top twenty checks
- Run in CI on each PR
Week 4:
- Add permission matrix
- Add one performance smoke threshold
- Review escaped defects and fill gaps
This plan creates durable skill, not only tool exposure.
Final Takeaway
This API testing tutorial should leave you with a clear method: learn the contract, design risk based cases, validate status and body and side effects, cover auth thoroughly, automate the stable core, and run it in CI. Functional correctness comes first. Non-functional and contract depth follow as the system and team mature.
Master the service layer and you will find higher severity defects earlier, with less flake and more confidence than UI only strategies can provide. Use tools as accelerators. Let checklist discipline and business risk decide what deserves coverage.
FAQ
Questions testers ask
What is API testing and why is it important?
API testing verifies that application interfaces behave correctly at the service layer: status codes, payloads, auth, errors, and business rules. It is important because APIs power mobile apps, web frontends, and integrations, and failures there often break users before the UI can compensate.
How do you test REST APIs step by step?
Read the contract, set up environment and auth, send requests for each important endpoint and state, validate status codes and response bodies, check error handling and edge data, then automate stable checks in CI. Cover CRUD flows, permissions, and negative cases, not only happy paths.
What tools are used for API testing?
Common tools include Postman, Bruno, Insomnia, REST Assured, Playwright request, Supertest, Karate, JMeter or k6 for performance, and contract tools like Pact. Choose based on team skills, automation needs, and whether you need exploratory calls, coded suites, or load testing.
What is the difference between functional and non-functional API testing?
Functional API testing checks correctness: business rules, validation, responses, and authorization. Non-functional testing checks qualities such as performance, reliability, security hardening, and scalability. Most teams need both, but they use different techniques and tools.
Can API testing replace UI testing?
No. API testing is faster and more stable for business logic and integrations, but it cannot fully prove layout, client side workflows, or browser specific behavior. Use API tests as the backbone and keep a smaller set of critical UI journeys.
How many API test cases does a CRUD endpoint need?
A practical minimum covers create success, read success, update success, delete success, missing auth, invalid payload, not found ids, and permission denials. Add uniqueness conflicts, pagination, and idempotency where the contract requires them.
RELATED GUIDES
Continue the route
Postman Tutorial: UI, Collections, Environments, and Tests
Postman tutorial for beginners: learn the Postman UI, collections, environments, variables, Tests tab, pre-request scripts, Collection Runner, and Newman.
REST API Status Codes: The Complete Reference for Testers
Master REST API status codes with a complete tester cheat sheet for 2xx, 4xx, and 5xx responses, error validation, and practical test design.
How to Write API Test Cases
How to write API test cases with practical templates, CRUD examples, auth checks, negative paths, and a review checklist for reliable service coverage.
Contract Testing with Pact: Consumer-Driven Contracts
Learn contract testing with Pact, consumer-driven contracts, provider verification, Pact Broker flow, and how it differs from Postman and integration tests.
API Authentication Testing: OAuth, JWT, and API Keys
Learn API authentication testing for OAuth 2.0, JWT expiry and refresh flows, API keys vs bearer tokens, and broken authentication test cases.