spikard 0.10.2

High-performance HTTP framework built on Axum and Tower-HTTP with type-safe routing, validation, WebSocket/SSE support, and lifecycle hooks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# Spikard

High-performance HTTP framework built on Axum and Tower-HTTP with type-safe routing, validation, WebSocket/SSE support, and lifecycle hooks.

## Status & Badges

[![Crates.io](https://img.shields.io/crates/v/spikard.svg)](https://crates.io/crates/spikard)
[![Downloads](https://img.shields.io/crates/d/spikard.svg)](https://crates.io/crates/spikard)
[![Documentation](https://docs.rs/spikard/badge.svg)](https://docs.rs/spikard)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Discord](https://img.shields.io/badge/Discord-Join%20our%20community-7289da)](https://discord.gg/pXxagNK2zN)
[![codecov](https://codecov.io/gh/Goldziher/spikard/graph/badge.svg?token=H4ZXDZ4A69)](https://codecov.io/gh/Goldziher/spikard)

### Multi-Language Bindings

[![PyPI](https://img.shields.io/pypi/v/spikard.svg)](https://pypi.org/project/spikard/)
[![npm](https://img.shields.io/npm/v/spikard.svg)](https://www.npmjs.com/package/spikard)
[![RubyGems](https://img.shields.io/gem/v/spikard.svg)](https://rubygems.org/gems/spikard)
[![Packagist](https://img.shields.io/packagist/v/spikard/spikard.svg)](https://packagist.org/packages/spikard/spikard)

## Features

- **Type-safe routing** with path parameter extraction and compile-time validation
- **JSON Schema validation** via schemars with automatic OpenAPI generation
- **WebSocket and SSE** (Server-Sent Events) support
- **Lifecycle hooks** with zero-cost abstraction (onRequest, preValidation, preHandler, onResponse, onError)
- **Tower middleware** stack (compression, rate limiting, auth, CORS, request IDs, timeouts)
- **OpenAPI 3.1** and AsyncAPI generation with Swagger UI and ReDoc
- **Testing utilities** with in-memory test server
- **File upload** handling with multipart form support
- **Streaming responses** with native async/await
- **Multi-language bindings** (Python, Node.js, Ruby, PHP)

## Installation

### Rust

```toml
[dependencies]
spikard = "0.10.2"
serde = { version = "1.0", features = ["derive"] }
schemars = "0.8"  # For JSON Schema generation
tokio = { version = "1", features = ["full"] }
```

## Quick Start

```rust
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use spikard::prelude::*;

#[derive(Deserialize, Serialize, JsonSchema)]
struct User {
    id: u64,
    name: String,
    email: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut app = App::new();

    app.route(get("/users/:id"), |ctx: Context| async move {
        let id: u64 = ctx.path_param("id").unwrap_or("0").parse().unwrap_or(0);
        Ok(Json(User {
            id,
            name: "Alice".to_string(),
            email: "alice@example.com".to_string(),
        }))
    })?;

    app.route(
        post("/users")
            .request_body::<User>()
            .response_body::<User>(),
        |ctx: Context| async move {
            let user: User = ctx.json()?;
            Ok(Json(user))
        },
    )?;

    app.run().await?;
    Ok(())
}
```

## Route Registration

### RouteBuilder API

```rust
use spikard::{get, post, put, patch, delete};
use schemars::JsonSchema;

#[derive(JsonSchema)]
struct UserParams {
    id: u64,
}

#[derive(JsonSchema)]
struct CreateUser {
    name: String,
    email: String,
}

let route = get("/users/:id")
    .handler_name("get_user_by_id")
    .params::<UserParams>();

let create_route = post("/users")
    .request_body::<CreateUser>()
    .response_body::<User>();
```

### With Raw JSON Schema

```rust
use serde_json::json;

let schema = json!({
    "type": "object",
    "properties": {
        "name": { "type": "string" },
        "email": { "type": "string", "format": "email" }
    },
    "required": ["name", "email"]
});

let route = post("/users")
    .request_schema_json(schema);
```

## Request Context

Access request data in handlers:

```rust
use spikard::prelude::*;

async fn handler(ctx: Context) -> HandlerResult {
    // Parse JSON body
    let body: MyStruct = ctx.json()?;

    // Query parameters
    let query: QueryParams = ctx.query()?;

    // Path parameters
    let id = ctx.path_param("id").unwrap();
    let path_data: PathParams = ctx.path()?;

    // Headers
    let auth = ctx.header("authorization");

    // Cookies
    let session = ctx.cookie("session_id");

    // Request metadata
    let method = ctx.method();
    let path = ctx.path_str();

    Ok(Json(body))
}
```

## Configuration

```rust
use spikard::{
    App, ServerConfig, CompressionConfig, RateLimitConfig,
    JwtConfig, StaticFilesConfig, OpenApiConfig
};

let config = ServerConfig {
    host: "0.0.0.0".to_string(),
    port: 8080,
    workers: 4,
    enable_request_id: true,
    max_body_size: Some(10 * 1024 * 1024),
    request_timeout: Some(30),
    compression: Some(CompressionConfig {
        gzip: true,
        brotli: true,
        min_size: 1024,
        quality: 6,
    }),
    rate_limit: Some(RateLimitConfig {
        per_second: 100,
        burst: 200,
        ip_based: true,
    }),
    jwt_auth: Some(JwtConfig {
        secret: "your-secret".to_string(),
        algorithm: "HS256".to_string(),
        audience: None,
        issuer: None,
        leeway: 0,
    }),
    static_files: vec![
        StaticFilesConfig {
            directory: "./public".to_string(),
            route_prefix: "/static".to_string(),
            index_file: true,
            cache_control: Some("public, max-age=3600".to_string()),
        }
    ],
    openapi: Some(OpenApiConfig {
        enabled: true,
        title: "My API".to_string(),
        version: "1.0.0".to_string(),
        description: Some("API documentation".to_string()),
        swagger_ui_path: "/docs".to_string(),
        redoc_path: "/redoc".to_string(),
        ..Default::default()
    }),
    ..Default::default()
};

let app = App::new().config(config);
```

## Lifecycle Hooks

```rust
use spikard::{LifecycleHooks, request_hook, response_hook, HookResult};
use std::sync::Arc;

let hooks = LifecycleHooks::builder()
    .on_request(request_hook("logger", |req| async move {
        println!("Request: {} {}", req.method(), req.uri());
        Ok(HookResult::Continue(req))
    }))
    .pre_validation(request_hook("auth", |req| async move {
        // Authentication check
        Ok(HookResult::Continue(req))
    }))
    .pre_handler(request_hook("rate_limit", |req| async move {
        // Rate limiting
        Ok(HookResult::Continue(req))
    }))
    .on_response(response_hook("headers", |mut resp| async move {
        resp.headers_mut().insert(
            "X-Frame-Options",
            axum::http::HeaderValue::from_static("DENY")
        );
        Ok(HookResult::Continue(resp))
    }))
    .on_error(response_hook("error_log", |resp| async move {
        eprintln!("Error: {}", resp.status());
        Ok(HookResult::Continue(resp))
    }))
    .build();

let config = ServerConfig {
    lifecycle_hooks: Some(Arc::new(hooks)),
    ..Default::default()
};
```

## WebSockets

```rust
use spikard::WebSocketHandler;
use serde_json::Value;

struct EchoHandler;

impl WebSocketHandler for EchoHandler {
    fn handle_message(&self, message: Value) -> impl std::future::Future<Output = Option<Value>> + Send {
        async move { Some(message) } // Echo back
    }

    fn on_connect(&self) -> impl std::future::Future<Output = ()> + Send {
        async {
            println!("Client connected");
        }
    }

    fn on_disconnect(&self) -> impl std::future::Future<Output = ()> + Send {
        async {
            println!("Client disconnected");
        }
    }
}

app.websocket("/ws", EchoHandler);
```

## Server-Sent Events

```rust
use spikard::{SseEventProducer, SseEvent};
use serde_json::json;

struct TickerProducer {
    count: std::sync::atomic::AtomicU64,
}

impl SseEventProducer for TickerProducer {
    async fn next_event(&self) -> Option<SseEvent> {
        let n = self.count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        if n < 10 {
            Some(SseEvent::new(json!({"tick": n})))
        } else {
            None
        }
    }
}

app.sse("/events", TickerProducer {
    count: std::sync::atomic::AtomicU64::new(0),
});
```

## File Uploads

```rust
use spikard::UploadFile;
use serde::Deserialize;

#[derive(Deserialize)]
struct UploadRequest {
    file: UploadFile,
    description: String,
}

async fn upload_handler(ctx: Context) -> HandlerResult {
    let upload: UploadRequest = ctx.json()?;
    let content = upload.file.as_bytes();
    let filename = &upload.file.filename;

    // Process upload...

    Ok(/* response */)
}
```

## Testing

```rust
use spikard::testing::TestServer;
use axum::http::Request;

#[tokio::test]
async fn test_api() {
    let mut app = App::new();
    // ... configure routes

    let server = TestServer::from_app(app).unwrap();

    let request = Request::builder()
        .uri("http://localhost/users")
        .method("GET")
        .body(axum::body::Body::empty())
        .unwrap();

    let response = server.call(request).await.unwrap();
    assert_eq!(response.status, 200);

    let json = response.json().unwrap();
    // assertions...
}
```

## Integration with Axum

Merge custom Axum routers:

```rust
use axum::{Router, routing::get};

async fn health() -> &'static str {
    "OK"
}

let custom_router = Router::new()
    .route("/health", get(health));

let app = App::new()
    .merge_axum_router(custom_router);
```

## Running

```rust
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = App::new();
    app.run().await?;
    Ok(())
}
```

## Type Safety

All handlers use `Context` and return `HandlerResult`:

```rust
pub type HandlerResult = Result<Response<Body>, (StatusCode, String)>;

pub trait IntoHandler {
    fn into_handler(self) -> Arc<dyn Handler>;
}
```

Handlers can be async functions or closures:

```rust
async fn handler(ctx: Context) -> HandlerResult { /* ... */ }

|ctx: Context| async move { /* ... */ }
```

## Features

- **Type-safe routing** with path parameter extraction
- **JSON Schema validation** via schemars
- **WebSocket and SSE** support
- **Lifecycle hooks** with zero-cost abstraction
- **Tower middleware** (compression, rate limiting, auth, CORS, etc.)
- **OpenAPI 3.1** generation
- **Testing utilities** with in-memory server
- **File upload** handling
- **Streaming responses**

## Performance

Built on:
- **Axum** for routing and handlers
- **Tower-HTTP** for middleware
- **Tokio** for async runtime
- **jsonschema** for validation
- Zero-copy where possible

## Language Bindings

Spikard is available for multiple languages:

### Python
```bash
pip install spikard
```
See [spikard-py]../spikard-py/README.md for details.

### Node.js / TypeScript
```bash
npm install spikard
```
See [spikard-node]../spikard-node/README.md for details.

### Ruby
```bash
gem install spikard
```
See [spikard-rb](../spikard-rb/README.md) for details.

### PHP
```bash
composer require spikard/spikard
```
See [spikard-php](../spikard-php/README.md) for details.


## Documentation

- [Main Project README]../../README.md
- [Contributing Guide]../../CONTRIBUTING.md
- [Architecture Decision Records]../../docs/adr/
- [Full API Documentation]https://docs.rs/spikard
- [Getting Started Guide]../../docs/getting-started.md

## Examples

See `/examples/rust/` for more Rust examples.

## Performance

Built on industry-proven foundations:
- **Axum** for high-throughput routing (600k+ req/s)
- **Tower-HTTP** for zero-overhead middleware
- **Tokio** for high-performance async runtime
- **jsonschema** for efficient validation

### Benchmark Results

Latest comparative run (2025-12-20, commit `25e4fdf`, Linux x86_64, AMD EPYC 7763 2c/4t, 50 concurrency, 10s, oha). Full artifacts: `snapshots/benchmarks/20397054933`.

| Binding | Avg RPS (all workloads) | Avg latency (ms) |
| --- | --- | --- |
| **spikard-rust** | **55,755** | **1.00** |
| spikard-node | 24,283 | 2.22 |
| spikard-php | 20,176 | 2.66 |
| spikard-python | 11,902 | 4.41 |
| spikard-ruby | 8,271 | 6.50 |

Spikard Rust is the fastest binding, delivering native performance as the reference implementation. All workloads include JSON, query/path params, forms, and multipart requests.

## Related Projects

- [spikard-http]../spikard-http/README.md - HTTP runtime
- [spikard-core]../spikard-core/README.md - Core primitives
- [spikard-cli]../spikard-cli/README.md - Command-line interface
- [spikard-codegen]../spikard-codegen/README.md - Code generation tools

## License

MIT