10 Practical Script Examples for API Testing

Your lightweight Client for API debugging
No Login Required
Requestly is a web proxy that requires a desktop and desktop browser.
Enter your email below to receive the download link. Give it a try next time youâre on your PC!
API testing gets serious the moment you stop clicking buttons and start scripting real-world scenarios. If you’re working with any API client that supports pre request and post response scripts, you can automate validations, chain requests, mock edge cases, and catch bugs before they hit production.
Here are 10 practical script examples you can actually use in day-to-day API testing
1. Validate Status Code and Response Time
Always validate that your API responds correctly and within acceptable time.
rq.test("Status code is 200", () => {
rq.expect(rq.response.code).to.equal(200);
});
rq.test("Response time is under 500ms", () => {
rq.expect(rq.response.responseTime).to.be.lessThan(500);
});This is essential for login endpoints, health checks, and critical APIs.
2. Validate Required Fields in Response
Instead of manually checking fields, automate it.
const data = rq.response.json();
rq.test("Response contains required fields", () => {
rq.expect(data).to.have.property("id");
rq.expect(data).to.have.property("email");
rq.expect(data).to.have.property("name");
});This protects you from accidental backend changes.
3. Extract Auth Token and Store It
Most APIs require authentication. Store the token for later requests.
const body = rq.response.json();
rq.environment.set("authToken", body.token);
rq.test("Token saved successfully", () => {
rq.expect(rq.environment.get("authToken")).to.be.ok;
});
Then use {{authToken}} in your Authorization header for subsequent requests.
4. Ensure Fields Are Not Empty
Sometimes fields exist but contain empty values.
const data = rq.response.json();
rq.test("Email is not empty", () => {
rq.expect(data.email).to.be.a("string").and.not.be.empty;
});
rq.test("Name is not empty", () => {
rq.expect(data.name).to.be.a("string").and.not.be.empty;
});Useful for profile and checkout validations.
5. Validate Array Length
If an endpoint returns a list, confirm it contains data.
const list = rq.response.json();
rq.test("At least one item returned", () => {
rq.expect(list.length).to.be.greaterThan(0);
});Important for search and listing APIs.
6. Conditional Testing Based on Response Data
Sometimes validation depends on the role or type returned.
const data = rq.response.json();
if (data.role === "admin") {
rq.test("Admin has permissions array", () => {
rq.expect(data.permissions).to.be.an("array");
});
}
This helps validate role based access logic.
7. Negative Testing for Invalid Input
Do not test only successful cases. Break the API intentionally.
rq.test("Returns 400 for invalid input", () => {
rq.expect(rq.response.code).to.equal(400);
});
const error = rq.response.json();
rq.test("Correct error message returned", () => {
rq.expect(error.message).to.equal("Invalid input provided");
});
This ensures error handling works as expected.
8. Chain Requests Using Dynamic IDs
Create a resource and reuse its ID in the next request.
const data = rq.response.json();
rq.environment.set("userId", data.id);
rq.test("User ID stored", () => {
rq.expect(rq.environment.get("userId")).to.be.ok;
});
Now use {{userId}} in the next request URL.
This simulates real workflows instead of isolated API calls.
9. Validate Business Logic Calculations
Go beyond structure validation and test logic.
const body = rq.response.json();
let calculatedTotal = 0;
body.items.forEach(item => {
calculatedTotal += item.price * item.quantity;
});
rq.test("Total amount is correct", () => {
rq.expect(body.totalAmount).to.equal(calculatedTotal);
});
This catches pricing and calculation bugs early.
10. Store and Reuse Custom Variables
You can also store custom values for later use.
rq.variables.set("currentUserEmail", rq.response.json().email);
rq.test("Email variable stored", () => {
rq.expect(rq.variables.get("currentUserEmail")).to.be.ok;
});This is helpful for multi-step API flows.
Why This Matters
Checking only status codes is shallow testing. Real API testing means validating structure, performance, data correctness, error responses, and business logic.
Requestly’s scripting capability lets you:
- Automate response validation
- Chain multi-step workflows
- Test negative scenarios
- Validate complex business rules
- Reuse dynamic values
Start with a few meaningful assertions per endpoint. Expand into workflow validation once the basics are solid.
API testing is not about sending requests. It is about enforcing contracts and preventing production issues.
Contents
- 1. Validate Status Code and Response Time
- 2. Validate Required Fields in Response
- 3. Extract Auth Token and Store It
- 4. Ensure Fields Are Not Empty
- 5. Validate Array Length
- 6. Conditional Testing Based on Response Data
- 7. Negative Testing for Invalid Input
- 8. Chain Requests Using Dynamic IDs
- 9. Validate Business Logic Calculations
- 10. Store and Reuse Custom Variables
- Why This Matters
Subscribe for latest updates
Share this article
Related posts
Get started today
Requestly is a web proxy that requires a desktop and desktop browser.
Enter your email below to receive the download link. Give it a try next time youâre on your PC!










