Back to guides

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.

By The Testing AcademyPublished July 9, 2026Updated July 9, 202616 min read

"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 focusAPI case focus
Screens, widgets, navigationResources, methods, contracts
Visible labels and layoutStatus codes, schemas, fields
Browser stateAuth tokens, idempotency, data state
Click pathsPayload 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-100 exists with stock 10.
  • Auth token with role buyer is available.
  • No existing order with client reference ref-123 if 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-empty id, status=pending, quantity=2, and productId=sku-100. A subsequent GET /orders/{id} with the same token returns the same core fields. Inventory for sku-100 decreases 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.

FieldDescriptionExample
Test Case IDUnique idAPI-ORD-001
TitleBehavior under testCreate order with valid buyer payload
RequirementStory/contract refUS-441 / POST /orders
PriorityH/M/LHigh
TypePositive/negative/auth/boundaryPositive
EnvironmentTargetStaging
PreconditionsRequired stateBuyer token, sku-100 stock >= 2
MethodHTTP verbPOST
EndpointPath/api/v1/orders
HeadersKey headersAuthorization, Content-Type
Request bodyPayloadproductId, quantity, address
Expected statusCode201
Expected responseKey assertsid present, status pending
Side effectsFollow-up checksGET order, stock reserved
Actual resultRuntimeFilled during run
StatusPass/fail/blockedFilled during run
AutomationMapped script idorders.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

  1. Admin creates valid user.
  2. Create with duplicate email.
  3. Create with weak password.
  4. Create with missing email.
  5. Create without auth.
  6. Buyer tries to create user.
  7. User reads own profile.
  8. User reads another profile.
  9. Admin reads any profile.
  10. Get unknown user id.

Detailed Cases

IDTitleExpected statusKey expects
API-USER-001Admin creates valid user201id, email, role returned; password not returned
API-USER-002Duplicate email rejected409 or 400stable error code/message
API-USER-003Weak password rejected400validation details
API-USER-004Missing email rejected400validation details
API-USER-005No token rejected401no user created
API-USER-006Buyer forbidden to create403no user created
API-USER-007Self profile read200email matches
API-USER-008Horizontal access denied403/404no sensitive fields leaked
API-USER-009Admin read any200target email visible
API-USER-010Unknown id404error 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:

ActorActionResource ownerExpected
AnonymousGET invoiceany401
Buyer AGET invoiceBuyer A200
Buyer AGET invoiceBuyer B403/404
Buyer ARefund invoiceBuyer A403 if admin-only
AdminRefund invoiceany200/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:

  1. Login
  2. Create project
  3. Add member
  4. List members
  5. Remove member
  6. 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 typeExample
Statusexpect 201 on create
Body field equalityquantity equals request quantity
Body field presenceid is non-empty string
Body field absencepassword hash not returned
HeaderContent-Type includes application/json
Timeresponse under agreed budget
PersistenceGET returns created resource
Authzforeign access denied
Error shapeerror.code is VALIDATION_ERROR
Idempotencyreplay 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:

  1. Health/readiness returns 200.
  2. Login returns token.
  3. Create order valid returns 201.
  4. Get order by id returns 200 with matching fields.
  5. Create order without token returns 401.
  6. Get foreign order returns 403/404.
  7. 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

  1. When OpenAPI changes, search linked cases and update expectations.
  2. When a bug escapes, add a case before closing the incident.
  3. Delete obsolete cases for removed endpoints.
  4. Keep naming conventions: API-<RESOURCE>-<NNN>.
  5. 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:

  1. Pick one resource.
  2. Write 12 case titles covering positive, negative, and auth.
  3. Fully detail the three highest priority cases with payloads and expected codes.
  4. Implement those three in Postman or code.
  5. 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

  1. Read contract and story risks.
  2. Brainstorm scenarios broadly.
  3. Prioritize by user and business impact.
  4. Fill the API test case template with exact requests and expects.
  5. Add authn/authz and negative paths.
  6. Define smoke vs extended suites.
  7. Implement in Postman/code with stable data setup.
  8. Review with a developer for expected codes and side effects.
  9. Automate high-value cases in CI.
  10. 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.

CaseExpected HTTPExpected error code
Missing field400VALIDATION_ERROR
Unknown resource404NOT_FOUND
Duplicate email409CONFLICT
Wrong role403FORBIDDEN

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:

  1. First request with key k1 creates resource A.
  2. Replay with same key and same body returns A, not B.
  3. Replay with same key and different body returns a conflict error per design.
  4. 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 IDAutomate now?Reason
API-ORD-001YesSmoke critical
API-ORD-014LaterNeeds complex multi-service setup
API-ORD-022NoPure 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:

  1. Read one OpenAPI path together.
  2. Write five scenario titles only.
  3. Expand two into full cases.
  4. Implement one in Postman.
  5. Review expected codes with a developer.
  6. 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.