API Response Simulator

Swipe to see more tools

API Response Simulator

Simulate API responses with custom status codes, delays, and payloads for testing frontend applications.

API Response Simulation

Test how your application handles different API scenarios including success, errors, timeouts, and slow responses without needing a real backend.

500ms

Quick Scenarios

Frequently Asked Questions

Why should I simulate API responses instead of using real APIs during development?
Benefits of API simulation: 1. Development independence: Work without waiting for backend API to be ready. Frontend and backend teams develop in parallel. No dependency on API server availability. 2. Faster development: No network latency (instant responses). No rate limits or API quotas. Offline development possible. 3. Controlled testing: Test specific scenarios (success, errors, edge cases) on demand. Reproduce rare errors consistently (timeouts, 500 errors). Test with exact data structures needed. 4. Cost savings: Avoid charges from third-party APIs during development. No accidental production API calls. 5. Better error handling: Easily test all error scenarios (401, 403, 404, 500, 503). Simulate network failures and timeouts. Test retry logic and error messages. 6. Realistic user testing: Create demo environments with realistic data. Consistent test data for QA teams. Common use cases: Developing new features before API exists. Testing error handling and edge cases. Creating demos for stakeholders. E2E testing with predictable data. Load testing frontend without stressing backend. When to use real APIs: Integration testing (verify actual API contract). Performance testing (measure real latency). Security testing (verify authentication/authorization). Final pre-deployment validation. Best practice: Use mocks during development, switch to real API for integration tests. Use this simulator to design and test API response handling before implementing backend.
How do I create realistic mock API responses with proper status codes, headers, and body structure?
Status codes: Choose appropriate code for scenario. Success: 200 OK (standard success), 201 Created (POST created resource), 204 No Content (DELETE success, no body). Client errors: 400 Bad Request (validation failed), 401 Unauthorized (missing/invalid auth), 403 Forbidden (insufficient permissions), 404 Not Found (resource doesn't exist), 409 Conflict (duplicate/state conflict), 422 Unprocessable Entity (semantic validation failed), 429 Too Many Requests (rate limited). Server errors: 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout. Response headers: Content-Type: application/json (JSON response), Content-Type: application/xml (XML), Content-Type: text/html (HTML). Cache-Control: max-age=3600 (cache for 1 hour), Cache-Control: no-cache (don't cache). Location: /api/users/123 (for 201 responses, points to created resource). Retry-After: 60 (for 429/503, retry after 60 seconds). X-RateLimit-Limit: 100, X-RateLimit-Remaining: 45, X-RateLimit-Reset: 1640000000 (rate limit info). ETag: "abc123" (for caching validation). Response body structure: Success response: {"status": "success", "data": {"id": 123, "name": "John"}, "message": "User retrieved"}. Error response: {"status": "error", "error": {"code": "INVALID_EMAIL", "message": "Email format is invalid", "field": "email"}, "timestamp": "2024-01-15T10:30:00Z"}. List response: {"data": [...items], "pagination": {"page": 1, "limit": 20, "total": 150, "pages": 8}}. Realistic data tips: Use consistent field naming (camelCase or snake_case). Include timestamps (ISO 8601 format). Add pagination metadata for lists. Include error details (code, message, field). Match your actual API structure exactly for realistic testing.
How do I simulate network delays, timeouts, and intermittent failures?
Network delay simulation: Add artificial delay to responses. Purpose: Test loading states, spinners, skeleton screens. Verify user experience on slow connections (3G, throttled networks). Test timeout handling. Implementation: Wrap mock response in setTimeout: setTimeout(() => resolve(mockResponse), 2000) for 2-second delay. Randomize delay for realism: const delay = Math.random() * 3000 + 500; (500ms-3.5s). Simulate different connection speeds: Fast (50-200ms), Normal (200-1000ms), Slow 3G (2000-5000ms), Offline (reject immediately). Timeout simulation: Test how app handles request timeouts. Client-side timeout: Set fetch timeout: const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); fetch(url, {signal: controller.signal}). Server timeout simulation: Return 504 Gateway Timeout after long delay: setTimeout(() => resolve({status: 504, body: 'Gateway Timeout'}), 30000). Intermittent failures: Simulate unreliable network/server. Random failures: Fail randomly (e.g., 20% failure rate): if (Math.random() < 0.2) { return {status: 500}; } else { return {status: 200, data: ...}; }. Flaky endpoints: Alternate between success and failure: let callCount = 0; return callCount++ % 2 === 0 ? successResponse : errorResponse;. Progressive failure: First N requests succeed, then fail (simulate degradation): if (callCount > 5) return {status: 503};. Testing scenarios: Loading states visible during delays. Retry logic triggers on failures. Error messages display on timeouts. Exponential backoff works correctly. User can cancel pending requests. Development workflow: Use this simulator to configure exact delay/failure scenarios. Test each scenario in isolation. Verify graceful degradation. Document expected behavior for each failure mode.
What's the difference between mocks, stubs, fakes, and fixtures, and when should I use each?
Mock: Object that records interactions and verifies they occurred correctly. Behavior: Tracks function calls, arguments, call count. Assertions: Verify specific functions were called with expected arguments. Example: const mockApi = jest.fn().mockResolvedValue({data: 'test'}); await fetchData(mockApi); expect(mockApi).toHaveBeenCalledWith('/api/users');. Use when: Testing interactions (was function called? with what args?). Verifying side effects. Unit testing with dependency injection. Stub: Object with predefined behavior, returns canned responses. Behavior: Always returns same hardcoded response. No verification of calls. Example: const stubApi = () => Promise.resolve({status: 200, data: [{id: 1, name: 'John'}]});. Use when: Testing logic that depends on specific responses. Replacing slow/unreliable dependencies. Isolating code under test from external dependencies. Fake: Working implementation with shortcuts (simpler than real thing). Behavior: Functional but not production-ready. Often in-memory storage instead of real database. Example: class FakeUserService { users = []; create(user) { user.id = this.users.length + 1; this.users.push(user); return user; } find(id) { return this.users.find(u => u.id === id); } }. Use when: Integration tests without real database. Faster test execution. Full feature testing without infrastructure. Fixture: Static test data (JSON files, objects). Behavior: Predefined data structures. Loaded and reused across tests. Example: const userFixture = {id: 123, name: 'John Doe', email: 'john@example.com', createdAt: '2024-01-01T00:00:00Z'};. Use when: Consistent test data across multiple tests. Complex data structures (avoid inline creation). Realistic data samples. Snapshot testing. Choosing: Use mocks for behavior verification (testing interactions). Use stubs for simple return values (testing logic). Use fakes for complex scenarios (integration-like tests). Use fixtures for data consistency (repeatable tests). This simulator creates stubs (predefined responses) and can act as a fake (stateful simulation with multiple endpoints).
How do I generate realistic mock data for different data types and use cases?
Manual mock data: Quick but tedious for large datasets. Example: const user = {id: 1, name: 'John Doe', email: 'john@example.com'};. Limitations: Time-consuming for complex objects. Data may look fake (all IDs sequential, all timestamps same). Libraries for data generation: Faker.js / @faker-js/faker: Generate realistic fake data. Examples: faker.name.fullName() → 'Sarah Johnson', faker.internet.email() → 'sarah.johnson@example.com', faker.datatype.uuid() → 'a1b2c3d4-e5f6...', faker.date.past() → random past date, faker.lorem.paragraph() → lorem ipsum text, faker.address.city() → 'New York'. Casual: Simpler API. Example: casual.full_name, casual.email. Chance.js: Random data with custom constraints. Example: chance.integer({min: 1, max: 100}). JSON Schema Faker: Generate data from JSON Schema. Define schema once, generate infinite variations. Mock data patterns: Lists with pagination: const users = Array.from({length: 100}, (_, i) => ({id: i + 1, name: faker.name.fullName()}));. Relationships: const posts = [{id: 1, userId: 5, title: '...'}]; (userId references user.id). Timestamps: createdAt: new Date().toISOString(), updatedAt: faker.date.recent(). Enums: status: faker.helpers.arrayElement(['active', 'inactive', 'pending']). Nested objects: {user: {profile: {avatar: faker.image.avatar()}}}. Edge cases to include: Empty lists: []. Null values: {optionalField: null}. Long strings: Test truncation/wrapping. Special characters: Test encoding (emojis, accents). Large numbers: Test number formatting. Realistic data characteristics: Vary lengths (names: 5-30 chars). Random ordering (not alphabetical). Non-sequential IDs (use UUIDs or gaps). Recent dates (not all same timestamp). Use this simulator to create templates with Faker.js snippets, generating fresh realistic data on each request for thorough testing.
How do I transition from mocked APIs to real APIs without breaking my application?
Environment-based switching: Use environment variables to toggle between mock and real APIs. Implementation: const API_URL = globalThis._importMeta_.env.MODE === 'development' ? 'http://localhost:3001/mock' : 'https://api.production.com';. API abstraction layer: Create wrapper that switches between mock and real implementation. Example: const apiClient = USE_MOCK_API ? mockApiClient : realApiClient; export const getUsers = () => apiClient.get('/users');. Benefits: Single place to switch. Easy to enable mocks for specific tests. Service Workers (MSW - Mock Service Worker): Intercept network requests at service worker level. Setup: import {setupWorker, rest} from 'msw'; const worker = setupWorker(rest.get('/api/users', (req, res, ctx) => res(ctx.json(mockUsers))));. Advantages: No code changes between mock/real. Intercepts at network level (works with any HTTP library). Can enable/disable via flag. Gradual migration strategy: Phase 1: All endpoints mocked. Phase 2: Critical endpoints use real API, rest mocked. Example: const getUsers = realEndpoint; const getPosts = mockEndpoint;. Phase 3: All real, mocks available for testing only. Contract testing: Ensure mock responses match real API contract. JSON Schema validation: Define schema: {type: 'object', properties: {id: {type: 'number'}, name: {type: 'string'}}}. Validate both mock and real responses against schema. Pact testing: Consumer defines expected API contract. Provider verifies it implements contract. Ensures mocks stay synchronized with real API. Handling differences: Response timing: Real APIs slower than mocks. Test with realistic delays. Error rates: Real APIs fail unpredictably. Add error handling not needed with perfect mocks. Data variations: Real data has edge cases (null, empty, special chars) not in mocks. Test with production-like data. Best practices: Keep mock responses in separate files, version controlled. Update mocks when API contract changes. Run integration tests against real API in CI/CD. Use this simulator to prototype API responses, then capture real responses with tools like Postman to ensure mocks match reality.

