Testsigma Agentic Test Automation Tool

Products

Solutions

Resources

AI agentsDocsPricing

Test Cases for API Testing – How to Write & Example

API test cases are structured test scenarios that validate whether an API endpoint returns the correct HTTP status code, response body, headers, and error messages for a given input. A complete API test case specifies the HTTP method (GET, POST, PUT, DELETE), endpoint URL, request headers, request body, and expected response, covering functional, security, performance, and regression scenarios. Whether you're verifying a 201 on a successful creation or asserting a 403 on an unauthorized request, well-defined test cases ensure your API behaves exactly as intended.

Ritika Kumari
Written by
reviewed-by-icon
Testers Verified
Last update: 25 Sept 2026
HomeBlogTest Cases for API Testing – How to Write & Example

Key Takeaways

  • An API test case documents a specific condition to verify: HTTP method, endpoint URL, request payload, and the expected response.
  • The API testing market was valued at $2.32 billion in 2024 and is projected to reach $10.59 billion by 2032 at a 20.9% CAGR (SNS Insider, 2025).
  • The average application today uses 26 to 50 APIs to function; a single failing API can cascade into a broken user experience (Postman State of the API, 2024).
  • 6 categories of API test cases to cover: Functional, Security, Performance, Regression, Usability, and Compliance.
  • The most critical API test: status code verification. Every endpoint must return the correct 2xx/4xx/5xx code for every scenario.
  • Testsigma enables codeless API test case creation. Import Postman/Swagger collections, generate tests from API specs with AI, and run them in CI/CD without writing a line of code.

What Are API Test Cases?

An API (Application Programming Interface) is the communication layer between software services. It allows a frontend application, mobile app, or third-party service to request data or trigger actions from a backend system.

API test cases are documented scenarios that validate this communication. Each test case sends a specific HTTP request to an API endpoint and verifies that the response matches expected behavior across four dimensions:

DimensionWhat It Validates
Status CodeDid the server respond correctly? (200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Internal Server Error)
Response BodyDoes the response JSON/XML contain correct fields, data types, and values?
Response HeadersAre Content-Type, Authorization, and other headers present and correct?
Response TimeDid the server respond within the acceptable performance threshold?

Import your Postman collections or Swagger specs and generate API test cases with AI, no code required.

Why Are API Test Cases Important?

The scale of modern API usage makes thorough API testing non-negotiable:

  • The average modern application uses 26 to 50 APIs to function (Postman State of the API, 2024). If one fails, it can cascade across the entire app.
  • The API testing market was valued at $2.32 billion in 2024, growing at 20.9% CAGR to reach $10.59 billion by 2032 (SNS Insider, 2025), reflecting how critical API quality has become.
  • 83% of all public APIs use REST API testing architecture as of 2024 (RapidAPI Developer Survey).
  • 39% of developers cite inconsistent API documentation as their biggest collaboration obstacle (Postman State of the API, 2024).
  • APIs are tested before the UI exists. API test cases catch bugs at a fraction of the cost, with defects found in production costing significantly more than those caught during development (IBM Systems Sciences Institute).

Why API test cases specifically (vs. exploratory testing):

  • Repeatability: Documented test cases produce the same steps and checks on every run, so any change in API behavior shows up immediately as a regression.
  • Coverage: A systematic approach makes sure every endpoint is checked across HTTP methods, expected status codes, error responses, and edge cases like empty payloads or invalid auth tokens.
  • Earlier bug detection: Catching API defects during development is far cheaper than fixing them after release, when they may already affect integrations, clients, and end users.
  • CI/CD readiness: Well-defined test cases convert easily into automated suites that run on every commit or pull request, blocking broken builds before they merge.
  • Living documentation: Test cases show exactly how the API is expected to behave, giving developers and new team members an up-to-date reference that stays in sync with the code.

What is the Standard API Test Case Format?

A well-structured API test case contains nine fields. Use this as your baseline template for every API test:

