MockForge HTTP
HTTP/REST protocol support for MockForge with OpenAPI integration, AI-powered responses, and comprehensive management APIs.
This crate provides full-featured HTTP mocking capabilities including automatic OpenAPI spec generation, request validation, AI-powered intelligent responses, real-time monitoring, and extensive management endpoints. Perfect for API development, testing, and microservice simulation.
Features
- OpenAPI Integration: Auto-generate mock endpoints from OpenAPI/Swagger specs
- Request Validation: Schema-based validation with configurable enforcement
- AI-Powered Responses: Generate contextual responses using LLMs and RAG
- Management API: REST and WebSocket APIs for real-time monitoring and control
- Server-Sent Events: Stream logs, metrics, and events to clients
- Request Logging: Comprehensive HTTP request/response logging
- Metrics Collection: Prometheus-compatible performance metrics
- Authentication: JWT, OAuth2, and custom auth middleware
- Rate Limiting: Configurable request throttling
- Coverage Tracking: API endpoint usage and coverage reporting
Quick Start
Basic HTTP Server from OpenAPI
use build_router;
use ValidationOptions;
async
Server with Management API
use ;
use ValidationOptions;
use Arc;
use RwLock;
async
OpenAPI Integration
Automatic Endpoint Generation
MockForge HTTP automatically generates mock endpoints from OpenAPI specifications:
# api.yaml
openapi: 3.0.0
info:
title: User API
version: 1.0.0
paths:
/users:
get:
summary: Get users
parameters:
- name: limit
in: query
schema:
type: integer
default: 10
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
post:
summary: Create user
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserRequest'
responses:
'201':
description: Created
content:
application/json:
schema:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: string
name:
type: string
email:
type: string
CreateUserRequest:
type: object
required:
- name
- email
properties:
name:
type: string
email:
type: string
Request Validation
Configure validation behavior:
use ValidationOptions;
// Strict validation - reject invalid requests
let strict_validation = enforce;
// Lenient validation - log warnings but allow
let lenient_validation = warn;
// No validation
let no_validation = none;
// Custom validation
let custom_validation = ValidationOptions ;
AI-Powered Responses
Generate intelligent, contextually aware responses:
use ;
use RagConfig;
let ai_config = AiResponseConfig ;
// Process request with AI
let response = process_response_with_ai.await?;
RAG Integration
Use Retrieval-Augmented Generation for enhanced responses:
use ;
// Configure RAG engine
let rag_config = RagConfig ;
let mut rag_engine = new;
// Add context documents
rag_engine.add_document?;
rag_engine.add_document?;
// Generate responses with context
let response = rag_engine.generate_with_rag.await?;
Management API
REST Endpoints
Access comprehensive server information and control:
# Health check
# Server statistics
# List fixtures
# Update configuration
WebSocket Management
Real-time monitoring via WebSocket:
// Connect to management WebSocket
const ws = ;
// Listen for events
ws ;
// Events include:
// - request_logged: New request received
// - response_sent: Response sent
// - config_updated: Configuration changed
// - stats_updated: Statistics updated
};
Server-Sent Events
Stream logs and metrics:
// Connect to SSE endpoint
const eventSource = ;
// Listen for log events
eventSource ;
Authentication & Authorization
JWT Authentication
use ;
let jwt_config = JwtConfig ;
let jwt_auth = new;
// Use as middleware
let app = new
.route
.layer;
OAuth2 Integration
use ;
let oauth_config = OAuth2Config ;
let oauth_middleware = new;
Request/Response Processing
Middleware Stack
MockForge HTTP includes a comprehensive middleware stack:
use ;
let app = new
.route
// Tracing middleware
.layer
// Metrics collection
.layer
// OpenAPI operation tracking
.layer
// Request logging
.layer;
Latency Simulation
use LatencyProfile;
// Fixed delay
let fixed_latency = with_fixed_delay; // 500ms
// Variable delay
let variable_latency = with_range; // 100-2000ms
// Realistic network simulation
let network_latency = network; // Simulates real network conditions
Request Chaining
Create multi-step request workflows:
use ;
let chain = new;
// Execute chain
let result = chain.execute.await?;
Metrics & Monitoring
Prometheus Metrics
use metrics_middleware;
// Metrics are automatically exposed at /metrics
// Available metrics:
// - http_requests_total
// - http_request_duration_seconds
// - http_response_size_bytes
// - mockforge_active_connections
// - mockforge_memory_usage
Coverage Reporting
Track API usage and test coverage:
use ;
// Calculate coverage from request logs
let report = calculate_coverage.await?;
// Coverage includes:
// - Route coverage (endpoints hit)
// - Method coverage (HTTP methods used)
// - Parameter coverage (query/path params used)
// - Response code coverage
println!;
Advanced Features
Template-Based Responses
Use Handlebars templates for dynamic responses:
use TemplateEngine;
// Template with variables
let template = r#"
{
"id": "{{uuid}}",
"name": "{{faker.name}}",
"email": "{{faker.email}}",
"timestamp": "{{now}}"
}
"#;
let engine = new;
let response = engine.render?;
Failure Injection
Simulate various failure scenarios:
use ;
let failure_config = FailureConfig ;
let injector = new;
// Automatically injects failures into responses
Rate Limiting
Control request throughput:
use ;
let rate_limit = RateLimitConfig ;
let limiter = new;
// Applied as middleware to routes
Testing with MockForge HTTP
Integration Testing
use Client;
use build_router;
async
Load Testing
use build_router;
use task;
async
Configuration
Server Configuration
# mockforge.yaml
http:
port: 3000
openapi_spec: "api.yaml"
validation:
request: true
response: false
coerce_types: true
management:
enabled: true
port: 9080
metrics:
enabled: true
prometheus:
port: 9090
ai:
enabled: true
rag:
provider: "openai"
model: "gpt-4"
api_key: "sk-..."
auth:
jwt:
enabled: true
secret: "your-secret"
issuer: "mockforge"
Environment Variables
# Server
# AI
# Auth
Performance Considerations
- Memory Usage: Large OpenAPI specs may increase memory usage
- Validation Overhead: Request/response validation adds processing time
- AI Processing: RAG and LLM calls introduce latency
- Metrics Collection: Enable only required metrics for production
- Connection Pooling: Configure appropriate connection limits
Examples
Complete Server Setup
use ;
use ;
use ValidationOptions;
use Arc;
use RwLock;
use CorsLayer;
async
Troubleshooting
Common Issues
OpenAPI validation errors:
- Check schema syntax and references
- Ensure all required fields are defined
- Validate against OpenAPI specification
AI response generation failures:
- Verify API keys and network connectivity
- Check model availability and rate limits
- Review prompt and schema configurations
Performance issues:
- Profile with metrics endpoint
- Check validation overhead
- Optimize AI configuration for production
Related Crates
mockforge-core
: Core mocking functionalitymockforge-data
: Synthetic data generationmockforge-observability
: Metrics and monitoring
License
Licensed under MIT OR Apache-2.0