Expand description
§MockForge HTTP
HTTP/REST API mocking library for MockForge.
This crate provides HTTP-specific functionality for creating mock REST APIs, including OpenAPI integration, request validation, AI-powered response generation, and management endpoints.
§Overview
MockForge HTTP enables you to:
- Serve OpenAPI specs: Automatically generate mock endpoints from OpenAPI/Swagger
- Validate requests: Enforce schema validation with configurable modes
- AI-powered responses: Generate intelligent responses using LLMs
- Management API: Real-time monitoring, configuration, and control
- Request logging: Comprehensive HTTP request/response logging
- Metrics collection: Track performance and usage statistics
- Server-Sent Events: Stream logs and metrics to clients
§Quick Start
§Basic HTTP Server from OpenAPI
use axum::Router;
use mockforge_core::openapi_routes::ValidationMode;
use mockforge_core::ValidationOptions;
use mockforge_http::build_router;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Build router from OpenAPI specification
let router = build_router(
Some("./api-spec.json".to_string()),
Some(ValidationOptions {
request_mode: ValidationMode::Enforce,
..ValidationOptions::default()
}),
None,
).await;
// Start the server
let addr: std::net::SocketAddr = "0.0.0.0:3000".parse()?;
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, router).await?;
Ok(())
}§With Management API
Enable real-time monitoring and configuration:
use mockforge_http::{management_router, ManagementState};
let state = ManagementState::new(None, None, 3000);
// Build management router
let mgmt_router = management_router(state);
// Mount under your main router
let app = axum::Router::new()
.nest("/__mockforge", mgmt_router);§AI-Powered Responses
Generate intelligent responses based on request context:
use mockforge_data::intelligent_mock::{IntelligentMockConfig, ResponseMode};
use mockforge_http::{process_response_with_ai, AiResponseConfig};
use serde_json::json;
let ai_config = AiResponseConfig {
intelligent: Some(
IntelligentMockConfig::new(ResponseMode::Intelligent)
.with_prompt("Generate realistic user data".to_string()),
),
drift: None,
};
let response = process_response_with_ai(
Some(json!({"name": "Alice"})),
ai_config
.intelligent
.clone()
.map(serde_json::to_value)
.transpose()?,
ai_config
.drift
.clone()
.map(serde_json::to_value)
.transpose()?,
)
.await?;§Key Features
§OpenAPI Integration
- Automatic endpoint generation from specs
- Request/response validation
- Schema-based mock data generation
§Management & Monitoring
management: REST API for server control and monitoringmanagement_ws: WebSocket API for real-time updatessse: Server-Sent Events for log streamingrequest_logging: Comprehensive request/response loggingmetrics_middleware: Performance metrics collection
§Advanced Features
ai_handler: AI-powered response generationauth: Authentication and authorizationchain_handlers: Multi-step request workflowslatency_profiles: Configurable latency simulationreplay_listing: Fixture management
§Middleware
MockForge HTTP includes several middleware layers:
- Request Tracing: [
http_tracing_middleware] - Distributed tracing integration - Metrics Collection:
metrics_middleware- Prometheus-compatible metrics - Operation Metadata:
op_middleware- OpenAPI operation tracking
§Management API Endpoints
When using the management router, these endpoints are available:
GET /health- Health checkGET /stats- Server statisticsGET /logs- Request logs (SSE stream)GET /metrics- Performance metricsGET /fixtures- List available fixturesPOST /config/*- Update configuration
§Examples
See the examples directory for complete working examples.
§Related Crates
mockforge-core: Core mocking functionalitymockforge-data: Synthetic data generationmockforge-plugin-core: Plugin development
§Documentation
Re-exports§
pub use ai_handler::process_response_with_ai;pub use ai_handler::AiResponseConfig;pub use ai_handler::AiResponseHandler;pub use health::HealthManager;pub use health::ServiceStatus;pub use management::management_router;pub use management::management_router_with_ui_builder;pub use management::ManagementState;pub use management::MockConfig;pub use management::ServerConfig;pub use management::ServerStats;pub use ui_builder::create_ui_builder_router;pub use ui_builder::EndpointConfig;pub use ui_builder::UIBuilderState;pub use management_ws::ws_management_router;pub use management_ws::MockEvent;pub use management_ws::WsManagementState;pub use verification::verification_router;pub use metrics_middleware::collect_http_metrics;pub use http_tracing_middleware::http_tracing_middleware;pub use coverage::calculate_coverage;pub use coverage::CoverageReport;pub use coverage::MethodCoverage;pub use coverage::RouteCoverage;
Modules§
- ai_
handler - AI-powered response handler for HTTP requests
- auth
- Authentication middleware for MockForge HTTP server
- chain_
handlers - Chain management HTTP handlers for MockForge
- consistency
- Cross-protocol consistency engine integration for HTTP Consistency engine integration for HTTP protocol
- contract_
diff_ middleware - Contract diff middleware for automatic request capture Contract diff middleware for capturing requests
- coverage
- Mock Coverage Tracking
- database
- Database connection and migration support for mockforge-http
- file_
generator - File generation service for creating mock PDF, CSV, JSON files File generation service for MockForge
- file_
server - File serving for generated mock files File serving for MockForge generated files
- handlers
- HTTP handlers module
- health
- Kubernetes-native health check endpoints (liveness, readiness, startup probes) Kubernetes-native health check endpoints
- http_
tracing_ middleware - HTTP tracing middleware for distributed tracing
- latency_
profiles - Latency profile configuration for HTTP request simulation Operation-aware latency/failure profiles (per operationId and per tag).
- management
- Management API for server control and monitoring
- management_
ws - WebSocket-based management API for real-time updates
- metrics_
middleware - HTTP metrics collection middleware
- middleware
- HTTP middleware modules
- op_
middleware - Middleware/utilities to apply latency/failure and overrides per operation.
- proxy_
server - Browser/Mobile Proxy Server Browser/Mobile Proxy Server
- quick_
mock - Quick mock generation utilities Quick Mock Mode
- rag_
ai_ generator - RAG-powered AI response generation RAG-based AI generator implementation
- replay_
listing - Replay listing and fixture management Record/replay listing for HTTP/gRPC/WS fixtures.
- request_
logging - HTTP request logging middleware
- spec_
import - Specification import API for OpenAPI and AsyncAPI Specification Import API
- sse
- Server-Sent Events for streaming logs and metrics Server Sent Events (SSE) support for MockForge
- state_
machine_ api - State machine API for scenario state machines State machine API handlers
- tls
- TLS/HTTPS support TLS/HTTPS support for HTTP server
- token_
response - Token response utilities Token-based response resolution for HTTP handlers
- ui_
builder - UI Builder API for low-code mock endpoint creation
- verification
- Verification API for request verification HTTP verification API handlers for MockForge
Structs§
- Http
Server State - Shared state for tracking OpenAPI routes
- Route
Info - Route info for storing in state
Functions§
- build_
router - Build the base HTTP router, optionally from an OpenAPI spec.
- build_
router_ with_ auth - Build the base HTTP router with authentication support
- build_
router_ with_ auth_ and_ latency - Build the base HTTP router with authentication and latency support
- build_
router_ with_ chains - Build the base HTTP router with chaining support
- build_
router_ with_ chains_ and_ multi_ tenant - Build the base HTTP router with chaining and multi-tenant support
- build_
router_ with_ latency - Build the base HTTP router with latency injection support
- build_
router_ with_ multi_ tenant - Build the base HTTP router with multi-tenant workspace support
- serve_
router - Serve a provided router on the given port.
- serve_
router_ with_ tls - Serve a provided router on the given port with optional TLS support.
- start
- Backwards-compatible start that builds + serves the base router.
- start_
with_ auth_ and_ injectors - Start HTTP server with authentication and injectors support
- start_
with_ auth_ and_ latency - Start HTTP server with authentication and latency support
- start_
with_ latency - Start HTTP server with latency injection support