FieldDescriptionExample
Test Case IDUnique identifierTC_API_001
Test Case TitleDescriptive nameVerify GET /users returns 200 with user list
DescriptionWhat is being validatedChecks that the users endpoint returns a valid list with all required fields
PreconditionsSetup requirementsAPI server running; test database populated with 5 users
HTTP MethodRequest typeGET
Endpoint URLFull request URLhttps://api.example.com/v1/users
HeadersRequest headersContent-Type: application/json, Authorization: Bearer {token}
Request BodyPayload (POST/PUT/PATCH/DELETE){“name”: “Test User”, “email”: “test@example.com”}
Expected Status CodeHTTP response code200 OK
Expected Response BodyJSON/XML structure expected[{“id”: 1, “name”: “…”, “email”: “…”}]
Expected HeadersResponse headers expectedContent-Type: application/json
Actual ResultFilled during execution
Pass/FailBased on expected vs actualPass / Fail
NotesDependencies or observationsDepends on TC_API_000 (auth token setup)

How Do You Write API Test Cases Step by Step?

Here’s a step-by-step process for writing structured, reliable API test cases from scratch.

Step 1: Understand the API Specification

Before writing a single test case, read the API documentation (OpenAPI/Swagger, Postman collection, or internal specs). Identify every endpoint, HTTP method, required parameters, authentication mechanism, and expected responses for both success and error scenarios.

Step 2: Define What to Test First

Prioritize in this order:

  • Happy path: valid inputs producing successful responses (200, 201)
  • Negative cases: invalid inputs producing the correct error responses (400, 401, 403, 404)
  • Boundary conditions: values at the edge of allowed ranges
  • Security: authentication bypass attempts, injection payloads
  • Performance: response time under load

Step 3: Use a Consistent Naming Convention

Test case titles should follow: [HTTP Method] [Endpoint] [Scenario]

Examples:

  • GET /users – Returns 200 with valid auth token
  • POST /users – Returns 400 for missing required email field
  • DELETE /users/{id} – Returns 404 for non-existent user ID

Step 4: Write the Test Case Using the 9-Field Format

Fill in all 9 fields for every test case. Leave no field empty. “Preconditions” is the most commonly skipped field and the most common cause of environment-related failures.

Step 5: Cover All HTTP Status Code Categories

For every endpoint, write at least one test case for each applicable status code category:

Status Code CategoryExample CodesTest Scenario
2xx Success200, 201, 204Valid request producing correct success response
4xx Client Error400, 401, 403, 404, 409, 422, 429Invalid/missing input, unauthorized access, resource not found
5xx Server Error500, 502, 503Server-side failures, gateway errors

Step 6: Parameterize for DATA-Driven Coverage

Instead of writing separate test cases for each user type, parameterize with a data table:

UsernamePasswordExpected StatusExpected Response
valid@test.comGoodPass1!200{“token”: “…”}
invalid@test.comWrongPass401{“error”: “Invalid credentials”}
(empty)GoodPass1!400{“error”: “Email is required”}
valid@test.com(empty)400{“error”: “Password is required”}

Step 7: Integrate into CI/CD

Automate your API test cases and trigger them on every pull request. API tests are fast (50 to 200 tests per minute depending on complexity), so there is no reason to run them only on a schedule. Learn more about how testing fits into your CI/CD pipeline to get the most out of automation.

Validate API status codes, headers, and response bodies with codeless assertions.

What Are the 6 Categories of API Test Cases?

Every API test case falls into one of six categories, each targeting a different layer of API reliability.

Category 1: Functional API Test Cases

Functional API testing verifies that each endpoint does exactly what it is supposed to do.

