Step by Step Process to Write Test Cases for API Testing: A Practical Guide
Step by Step Process to Write Test Cases for API Testing
Introduction
Learn how to create effective API test cases, check responses, find errors, and test real-world API features with simple examples.
API testing is an important part of software development. It helps developers and testers find problems before an application reaches its users. A website might look perfect on the screen, but if its API fails to send or receive the correct data, the entire application can stop working properly.
That is why understanding the step by step process to write test cases for API testing matters.
A good API test case does more than check whether an endpoint returns a successful response. It examines the request, response data, authentication, error messages, and expected application behaviour.
The process becomes much easier when you know what to test, how to prepare the required data, and how to document the results.
Quick Facts About API Test Cases
| Topic | Details |
|---|---|
| Main purpose | Check API functionality, reliability, and security |
| Common API type | REST API |
| Request methods | GET, POST, PUT, PATCH, DELETE |
| Popular testing tools | Postman, REST Assured, pytest, Playwright |
| Important checks | Status code, response body, headers, data accuracy |
| Testing approaches | Positive, negative, boundary, security, performance |
| Common response format | JSON |
| Test case result | Pass, Fail, Blocked, or Not Run |
| Suitable for | QA testers, developers, automation engineers |
What Is an API Test Case?
An API test case is a documented set of instructions used to check whether an Application Programming Interface works as expected.
It describes the conditions under which an API should be tested, the input values used, and the response that should be returned.
For example, imagine an online shopping application with an API that retrieves customer information.
A tester sends a request containing a valid customer ID. The API should return the correct customer details.
But what happens if the customer ID does not exist? What if the request has no authentication token?
These situations need separate test cases.
A properly written test case helps a tester identify exactly what went wrong, making the problem easier for developers to investigate.
Why Writing Proper Test Cases Matters
API testing is not simply about sending a request and checking whether the server responds.
It is about confirming that the application behaves correctly in different situations.
Well-written API test cases help teams:
- Detect functional errors before software release.
- Check that an API returns accurate information.
- Identify invalid input handling problems.
- Confirm authentication and access permissions.
- Reduce repeated manual testing.
- Catch unexpected changes after software updates.
- Document expected behaviour for future testing.
They also make teamwork easier. When a test case has clear steps and expected results, another tester can execute it without asking for additional instructions.
Step 1: Understand the API Requirements
Before writing any test cases, understand what the API is supposed to do.
Start by reviewing the API documentation, functional requirements, and business rules.
You should identify the endpoint URL, request method, supported parameters, authentication mechanism, and expected response format.
For example:
Sample API endpoint:
GET https://api.example.com/v1/users/101
This endpoint represents an API that retrieves information about a user with ID 101.
Questions to answer before testing include:
- Does the endpoint require authentication?
- What happens when the user exists?
- What happens when the user does not exist?
- Which fields should appear in the response?
- Are some fields optional?
- Can users access another person’s information?
An OpenAPI specification, when available, can serve as a useful reference for endpoint definitions, parameters, request bodies, and responses.
Tip: Never assume how an API should behave just because another application uses similar endpoints. The actual requirements and API contract should determine the expected results.
Step 2: Identify the API Endpoints and Methods
The next step is to identify all endpoints that need testing.
An endpoint is a specific URL through which an application communicates with an API service.
Different HTTP methods perform different operations.
| HTTP Method | Main Purpose | Example |
|---|---|---|
| GET | Retrieve information | Get user details |
| POST | Submit or create data | Create a user |
| PUT | Replace a resource | Replace user details |
| PATCH | Partially modify a resource | Change an email address |
| DELETE | Remove a resource | Delete a user |
Suppose a user-management API provides these endpoints:
GET /users— retrieve users.GET /users/{id}— retrieve a particular user.POST /users— create a user.PATCH /users/{id}— update selected user fields.DELETE /users/{id}— remove a user.
Each endpoint needs its own collection of test cases.
For example, testing a GET request will be different from testing a POST request because their operations and expected responses are different.
Step 3: Define the Testing Scenarios
Once the endpoints are identified, decide which situations need testing.
This is one of the most important parts of the process.
A testing scenario describes a condition or behaviour that must be checked.
There are several types of scenarios.
Positive Testing
Positive testing checks whether the API works when valid information is provided.
Examples include retrieving an existing user, creating a record with valid details, and updating information using permitted values.
Negative Testing
Negative testing checks how the API responds to invalid information or unsupported operations.
Examples include submitting incomplete data, entering an invalid user ID, using expired credentials, and requesting a resource without permission.
Boundary Testing
Boundary testing examines values near the minimum or maximum limits accepted by an API.
Suppose a registration API accepts a username containing between 3 and 20 characters.
You could test usernames with 2, 3, 20, and 21 characters.
This helps identify errors at the edges of the accepted range.
Security Testing
Security testing checks whether an API protects sensitive information and prevents unauthorised operations.
Important areas include authentication, authorisation, input validation, and data exposure.
The OWASP Web Security Testing Guide provides established guidance for these areas.
Performance Testing
Performance testing checks how an API responds under different workloads.
It may involve response latency, throughput, concurrent users, error rates, or resource consumption.
A quick response-time assertion is useful, but proper load testing requires controlled conditions and meaningful performance targets.
Step 4: Prepare the Test Data
Good test cases require carefully selected test data.
Without appropriate data, even a correctly written test case may produce misleading results.
For a registration API, your testing data might include:
| Test Data | Example | Expected Behaviour |
|---|---|---|
| Valid email | user@example.com | Accepted |
| Invalid email | userexample.com | Validation error |
| Empty email | Empty string | Validation error |
| Missing email | Field omitted | Required-field error |
| Duplicate email | Previously registered address | Duplicate-record error |
| Maximum-length name | Name at accepted limit | Accepted |
| Excessively long name | Name above limit | Validation error |
The exact responses depend on the application’s specification.
Use fictional accounts and synthetic information rather than exposing real customer data.
It is also useful to prepare separate accounts with different roles, such as an administrator, regular user, and read-only user.
These accounts allow you to test permissions correctly.
Step 5: Create a Standard Test Case Format
A consistent template makes API testing easier to manage.
Every test case should contain enough information for another tester to execute it independently.
A useful template includes:
| Field | Description |
|---|---|
| Test Case ID | Unique identifier |
| Test Scenario | Behaviour being tested |
| Endpoint | API URL or path |
| HTTP Method | GET, POST, PUT, PATCH, DELETE |
| Preconditions | Requirements before execution |
| Test Data | Input and request parameters |
| Test Steps | Instructions for executing the test |
| Expected Result | Correct behaviour defined by requirements |
| Actual Result | Behaviour observed during testing |
| Status | Pass, Fail, Blocked, Not Run |
Example of a Written API Test Case
Test Case ID: API_USER_001
Test Scenario: Verify user details are returned for a valid user ID.
Endpoint: /v1/users/101
Method: GET
Preconditions:
- The API service is running.
- A user with ID 101 exists.
- The tester has valid credentials and permission to view the resource.
Test Steps:
- Open an API testing tool.
- Select the GET method.
- Enter the endpoint URL.
- Add the required authentication header.
- Send the request.
- Review the returned response.
Expected Result:
The API returns HTTP 200, provides valid JSON containing the requested user’s permitted fields, and matches the stored test data.
Actual Result: To be recorded during execution.
Test Status: Not Run.
This structure makes it clear what is being checked and how success will be measured.
Step 6: Check HTTP Status Codes
HTTP status codes tell the client what happened after a request was processed.
They are an important part of API testing, but a status code alone cannot prove that the returned information is correct.
Some commonly encountered status codes include:
| Status Code | Meaning | Typical Testing Situation |
|---|---|---|
| 200 | OK | Successful data retrieval |
| 201 | Created | Resource successfully created |
| 204 | No Content | Successful operation without response content |
| 400 | Bad Request | Invalid request |
| 401 | Unauthorized | Missing or invalid authentication |
| 403 | Forbidden | Access is not permitted |
| 404 | Not Found | Requested resource does not exist |
| 405 | Method Not Allowed | Unsupported method for the resource |
| 409 | Conflict | Request conflicts with existing resource state |
| 422 | Unprocessable Content | Semantically invalid request content |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Unexpected server-side failure |
Not every API uses every code. A specific API contract determines which response is correct for each scenario.
For example, a successful user-creation request commonly returns HTTP 201, while a successful DELETE request may return HTTP 204.
Test cases should check the exact behaviour promised by the API documentation.
Step 7: Validate the Response Body and Headers
A successful status code does not automatically mean the API is functioning properly.
Imagine that a request returns HTTP 200, but the customer’s name belongs to a different account.
The request succeeded at the HTTP level, but the application still has a serious problem.
That is why response validation matters.
For example, a user API might return:
{
"id": 101,
"name": "John Smith",
"email": "john@example.com",
"active": true
}
A tester should verify that:
- The returned ID matches the requested user.
- The name and email match the expected test data.
- Required fields are present.
- Each field has the correct data type.
- No unauthorised sensitive information is exposed.
- The response follows the documented JSON schema.
Response headers also matter.
For example, a JSON response commonly uses a Content-Type header indicating application/json.
Depending on the API requirements, other headers may relate to caching, rate limits, content security, or request tracing.
Step 8: Write Negative and Error-Handling Test Cases
Many beginners focus too heavily on successful requests.
But APIs must also handle unsuccessful requests correctly.
Consider a login API.
Testing a correct username and password is necessary, but it is only one scenario.
You should also test an incorrect password, a missing password, malformed input, an expired token, and requests made without credentials.
Here is an illustrative test-case matrix:
| Test ID | Scenario | Expected Result |
|---|---|---|
| API_001 | Login with valid credentials | Authentication succeeds |
| API_002 | Login with incorrect password | Authentication is rejected |
| API_003 | Login without password | Validation error |
| API_004 | Access protected endpoint without token | HTTP 401 |
| API_005 | Access another user’s restricted resource | Access denied |
| API_006 | Request nonexistent resource | HTTP 404 where specified |
| API_007 | Submit unsupported request method | HTTP 405 where applicable |
The expected status of incorrect login credentials varies by endpoint and contract.
A well-designed API should return useful error information without exposing confidential server details, passwords, tokens, or internal system information.
Step 9: Execute the Test Cases Using Postman
Postman is a widely used tool for sending API requests, viewing responses, and executing automated assertions.
It is especially useful for beginners because requests can be configured without creating an entire test framework.
Here is a simple practical workflow.
First, create a request.
Open Postman, create an HTTP request, select GET, and enter the endpoint:
https://api.example.com/v1/users/101
This is an illustrative address, not a live testing endpoint.
Next, configure authentication.
Select the required authentication type and use an approved test token or credentials.
Then, send the request.
Examine its status code, response body, headers, and response time.
Finally, write assertions.
In Postman’s Scripts → Post-response tab, add:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Response contains correct user ID", function () {
const data = pm.response.json();
pm.expect(data.id).to.eql(101);
});
pm.test("Response contains an email field", function () {
const data = pm.response.json();
pm.expect(data).to.have.property("email");
});
pm.test("Response time is within target", function () {
pm.expect(pm.response.responseTime).to.be.below(2000);
});
This script checks the response status, user ID, email property, and latency.
The 2,000-millisecond threshold is only an example. Your real threshold should come from documented performance requirements.
Postman displays the results of these assertions after execution, helping testers identify failed conditions.
Step 10: Check Authentication and Authorisation
Authentication and authorisation are different, and both require testing.
Authentication confirms who is making a request.
Authorisation determines which resources and operations that requester is allowed to access.
An API may correctly require users to log in but still allow them to read another user’s private records.
This is an authorisation problem.
To test access restrictions, create separate test accounts and verify that each account can perform only its permitted actions.
For example, a regular user might be allowed to view their own account information but not modify an administrator’s settings.
Include cases covering missing tokens, invalid tokens, expired tokens, insufficient permissions, and attempts to access another user’s resources.
Security testing should be performed against systems you own or are authorised to test.
Step 11: Automate Repetitive Test Cases
Manual testing is useful during initial development and investigation.
However, repeating dozens or hundreds of test cases after every code update can become time-consuming.
Automation helps teams execute consistent checks more frequently.
Common automation options include:
- Postman: JavaScript assertions and collection runs.
- REST Assured: REST API testing in Java.
- pytest: Python-based API test automation.
- Playwright: HTTP API testing using its API request capabilities.
- Newman or Postman CLI: Running suitable Postman test collections from command-line workflows.
Automated API tests can be included in continuous integration pipelines.
For example, when developers submit new code, a test pipeline can check important endpoints and report regressions before deployment.
Automation works best when test cases have reliable assertions, independent test data, and predictable environment conditions.
Step 12: Record Results and Report Defects
Writing the test case is only part of the job.
Once execution is complete, record what happened.
A test report should show which cases passed, failed, or could not be executed.
For failed cases, document the details developers need to reproduce the problem.
These may include the endpoint, HTTP method, sanitised request data, expected response, actual response, timestamp, environment, and relevant request identifier.
For example:
Defect ID: BUG_API_015
Issue: User endpoint returns the wrong email address.
Endpoint: GET /v1/users/101
Expected: Email matches the account’s verified test data.
Actual: Email belongs to another test account.
Severity: High, because the response may expose another user’s data.
After developers fix the defect, the affected test case should be executed again.
Regression testing can then confirm that the change has not damaged related functionality.
Complete API Testing Example: User Registration
To understand how these steps work together, consider a sample registration API.
Endpoint: POST /v1/users
Request body:
{
"name": "Sarah Khan",
"email": "sarah@example.com",
"password": "ExampleTestPassword123!"
}
The sample password is fictional and must not be used as a production credential.
Assume the API specification requires a unique email, a nonempty name, and a password that meets defined validation rules.
The following cases could be written:
| Test Case | Input | Expected Behaviour |
|---|---|---|
| Valid registration | All valid fields | User created; HTTP 201 |
| Duplicate email | Existing email | Duplicate registration rejected |
| Missing email | Email omitted | Validation error |
| Invalid email | Incorrect format | Validation error |
| Weak password | Password below requirements | Validation error |
| Missing name | Name omitted | Validation error |
| Excessive field length | Name exceeds maximum | Validation error |
| Unexpected extra field | Undocumented property | Handled according to contract |
After successful registration, the tester should also check that the account was stored correctly, that no password is returned in the response, and that duplicate submission does not create unintended records.
This example demonstrates why one successful POST request is not enough to establish that an endpoint works correctly.
Common Mistakes When Writing API Test Cases
Some testing mistakes repeatedly create problems for QA teams.
One is writing test cases without reviewing the requirements. That leads to incorrect expectations and unnecessary defect reports.
Another is checking only HTTP 200. The server may return a successful status while supplying inaccurate or incomplete information.
Poor test data also causes trouble. If a test depends on a record that another test has already deleted, its result may become unreliable.
Other common mistakes include ignoring access controls, combining too many behaviours into one test, using unstable response-time thresholds, and failing to record actual results.
Good test cases should remain clear, independent wherever practical, and easy to repeat.
Best Practices for Writing Better API Tests
The most useful API test cases share several characteristics.
They have descriptive names, defined inputs, clear expected results, and a direct connection to the requirement being tested.
When building a larger API test suite, apply these practices:
- Write separate tests for different behaviours.
- Cover successful, unsuccessful, and boundary scenarios.
- Validate response content, not just status codes.
- Check authentication and resource-level permissions.
- Use predictable, non-sensitive test data.
- Clean up test resources after execution when needed.
- Avoid dependencies between unrelated test cases.
- Keep automated assertions consistent with the API contract.
- Run important regression tests after changes.
- Review cases when the API specification changes.
A smaller collection of meaningful test cases is often more valuable than hundreds of repetitive tests that check very little.
Final Thought
Writing API test cases becomes easier when you follow a clear process.
Start with the API requirements. Identify the endpoints, prepare meaningful test data, define the scenarios, and document the expected results.
Then execute the tests, check more than just the HTTP response code, and report unexpected behaviour clearly.
The real purpose of API testing is not to produce a long test-case spreadsheet. It is to establish whether an API behaves correctly, protects information, and supports the application that depends on it.
A good test case answers three questions: What are we testing? What should happen? What actually happened?
When those answers are clear, the testing process becomes far more useful.
Frequently Asked Questions
1. What is the first step in writing API test cases?
The first step is understanding the API requirements. Review the endpoints, HTTP methods, accepted inputs, authentication rules, and expected responses before writing tests.
2. How do beginners write API test cases?
Beginners can start with one endpoint, define a valid request, document the expected result, and execute it using Postman. They should then add invalid-input and error-handling cases.
3. What should an API test case contain?
An API test case should contain a unique ID, scenario, endpoint, method, preconditions, test data, execution steps, expected result, actual result, and execution status.
4. Which tool is best for writing API test cases?
Postman is a practical starting point because it allows testers to send requests and write assertions in one interface. REST Assured, pytest, and Playwright are also useful, depending on the programming language and project requirements.
5. What is the difference between positive and negative API testing?
Positive testing checks whether an API works with valid inputs. Negative testing checks how it behaves when inputs, credentials, or operations are invalid.
6. Can API test cases be automated?
Yes. API tests can be automated with frameworks and testing tools. Automated test suites are often run as part of continuous integration workflows to detect regressions.
7. Is checking the status code enough for API testing?
No. A complete test may also need to check response fields, data types, headers, permissions, business rules, and changes made to stored data.
8. How many test cases are needed for one API?
There is no fixed number. The required coverage depends on the endpoint’s complexity, business rules, security risks, and possible input combinations.



