API Response Simulator
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.
Quick Scenarios
❓ Frequently Asked Questions
▶Why should I simulate API responses instead of using real APIs during development?
▶How do I create realistic mock API responses with proper status codes, headers, and body structure?
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?
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?
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?
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?
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.Explore Other Categories
Discover tools from different categories to expand your toolkit beyond Developer's World.
Word Order Reverser
Reverse the order of words in text. Create backwards sentences while maintaining word spelling.
Online Image Editor
Edit your images online with our free tool. Adjust brightness, contrast, apply effects, resize, crop, rotate, and more without software installation.
What Is My IP
Find out your public IP address, location, ISP, and detailed network information. View both IPv4 and IPv6 addresses and check if your location is exposed.
Constellation Finder
Discover the 88 IAU constellations with mythology, bright stars, best viewing times, and deep-sky objects. Interactive constellation database for learning the night sky and planning stargazing sessions.
Recommended For You
Based on the tools you've explored, we think you'll find these useful. ( tools visited)
Base64 Converter
✨ Complements tools from different categories
Easily encode and decode text and files to Base64 format. Simple and fast online...
Duplicate Line Remover
✨ Complements tools from different categories
Remove duplicate lines from text with this free online tool. Clean up lists and ...
DNS Lookup
✨ Complements tools from different categories
Check DNS records (A, MX, CNAME, etc.) with our free DNS lookup tool. Fast and r...
WHOIS Lookup
✨ Complements tools from different categories
Free WHOIS lookup tool to check domain registration, expiry dates, nameservers a...
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.