Test Case IDTitleMethodEndpointExpected StatusExpected Result
TC_FUNC_001Valid GET returns 200 with all usersGET/users200JSON array of user objects with id, name, email fields
TC_FUNC_002POST creates new user, returns 201POST/users201Created user object with new id; Location header present
TC_FUNC_003PUT updates existing user, returns 200PUT/users/1200Updated user object with new field values
TC_FUNC_004PATCH partially updates user, leaves other fields unchangedPATCH/users/1200Only specified fields updated; other fields unchanged
TC_FUNC_005DELETE removes user, returns 204DELETE/users/1204No response body; user no longer retrievable
TC_FUNC_006GET returns 404 for non-existent resourceGET/users/99999404{“error”: “User not found”}
TC_FUNC_007Response body contains all required fieldsGET/users/1200id, name, email, created_at fields all present
TC_FUNC_008Response data types are correctGET/users/1200id is integer, name and email are strings
TC_FUNC_009CRUD end-to-end flow works in sequencePOST, GET, PUT, DELETE/users201, 200, 200, 204Each operation succeeds; data reflects each change

Category 2: Security API Test Cases

Security tests verify that the API correctly enforces authentication, authorization, and input validation.

Test Case IDTitleMethodScenarioExpected StatusExpected Result
TC_SEC_001Request with no auth token returns 401GETNo Authorization header401{“error”: “Unauthorized”}
TC_SEC_002Request with expired token returns 401GETExpired Bearer token401{“error”: “Token expired”}
TC_SEC_003User A cannot access User B’s private dataGETValid token for User A; request /users/B403{“error”: “Forbidden”}
TC_SEC_004SQL injection in request parameter is rejectedGET/users?id=1′ OR ‘1’=’1400Error or empty result; no SQL data leaked
TC_SEC_005XSS payload in request body is sanitizedPOST{“name”: “”}400 or 201Script tags stripped or rejected
TC_SEC_006Sensitive data is not exposed in error messagesGET/users/invalid404No stack trace, DB connection strings, or internal paths
TC_SEC_007Rate limiting returns 429 after thresholdGET200+ requests in 1 minute429{“error”: “Too many requests”} with Retry-After header
TC_SEC_008Data transmitted via HTTPS onlyGETHTTP (non-secure) request301 or connection refusedRedirected to HTTPS or rejected
TC_SEC_009API key or token not exposed in responsesGETAny authenticated request200Response body contains no auth credentials

Category 3: Performance API Test Cases

API performance testing verifies that the API responds within acceptable time thresholds under normal and peak loads.

Test Case IDTitleConditionMetricPass Threshold
TC_PERF_001Response time under normal load1 concurrent userTime to first byte< 200ms
TC_PERF_002Response time under moderate load50 concurrent usersAverage response time< 500ms
TC_PERF_003Response time under peak load500 concurrent users95th percentile response time< 2000ms
TC_PERF_004Throughput measurement60 secondsRequests per second≥ 100 RPS
TC_PERF_005Scalability under increasing load100, 500, 1000 usersDegradation rate< 20% increase in response time
TC_PERF_006Stress test to find breaking pointContinuously increase loadError rate threshold< 1% error rate at target load
TC_PERF_007Rate limit header present in responsesAny requestX-RateLimit-* headersPresent and accurate

Category 4: Regression API Test Cases

Regression tests ensure that new code changes do not break existing API behavior.

Test Case IDTitleVerification Approach
TC_REG_001Existing endpoints return same response schema after updateCompare JSON schema of responses before and after deployment
TC_REG_002New API version does not break v1 consumersRun v1 test suite against new build
TC_REG_003All functional tests pass after code changeRe-execute TC_FUNC_001 through TC_FUNC_009
TC_REG_004API integrations with dependent services still workEnd-to-end integration test across service boundaries
TC_REG_005Automated regression suite completes without new failuresRun full automated suite; 0 new failures introduced

Category 5: Usability API Test Cases

Test Case IDTitleWhat to Check
TC_USE_001API documentation matches actual behaviorSend requests as documented; verify documented responses match actual
TC_USE_002Consistent naming conventions across endpointsAll endpoints use the same naming style (snake_case, camelCase)
TC_USE_003Error messages are actionableError responses include field name and specific issue
TC_USE_004API is easy to integrate (clear auth flow)Complete auth to first successful request in < 5 minutes

