API testing often relies on services that are slow, unreliable, or expensive, leading to delays and blocked development. API stubbing avoids this by returning predefined responses, so teams can test and build features without depending on real APIs.
Overview
What is API Stubbing?
API stubbing is the practice of creating a fake API that returns predefined responses instead of calling the actual backend service. It allows developers and testers to simulate API behavior during development or automated testing.
Benefits of API Stubbing
- Faster Testing: By using stubs, teams can avoid waiting for real API responses, which speeds up both development and test execution.
- Improved Test Reliability: Stubs remove dependency on external services, making tests more stable and less likely to fail due to network errors or backend downtime.
- Error Scenario Testing: Stubbing allows developers to simulate rare or complex error responses, such as server timeouts or 500 errors.
- Cost Savings: Stubs eliminate the need to call paid third-party APIs during testing and help teams avoid usage-based charges or exceeding rate limits.
- Enables Parallel Development: Frontend and backend teams can work independently since stubbed APIs do not depend on the readiness or stability of the real service.
How API Stubbing Works?
- Define Fixed Responses: The stub is set up with rules that match specific requests and return predefined responses.
- Intercept Requests: The app sends API calls to the stub instead of the real backend. The stub captures the request and returns the matching response.
- Simulate Real Conditions: Stubs can delay responses, return error codes, or send varied data to mimic timeouts and failures.
- Plug into Tests: Replace the real API with the stub by switching the base URL without changing the code.
This article explains what API stubbing is, its benefits, when to use it, and the best API stubbing tools.
What is API Stubbing?
API stubbing is a testing method where you replace a real API with a simple substitute that returns fixed responses to specific requests.
Unlike mocks, stubs don’t verify how requests are made or simulate complex behavior. They just return predefined data to let dependent code run. For example, when your app calls the /users endpoint, the stub can return a fixed user profile JSON.
With stubs, your client-side or dependent services can run as if the target API is up, even if, in reality, the actual API is unfinished, unavailable, or unreliable.
Why Use API Stubbing?
API stubbing helps teams work faster, test more reliably, and avoid issues from slow or unstable services. Here are the key benefits of API stubbing.
- Isolation: Stubs allow you to test your code without depending on real APIs. This avoids test failures caused by server downtime, broken authentication, or incomplete backend features.
- Speed: Stubbed responses return instantly, removing delays from network calls or slow third-party services. This shortens development cycles and speeds up automated testing.
- Control: You can define exactly how the API responds to each request. This helps you simulate errors, edge cases, or unusual payloads that are hard to trigger in a live system.
- Cost Efficiency: Stubbing prevents unnecessary use of third-party APIs that may charge per request or enforce rate limits. This is especially useful when running high-volume test suites.
- Repeatability: The same request always gets the same response. This ensures consistent results across test runs, makes debugging easier, and improves test reliability.
- Availability: Stubs let you keep working when the real API is still being developed or temporarily offline. Teams can build and test independently without waiting for backend readiness.
How API Stubbing Works
API stubbing replaces live backend calls with predefined responses. Here’s how stubs intercept, control, and simulate real API behavior during development and testing.
- Response Definition: Developers or testers specify the exact HTTP response (status, headers, body) to return for particular API requests. These can be static or use templating for minor variation.
- Request Interception: Stub services run locally or on test infrastructure and intercept outgoing API calls targeting the real endpoint URLs. The stubs then serve the predefined replies instead.
- Scenario Simulation: Advanced stubbing frameworks support injecting delays, faults, and conditional responses to mimic real API behaviors like slow responses or partial failures.
- Integration Flexibility: Applications or tests interact with the stub endpoints as if they were real APIs, with changes managed by environment variables or configuration, requiring minimal or no code edits.
- Lifecycle Management: Stubs can be dynamically loaded, recorded from real traffic, or scripted for complex behavior, enabling automated updates and flexible workflows.
When Should You Use API Stubbing?
API stubbing is especially valuable in these situations:
- API Under Development: When the real API is incomplete or evolving, stubs let client teams continue work without delay.
- Unstable or Rate-Limited APIs: For third-party services that are unreliable, slow, or have strict call quotas, stubbing avoids disruption and throttling in tests.
- Negative and Edge Case Testing: To safely test error handling (timeouts, 500 errors, invalid data) that is rare or unsafe on production APIs.
- Parallel Team Collaboration: When frontend, backend, and integration teams work concurrently, stubs provide agreed contract surfaces.
- Automated Regression Testing: Stubs guarantee repeatability so CI pipelines avoid flaky failures caused by external API changes or downtime.
Read More: How to Prepare a Regression Test Suite
- Performance Testing and Resilience Testing: Inject latency or failure conditions using stubs to validate client-side retry and fallback mechanisms.
- Cost Control: Avoid high usage fees by running tests without calling third-party paid APIs.
Note: For tests validating overall end-to-end flow and business logic involving real systems, stubbing should complement and not replace calls to real APIs.
API Stubbing vs API Mocking vs Service Virtualization
API stubbing, mocking, and service virtualization are all techniques used to simulate APIs and backend services during development and testing, but they vary in complexity, scope, and fidelity.
Here is a table highlighting the key differences between API Stubbing, API Mocking, and Service Virtualization.
Aspect | API Stubbing | API Mocking | Service Virtualization |
---|---|---|---|
Purpose | Return fixed responses to simulate API endpoints | Simulate API with behavior verification (call counts, args) | Simulate full services, including state, behavior, and data |
Focus | Isolation of the caller from the external API | Verify interactions and API contract adherence | Replicate complex system interactions and dependencies |
Complexity | Simple fixed or lightly dynamic responses | Supports statefulness and request validation | Complex workflows, orchestration, and end-to-end system simulation |
Realism | Basic interface mimicry | Behavior-driven with call behavior assertions | High-fidelity simulation including databases, transactions |
Typical Use Cases | Unit/integration tests needing API response isolation | Contract testing, verifying caller behavior | Full integration/acceptance testing of distributed systems |
Verification | No verification of how the stub was called | Verifies call order, parameters, and frequency | Emulates production systems for end-to-end validation |
Popular Tools for API Stubbing
Here are the best API Stubbing tools in 2025.
1. Requestly by BrowserStack
Requestly is a browser extension and cloud-based tool designed for intercepting, modifying, and stubbing HTTP requests. It works well for frontend developers needing quick, code-free API stubbing and request manipulation within browsers or CI environments.
Key features of Requestly
- Redirect URL: Reroute API requests from the original backend to a mock server or local endpoint.
- Replace Rule (Switch Domain): Swap domains in API calls to point your app to a stubbed version instead of the real service.
- Modify API Response: Change the body, status code, or headers of an API response to simulate different scenarios.
- Delay Request: Add artificial delays to mimic slow or high-latency APIs during testing.
- Modify Request Body: Alter outgoing request payloads to test how your backend handles varied or malformed inputs.
- Modify HTTP Headers: Inject or override headers in requests or responses, useful for testing auth, content types, or feature flags.
- Modify Query Param: Adjust query parameters on the fly to test different filtering, sorting, or pagination behaviors.
Pros of Using Requestly
- Easy to set up: You can stub APIs without writing code by creating rules in the browser extension or desktop app.
- Works in any environment: Use stubs locally or in shared test setups by switching between local and cloud mocks.
- Faster debugging and testing: You can simulate success, error, or delay scenarios instantly without waiting for real API responses.
- Supports team collaboration: Teams can share rules and mock APIs so everyone tests against the same expected behavior.
- Supports bug reproduction: You can record sessions, capture network logs, and replay them to reproduce and fix bugs faster.
Ratings: Requestly has a rating of 4.6 out of 5 on G2.
Pricing:
- Free plan: $0/month
- Lite (for Individuals): $8/month
- Basic (for Small teams): $15/month
- Professional (for Enterprises): $23/month
2. WireMock
WireMock is a Java-based HTTP API stubbing and mocking framework that supports powerful request matching, response templating, and stateful behavior.
Pros | Cons |
---|---|
Wide adoption and robust feature set | Java-centric; less native support for other stacks |
Supports complex request matching | Steeper learning curve for advanced scenarios |
Response templating and scenario simulation | Basic UI; web interface available as a paid feature |
Record and playback of real traffic | Memory consumption can grow with heavy use |
3. Mountebank
Mountebank is an open-source, multi-protocol stubbing tool that supports HTTP, TCP, SMTP, and more, allowing versatile test doubles beyond REST.
Pros | Cons |
Multi-protocol support (not just HTTP) | Requires scripting for complex behavior |
Simple CLI and HTTP API for config | UI is fairly minimal |
Good for microservices and messaging | Smaller user community than WireMock |
4. Mock Service Worker (MSW)
MSW uses service workers to intercept requests in browser or Node environments, providing an excellent way to stub APIs in frontend and component tests.
Pros | Cons |
---|---|
Intercepts requests at the network layer | Limited to HTTP/REST protocols |
Works seamlessly with React, Vue, Angular | Limited advanced statefulness |
Ideal for UI and integration testing | Not suited for multiple protocol stubs |
5. Hoverfly
Hoverfly offers lightweight HTTP(S) simulation, including capture and playback modes, focusing on high performance and easy deployment.
Pros | Cons |
---|---|
Lightweight and container-friendly | Limited to HTTP(s) protocols |
Supports latency and fault injection | Smaller ecosystem and community |
Good for performance/resilience tests | CLI-focused; limited GUI tools |
Advanced API Stubbing Techniques
Modern API stubbing tools support far more than just static responses. When used correctly, these techniques allow you to simulate real-world conditions, trigger workflows, test error handling, and mimic dynamic backend behavior.
Below are advanced stubbing techniques that go beyond simple API substitution and provide deeper control for developers and testers.
1. Dynamic Responses
Use templating engines or scripting support to generate responses based on incoming request data. This allows you to create flexible stubs that return different results without hardcoding each one. For example, if a request includes a query param like ?country=IN, the stub can return a localized user profile for India.
2. Scenario Management
Simulate workflows or session-based flows by changing stub responses based on prior requests. This typically involves maintaining internal state in the stubbing tool to track how many times an endpoint has been called or what inputs were previously received.
For example, the first POST to /payment/status returns pending, the second returns confirmed, and the third returns completed.
3. Latency and Fault Injection
Mimic network delays, timeouts, dropped connections, or server errors to test how well your application handles unreliable conditions. This is especially important for frontend timeout handling, retry logic, and fallback mechanisms. For example, simulate a 10-second delay for a /pricing call or return a 503 Service Unavailable for stress testing.
4. Traffic Capture and Replay
Record real API traffic in staging or production and replay those responses in test environments. This technique reduces the manual effort of crafting responses and ensures the stub matches real-world data patterns. For example, capture search results for /products?q=mobile and use those as stub responses to validate pagination or filtering.
5. Chained Responses
Design stubs that return different responses in sequence to simulate data mutation or multi-step processes. These are useful for mimicking APIs where responses change based on internal progress or state transitions. For example, calling /jobs/status repeatedly could return queued, then running, then complete in that order.
Challenges and Limitations of API Stubbing
API stubbing improves speed, control, and test reliability, but it has clear limits. Understanding these challenges helps teams avoid misuse and design better testing strategies.
- Limited Realism: Stubs usually do not replicate complex business logic, authentication layers, or dynamic behavior. This means some issues only appear during real API interaction. For example, a stub might return a successful 200 OK for a user login, but the real service could reject it due to token expiration logic.
- Stub Drift and Maintenance: When real APIs evolve, stub definitions must be updated to stay aligned. Otherwise, tests may pass against stubs but fail in production due to outdated contracts.
- No Interaction Verification: Basic stubs only respond to requests. They do not confirm whether your code called the right endpoint, with the right payload, or in the right sequence. For example, the app might skip a security check call, but the stub won’t report it unless paired with mocking or spy tools.
- Difficulty with Stateful Logic: Simulating multi-step flows or transactional behavior requires maintaining internal state across requests. For example, trying to model a checkout flow with inventory updates and discount applications can get overly complex using only stubs.
- False Confidence Risk: Over-relying on stubs can give teams a false sense of correctness. Real-world failures like API rate limits, latency spikes, or data mismatches will not show up in stub-based tests. For example, an API might throttle after 100 requests, which a stub won’t reproduce.
Best Practices for API Stubbing
API stubbing works best when it’s treated as part of your testing infrastructure, not a quick workaround. These practices help teams build reliable, scalable, and maintainable stub environments.
- Keep stubs in version control: Store stub configurations alongside your application code. This ensures traceability when APIs change and allows different branches to manage their own stub logic.
- Include integration tests with the real API: Stubbing is ideal for speed and isolation, but it can’t replace real-world coverage. Reserve a portion of your test suite to run against staging or production-like APIs to detect issues that stubs can’t surface.
- Test for failures, not just happy paths: Design stubs that simulate slow responses, malformed payloads, or status codes like 401 and 500. This reveals how your application handles unexpected conditions.
- Document stub behavior and scope: Make it easy for other developers and testers to understand what a stub does and when to use it. Clear naming, folder structures, or inline comments all help reduce misuse.
- Avoid overcomplicating with too much state logic: Stateful stubs can simulate realistic flows, but they’re harder to maintain. Use them when absolutely necessary, such as for simulating a login session or checkout process.
- Return realistic data structures: Keep responses varied and detailed enough to match what your application expects. Instead of always returning a static “user: John Doe”, use representative payloads with nested fields and pagination.
Conclusion
API stubbing is a vital technique for improving speed, reliability, and scope of API testing. It creates controlled, predictable substitutes for external services, enabling development and testing without real API constraints. When used appropriately alongside real integration tests, API stubbing empowers teams to build resilient, high-quality software faster.
Requestly offers a powerful and flexible solution for API stubbing, allowing developers to intercept, modify, or simulate API behavior directly in the browser. It simplifies testing, speeds up development, and works without backend dependencies or complex setup.