GUIDE / api
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.
"Test the orders endpoint" is not a case; it is a wish. How to write API test cases turns vague coverage into precise checks for status codes, payloads, authorization, validation, and side effects that any competent tester or script can execute.
This guide gives you a complete method: read the contract, identify scenarios, prioritize risk, write a reusable template, cover CRUD and negatives, handle auth, chain flows, review coverage, and implement cases in tools like Postman or code. For general test case craft, see how to write test cases. For service-layer fundamentals, see the API testing tutorial.
What Is an API Test Case?
An API test case documents one verifiable behavior of a service interface. It usually includes:
- What request to send (method, path, headers, body, query)
- Under what conditions (auth, existing data, feature flags)
- What should happen (status, body, headers, side effects)
Example one-liner title:
Verify that an authenticated buyer can create an order with a valid product and quantity and receives 201 with an order id.
That title already beats "Test create order."
Why API Test Cases Need Their Own Discipline
API testing inherits classic design skills, but the details differ from UI cases:
| UI case focus | API case focus |
|---|---|
| Screens, widgets, navigation | Resources, methods, contracts |
| Visible labels and layout | Status codes, schemas, fields |
| Browser state | Auth tokens, idempotency, data state |
| Click paths | Payload matrices and role matrices |
If you only copy UI case style into API work, you may under-specify headers, codes, and persistence checks.
Step-by-Step: How to Write API Test Cases
Step 1: Gather the Contract Inputs
Collect whatever exists:
- OpenAPI or Swagger
- Story acceptance criteria
- Sequence diagrams
- Example curl or Postman snippets
- Error catalog
- Auth model (API key, JWT, OAuth)
Highlight:
- Resources and path parameters
- Required vs optional fields
- Enums and formats
- Auth requirements
- Expected status codes
- Side effects (email, inventory, ledger)
When the contract is incomplete, write questions as draft cases marked blocked until clarified.
Step 2: List Scenarios Before Writing Details
Scenarios are ideas. Cases are precise executions.
For POST /api/v1/orders:
- Create order with valid payload.
- Reject order with missing product id.
- Reject quantity zero.
- Reject negative quantity.
- Reject unauthenticated request.
- Reject user creating order for another customer id if forbidden.
- Create order for out-of-stock product according to business rule.
- Verify created order can be fetched by id.
- Verify list endpoint includes the new order.
This brainstorm prevents happy-path tunnel vision.
Step 3: Prioritize by Risk
Not every scenario needs equal depth.
High priority usually includes:
- Money movement
- Auth and permission boundaries
- Data loss or corruption risks
- Core create/read journeys
- Known production incident areas
Medium priority:
- Validation messages wording
- Optional field combinations
- Sorting defaults
Low priority:
- Cosmetic error text differences
- Rare admin-only formatting preferences
Priority drives what enters smoke suites versus extended regression.
Step 4: Define Preconditions and Data
API cases fail noisily when data is wrong.
Examples of preconditions:
- Buyer account exists and is active.
- Product
sku-100exists with stock 10. - Auth token with role
buyeris available. - No existing order with client reference
ref-123if uniqueness is required.
Name data explicitly. "Valid product" is weaker than productId: sku-100.
Step 5: Specify the Request Precisely
Include:
- Base URL or environment
- Method and path
- Path/query params
- Headers
- Body
- Auth mechanism
POST {{baseUrl}}/api/v1/orders
Authorization: Bearer {{buyerToken}}
Content-Type: application/json
{
"productId": "sku-100",
"quantity": 2,
"shippingAddressId": "addr_9"
}
Step 6: Write Expected Results That Are Observable
At minimum:
- Expected status code
- Critical response fields
- Important headers if part of contract
- Follow-up side effect checks
Better expected result:
Returns
201 Created. Body includes non-emptyid,status=pending,quantity=2, andproductId=sku-100. A subsequentGET /orders/{id}with the same token returns the same core fields. Inventory forsku-100decreases by 2 if the business reserves stock on create.
Avoid: "Works fine."
Step 7: Add Traceability
Link cases to:
- User story ids
- OpenAPI operation ids
- Risk ids
- Production bug ids
Traceability makes impact analysis possible when the contract changes.
Step 8: Review and Split
Split cases when one script tries to prove create, tax calculation, loyalty points, email delivery, and admin audit logs at once. Keep end-to-end API journeys, but label them as flows. Keep atomic cases for diagnosis.
API Test Case Template
Use this table format in TestRail, Xray, Google Sheets, or markdown.
| Field | Description | Example |
|---|---|---|
| Test Case ID | Unique id | API-ORD-001 |
| Title | Behavior under test | Create order with valid buyer payload |
| Requirement | Story/contract ref | US-441 / POST /orders |
| Priority | H/M/L | High |
| Type | Positive/negative/auth/boundary | Positive |
| Environment | Target | Staging |
| Preconditions | Required state | Buyer token, sku-100 stock >= 2 |
| Method | HTTP verb | POST |
| Endpoint | Path | /api/v1/orders |
| Headers | Key headers | Authorization, Content-Type |
| Request body | Payload | productId, quantity, address |
| Expected status | Code | 201 |
| Expected response | Key asserts | id present, status pending |
| Side effects | Follow-up checks | GET order, stock reserved |
| Actual result | Runtime | Filled during run |
| Status | Pass/fail/blocked | Filled during run |
| Automation | Mapped script id | orders.create.valid |
Copy-friendly text version:
Test Case ID:
Title:
Requirement Reference:
Priority:
Type:
Preconditions:
Auth Context:
Method:
Endpoint:
Query Params:
Headers:
Request Body:
Expected Status:
Expected Response:
Side Effect Checks:
Notes:
Automation ID:
Worked Example: Users Resource Pack
Requirement sketch:
Admins can create users with email and role. Email must be unique. Password must meet policy. Non-admins cannot create users. Users can read their own profile. Admins can read any profile.
Scenario List
- Admin creates valid user.
- Create with duplicate email.
- Create with weak password.
- Create with missing email.
- Create without auth.
- Buyer tries to create user.
- User reads own profile.
- User reads another profile.
- Admin reads any profile.
- Get unknown user id.
Detailed Cases
| ID | Title | Expected status | Key expects |
|---|---|---|---|
| API-USER-001 | Admin creates valid user | 201 | id, email, role returned; password not returned |
| API-USER-002 | Duplicate email rejected | 409 or 400 | stable error code/message |
| API-USER-003 | Weak password rejected | 400 | validation details |
| API-USER-004 | Missing email rejected | 400 | validation details |
| API-USER-005 | No token rejected | 401 | no user created |
| API-USER-006 | Buyer forbidden to create | 403 | no user created |
| API-USER-007 | Self profile read | 200 | email matches |
| API-USER-008 | Horizontal access denied | 403/404 | no sensitive fields leaked |
| API-USER-009 | Admin read any | 200 | target email visible |
| API-USER-010 | Unknown id | 404 | error body consistent |
Notice password should not appear in responses. Security expectations belong in functional API cases, not only in a separate security backlog.
Designing CRUD API Test Cases
Create
- Valid payload
- Missing required fields
- Invalid types
- Boundary lengths
- Authn and authz failures
- Duplicate unique keys
- Read-after-write verification
Read
- Existing id
- Unknown id
- Invalid id format
- Auth matrix
- Field filtering if supported
- Performance budget smoke if critical
Update (PUT/PATCH)
- Valid partial/full update
- No-op update
- Invalid transitions (for example, terminal status changes)
- Updating immutable fields
- Concurrent update conflict if applicable
- Authz on foreign resources
Delete
- Delete existing
- Delete unknown
- Delete already deleted (idempotency expectations)
- Authz restrictions
- Dependent resource behavior (cascade vs block)
List
- Default pagination
- Custom page size
- Filters
- Sort order
- Empty lists
- Unauthorized list access
Negative and Boundary Techniques for APIs
Apply classic techniques with HTTP specifics.
Equivalence Style Groups
For quantity:
- Valid: 1 to maxAllowed
- Invalid low: 0, negative
- Invalid high: maxAllowed + 1
- Invalid type: "two", true, []
Boundary Values
If name length is 1 to 80:
- 0, 1, 80, 81 characters
- whitespace-only if not allowed
- unicode characters if product supports international text
Protocol Level Negatives
- Wrong
Content-Type - Malformed JSON
- Unsupported method
- Extra unexpected fields (if contract forbids them)
Document expected codes with developers. Do not invent 422 vs 400 alone if the contract is silent. Raise the question.
Authorization Case Design
Many severe API defects are authorization defects.
Build a matrix:
| Actor | Action | Resource owner | Expected |
|---|---|---|---|
| Anonymous | GET invoice | any | 401 |
| Buyer A | GET invoice | Buyer A | 200 |
| Buyer A | GET invoice | Buyer B | 403/404 |
| Buyer A | Refund invoice | Buyer A | 403 if admin-only |
| Admin | Refund invoice | any | 200/202 |
Write one case per high-risk cell, not one vague case called "check roles."
Chained Flow Cases vs Atomic Cases
Atomic Case
Verifies one behavior, easy to diagnose.
Example: missing token on create returns 401.
Flow Case
Sequences multiple calls:
- Login
- Create project
- Add member
- List members
- Remove member
- Delete project
Flows prove integration across endpoints. Keep a few critical flows, plus many atomic cases. If a flow fails at step 5, atomic coverage should help pinpoint whether remove member itself is broken.
From Cases to Execution Artifacts
Manual or Exploratory Execution Notes
Useful early in a feature when responses still move.
Postman Implementation
Each high-value case becomes a request plus Tests assertions. Variables store ids. Folders mirror packs. See the Postman tutorial.
Coded Tests
Represent cases as tests in REST Assured, Supertest, Playwright request, or similar. Reuse fixtures for auth and data factories.
Contract Tests
When consumer-provider alignment is the risk, complement functional cases with contract testing with Pact. Contract tests do not replace business rule cases.
Assertion Catalog You Can Reuse
| Assertion type | Example |
|---|---|
| Status | expect 201 on create |
| Body field equality | quantity equals request quantity |
| Body field presence | id is non-empty string |
| Body field absence | password hash not returned |
| Header | Content-Type includes application/json |
| Time | response under agreed budget |
| Persistence | GET returns created resource |
| Authz | foreign access denied |
| Error shape | error.code is VALIDATION_ERROR |
| Idempotency | replay returns same resource id |
Pick assertions that would catch a bug users care about.
Common Mistakes When Writing API Test Cases
Mistake 1: Title Without Behavior
Bad: "Orders API test 1"
Better: "Reject create order when quantity is zero with 400"
Mistake 2: Expected Result = "Success"
Success means different codes for different methods. Be explicit.
Mistake 3: Ignoring Side Effects
Create can return 201 while database write fails in broken systems. Read-after-write matters.
Mistake 4: No Auth Variants
One happy token is not coverage.
Mistake 5: Over-Specifying Unstable Fields
Exact timestamps or generated marketing copy can flake. Assert formats or presence when values are dynamic.
Mistake 6: Duplicating the Same Case in Five Tools
One source of truth for design, multiple execution bindings if needed.
Mistake 7: Never Updating Cases After Incidents
Every serious production API bug should produce or update a case.
Review Checklist for API Test Suites
- Critical resources have CRUD coverage.
- Each protected route has authn failure coverage.
- High-risk routes have authz matrix coverage.
- Validation negatives exist for required fields and core boundaries.
- Expected status codes are explicit and agreed.
- Side effects are verified where business value depends on them.
- Data preconditions are realistic and isolated.
- Smoke pack is identified and small enough for CI.
- Cases map cleanly to automation ids.
- Open questions are marked, not silently assumed.
Example Smoke Pack (Release Gate)
For an e-commerce API:
- Health/readiness returns 200.
- Login returns token.
- Create order valid returns 201.
- Get order by id returns 200 with matching fields.
- Create order without token returns 401.
- Get foreign order returns 403/404.
- Product list returns 200 with non-empty schema checks.
That pack will not catch everything. It will catch many "deploy is broken" moments quickly.
Example Extended Regression Additions
- Coupon application rules
- Tax calculation combinations
- Pagination edges
- Rate limit headers on sensitive routes
- Webhook signing for payment events
- Idempotency-key behavior on payment capture
For list endpoints, expand that bullet into concrete test API pagination coverage for page size, cursors, filters, and stable ordering.
Layer suites so not everything runs on every PR if time is tight. Keep risk-based selection conscious.
Translating Cases Into Postman Tests
Case API-ORD-001 becomes:
pm.test('status is 201', () => pm.response.to.have.status(201));
const json = pm.response.json();
pm.test('has id', () => pm.expect(json.id).to.be.a('string').and.not.empty);
pm.test('quantity persisted in response', () => pm.expect(json.quantity).to.eql(2));
pm.environment.set('orderId', json.id);
Then a second request implements the side-effect GET check. The written case remains the design authority when scripts drift.
Maintenance Rules
- When OpenAPI changes, search linked cases and update expectations.
- When a bug escapes, add a case before closing the incident.
- Delete obsolete cases for removed endpoints.
- Keep naming conventions:
API-<RESOURCE>-<NNN>. - Revisit priorities quarterly as traffic patterns change.
A stale suite is a liability. Maintenance is part of writing cases, not an afterthought.
Practice Exercise
Take any public practice API or your staging service and do this in 45 minutes:
- Pick one resource.
- Write 12 case titles covering positive, negative, and auth.
- Fully detail the three highest priority cases with payloads and expected codes.
- Implement those three in Postman or code.
- Run them and fix any false assumptions.
For more scenario reps, use QABattle and convert each challenge into formal API cases using the template above.
Final Workflow You Can Reuse
- Read contract and story risks.
- Brainstorm scenarios broadly.
- Prioritize by user and business impact.
- Fill the API test case template with exact requests and expects.
- Add authn/authz and negative paths.
- Define smoke vs extended suites.
- Implement in Postman/code with stable data setup.
- Review with a developer for expected codes and side effects.
- Automate high-value cases in CI.
- Update from incidents and contract changes.
If you remember one principle about how to write API test cases, remember this: a useful API case makes the request and the expected service outcome unambiguous to any competent tester or automation script. Clarity is the feature. Everything in the template exists to protect that clarity.
Writing API Test Cases for Error Catalogs
Mature APIs publish error codes such as VALIDATION_ERROR, NOT_FOUND, CONFLICT. Your cases should reference them.
| Case | Expected HTTP | Expected error code |
|---|---|---|
| Missing field | 400 | VALIDATION_ERROR |
| Unknown resource | 404 | NOT_FOUND |
| Duplicate email | 409 | CONFLICT |
| Wrong role | 403 | FORBIDDEN |
If error codes are undocumented, capture observed codes and push for documentation. Consistency in errors is part of product quality.
Versioning and Compatibility Cases
When APIs version via path (/v1, /v2) or headers, write cases that protect consumers:
- v1 behavior remains stable for supported window.
- Deprecated fields still work until sunset date.
- New required fields in v2 rejected appropriately when missing.
- Unknown fields policy is consistent.
Compatibility bugs are expensive because clients you do not control break silently.
Idempotency-Key Cases
For payment-like POSTs:
- First request with key
k1creates resource A. - Replay with same key and same body returns A, not B.
- Replay with same key and different body returns a conflict error per design.
- Different key creates a new resource.
These cases belong near the top of risk-ranked suites for financial flows.
Webhook and Callback Case Design
Even if delivery is asynchronous, you can still write cases:
- Given a triggering action, a webhook record is created with correct event type.
- Signature header validates with shared secret.
- Invalid signature is rejected.
- Duplicate delivery does not double-apply side effects.
Execution may involve test doubles or webhook inspection tools, but the case text stays valuable.
Collaborating With Developers on Expected Results
Ambiguity examples to resolve early:
- Is DELETE twice 404 or 204?
- Does GET hidden resource return 403 or 404?
- Are timestamps UTC ISO-8601 with Z?
- Is pagination 0-based or 1-based?
Write the decision into the case expected result. Silent assumptions become flakes and arguments later.
From Spreadsheet to Automation Backlog
Not every written case should be automated immediately.
Columns to add:
| Case ID | Automate now? | Reason |
|---|---|---|
| API-ORD-001 | Yes | Smoke critical |
| API-ORD-014 | Later | Needs complex multi-service setup |
| API-ORD-022 | No | Pure exploratory while rule unsettled |
This prevents automation backlogs full of low-value scripts.
Example: Full Case Narrative
Test Case ID: API-INV-017
Title: Buyer cannot download another buyer's invoice PDF metadata
Requirement Reference: SEC-AUTHZ-12
Priority: High
Type: Authorization negative
Preconditions:
- Buyer A and Buyer B exist
- Invoice inv_b1 belongs to Buyer B
Auth Context: Bearer token for Buyer A
Method: GET
Endpoint: /api/v1/invoices/inv_b1
Expected Status: 404 or 403 (confirm privacy policy)
Expected Response:
- No invoice totals or line items returned
- Error body follows standard envelope
Side Effect Checks:
- Access attempt is audit-logged if required by policy
Notes:
- Prefer 404 if product hides existence of foreign invoices
This is what strong API cases look like in real teams.
Teaching Juniors How to Write API Test Cases
Pairing outline:
- Read one OpenAPI path together.
- Write five scenario titles only.
- Expand two into full cases.
- Implement one in Postman.
- Review expected codes with a developer.
- Add the case id to CI smoke if critical.
Reps beat lectures. After three resources, juniors usually internalize the pattern of how to write API test cases without copying templates blindly.
Closing Addition
API test design is product risk design expressed as HTTP expectations. Keep cases precise, authorization-aware, and maintainable. If a new teammate can execute or automate your case without asking what "success" means, you wrote it well.
FAQ
Questions testers ask
What is an API test case?
An API test case is a documented check that specifies endpoint, method, preconditions, request data, auth context, expected status code, expected response body or headers, and any side effects to verify. It makes service behavior repeatable and reviewable.
How do you write API test cases from requirements?
Read the contract or story, list resources and rules, derive positive scenarios, add validation and authorization negatives, define exact payloads and expected codes, then map each case to automation or manual execution notes with traceability.
What should every API test case include?
Include id, title, priority, endpoint, method, auth, preconditions, request headers/body, expected status, expected key fields, side-effect checks, and references to requirements or risks. Consistency matters more than fancy formatting.
How many test cases does a CRUD API need?
A practical baseline covers create, read, update, delete success paths, missing auth, invalid payloads, not found ids, and forbidden roles. Add uniqueness conflicts, pagination, and idempotency where the contract requires them.
What is the difference between API test cases and Postman requests?
A test case is the designed expectation. A Postman request is one way to execute it. Good teams design cases first, then implement them as Postman tests, coded assertions, or both.
Should API test cases be automated?
Automate stable, high-value, repeatable cases, especially smoke and regression packs. Keep exploratory notes for unstable or newly discovered behavior until expectations are clear enough to codify.
RELATED GUIDES
Continue the route
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.
How to Write Test Cases: Complete Guide with Examples
Learn how to write test cases with practical steps, examples, a QA template, common mistakes, and review tips for reliable software coverage.
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.
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.
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.