Category 6: Compliance API Test Cases

Test Case IDTitleStandardWhat to Check
TC_COMP_001PII data masked in logsGDPR / HIPAARequest/response logs do not contain full SSN, passwords, card numbers
TC_COMP_002Data retention policy enforced via APIGDPR Article 17DELETE endpoint actually removes data from persistence layer
TC_COMP_003API requires consent for data collectionGDPRRelevant endpoints check for user consent before processing
TC_COMP_004Audit log records all data accessSOC 2 / HIPAAEvery GET on sensitive resource creates an audit log entry

What Does a Complete API Test Case Template Look like?

Here are two ready-to-use API test case templates you can copy and adapt for your own projects.

Example: Google Oauth Login API Test Case

The following 3-case table covers a common real-world scenario, testing third-party authentication:

Sl.NoTest Case TitlePriorityHTTP MethodEndpointRequest PayloadExpected StatusExpected ResponsePass/Fail
TC_API_001Login with valid Google credentialsHighPOST/auth/google{“token”: “<valid_google_token>”}200{“access_token”: “…”, “user”: {“id”: …, “email”: “…”}}–
TC_API_002Login with invalid/expired Google tokenHighPOST/auth/google{“token”: “<expired_token>”}401{“error”: “Invalid or expired token”}–
TC_API_003Login without providing a tokenHighPOST/auth/google{}400{“error”: “token is required”}–

Example: Response Header Validation Test Case

FieldValue
Test Case IDTC_API_010
TitleVerify Content-Type header is application/json for GET /users
MethodGET
Endpoint/users
Headers (Request)Authorization: Bearer {valid_token}
Expected Status200
Expected Response HeaderContent-Type: application/json; charset=utf-8
Expected BodyJSON array of user objects
Pass CriteriaStatus is 200 AND Content-Type header matches exactly

Download the full template: API Testing Test Case Template (Google Sheets)

How Do You Automate API Test Cases with Testsigma?

Testsigma provides a codeless API testing platform that lets you create, execute, and manage API test cases without writing code. It integrates directly with Postman collections, Swagger/OpenAPI specs, and CI/CD pipelines.

Documentation:

  • Getting Started: Automate REST APIs
  • REST API Test Step Type
  • API Request Configuration

Step 1: Log in and Open Test Management

Log in to app.testsigma.com. Navigate to the Test Cases tab and create a new folder named for your API (e.g., “User Authentication API”).

Step 2: Generate API Test Cases Using AI (generator Agent)

Click Ask AI and provide a prompt describing your API:

  • “Generate test cases for a login API that accepts email and password via POST /auth/login”
  • “Generate test cases for the GET /users endpoint including 200, 401, and 404 scenarios”

Alternatively, import directly from:

  • Postman: export collection as JSON and upload to Testsigma
  • Swagger/OpenAPI: upload your .yaml or .json spec file
  • Jira: generate test cases from linked requirements

Step 3: Create an API Test Case Manually

For custom test cases, click Create Test Case and choose Step Type: REST API.