API Response Simulator - Mock Backend Testing

API response simulation enables frontend developers to test applications without requiring functional backend services by mocking status codes, response delays, and custom payloads. Our API simulator provides configurable scenarios for testing success states, error handling, timeout behavior, and slow network conditions during development. Simulating API responses is crucial for frontend development workflows where backend services are unavailable, still in development, or need specific error conditions for comprehensive testing. The simulator allows configuration of HTTP status codes from 200 success to 404 not found and 500 server errors, helping developers test how applications handle different response scenarios. Response delay configuration simulates slow networks, timeout conditions, and loading states essential for validating spinner behavior, retry logic, and user experience during poor connectivity. Custom JSON payload editing enables testing with realistic data structures, edge cases, and error response formats matching production API specifications. Frontend teams use API simulators to develop interfaces before backend implementation, test error boundaries, and validate loading state transitions without backend dependencies. The tool includes quick scenario presets for common cases like successful responses, slow loading (3-5 seconds), not found errors, and server failures for rapid testing. Whether you're building React components with loading states, implementing error handling in Vue applications, or testing Angular HTTP interceptors, this simulator provides controlled testing environments for comprehensive frontend validation without requiring complex mock server setup or backend coordination.

Key Features

  • Configurable HTTP status codes including 200, 201, 400, 404, 429, 500, and custom codes
  • Response delay simulation from instant to 5+ seconds for testing loading states
  • Custom JSON payload editor for realistic response data and error message formats
  • Quick scenario presets including success, slow network, not found, and server error
  • Countdown timer displaying remaining delay time during simulation execution
  • Response visualization showing simulated status, body, and timing information

Common Use Cases

  • Frontend developers testing loading states and spinner behavior during API calls
  • React engineers implementing error boundaries and testing failure scenarios
  • UI/UX designers validating user experience during slow network conditions
  • QA teams testing error handling without requiring backend failure injection
  • Mobile developers simulating poor connectivity for offline-first application testing
  • Integration developers testing retry logic and exponential backoff strategies

Get More Insights

Subscribe to our newsletter for more in-depth guides, tool reviews, and productivity tips delivered weekly.

Share This Article