Enter:

  • Title (e.g., “GET /users – Returns 200 with valid token”)
  • HTTP Method: select from GET, POST, PUT, PATCH, DELETE
  • Endpoint URL (e.g., https://api.example.com/v1/users)
  • Headers: add key-value pairs (Authorization: Bearer {{auth_token}})
  • Request Body: for POST/PUT/PATCH, enter JSON payload
  • Assertions: add codeless verifications such as Status Code = 200, Response Body contains “id”, Content-Type header = application/json

Step 4: Add Assertions for Each Validation Point

In Testsigma, assertions validate the response without any code. Click Add Verification and configure:

Assertion TypeExample
Status CodeExpected: 200
Response Body (Contains Field)data[0].id exists
Response Body (Field Value)data[0].email equals “test@example.com”
Response HeaderContent-Type equals application/json
Response TimeLess than 500ms
JSON SchemaUpload expected schema file

Step 5: Create a Test Run and Execute

Navigate to Test Runs, then Create Test Run. Select your API test cases and click Execute with Atto.

Atto (Testsigma’s execution AI agent) executes each test, validates assertions automatically, and generates results with:

  • Pass/Fail status per assertion
  • Full request and response logs
  • Response time metrics
  • AI-generated failure analysis with suggested fixes

Step 6: Integrate with CI/CD

Trigger API test runs automatically from Jenkins, GitHub Actions, Azure DevOps, or CircleCI. Testsigma provides REST API and webhook triggers to start runs from your pipeline.

Example GitHub Actions trigger:

- name: Run API Test Suite
  run: |
    curl -X POST "https://app.testsigma.com/api/v1/execution_results" \
      -H "Authorization: Bearer ${{ secrets.TESTSIGMA_API_KEY }}" \
      -d '{"test_plan_id": "123"}'

Testsigma Automated API Testing: testsigma.com/automated-api-testing

Run your full API test suite on every commit with built-in CI/CD triggers.

What Are Generic API Test Cases Every API Should Have?

Regardless of your application, these test cases apply to virtually every REST API:

  • Validate API keys for minimum and maximum length/range
  • Verify JSON and XML response formats match the API contract testing
  • Validate JSON schema, correct field types, and mandatory fields present
  • Verify response headers match expected Content-Type, Cache-Control, and CORS headers
  • Validate HTTP status codes for all major success and error scenarios
  • Test request chaining with multiple APIs working together in sequence
  • Verify CRUD operations end-to-end (Create, Read, Update, Delete)
  • Test boundary values, maximum/minimum allowed parameter values
  • Test for empty, null, and missing required parameters
  • Verify database integrity and data persisted correctly after write operations
  • Validate error messages are descriptive and actionable
  • Test file upload endpoints if applicable
  • Verify rate limiting is enforced and documented correctly
  • Test pagination with correct page sizes, page counts, and navigation

Conclusion

API test cases are the foundation of reliable software. When every endpoint is validated for correct status codes, response bodies, headers, and error handling across functional, security, performance, regression, usability, and compliance scenarios, you catch defects early, ship faster, and protect the user experience.

The key is consistency: use a standardized test case format, cover all six categories, automate everything, and run your suite on every commit. Start with the test cases and templates in this guide, then scale with automation as your API surface grows.

FAQs

What is an API test case?

An API test case is a documented scenario that specifies the HTTP method, endpoint URL, request details, and expected response to validate a specific API behavior. It covers both success and failure scenarios.

What are the most important API test cases to write?

Status code verification, authentication tests, CRUD end-to-end tests, and negative tests for invalid inputs are the most critical. These four categories catch the majority of API defects early.

How do you write a good API test case?

Use a descriptive title following [HTTP Method] [Endpoint] [Scenario] and fill in all 9 standard fields including preconditions and expected response. Each test case should validate exactly one behavior and cover both positive and negative paths.

What is the difference between API testing and UI testing?

API testing validates the communication layer directly by sending HTTP requests, making it faster and more stable than UI testing. UI testing validates the full user experience through a browser or app and is best reserved for end-to-end workflow validation.

How do I automate API test cases?

Import your API spec into a tool like Postman, REST Assured, or Testsigma, then add assertions for status codes, response fields, and headers. Integrate the suite into your CI/CD pipeline so tests run automatically on every commit.

Written By

Ritika Kumari

Testsigma Author - Ritika Kumari

Ritika Kumari

A writer for 4+ years with QA and Engineering background, I have always liked to blend creativity with technology. Although my experience plays an important role in making every article ‘my own piece of work,’ I believe writing is a never-ending learning process where I am still a student. Besides creating content, I try to read every book there ever existed and travel to places that are within reach (for now).

Published on: 19 Apr 2023

RELATED BLOGS