rapina 0.11.0

A fast, type-safe web framework for Rust inspired by FastAPI
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! Integration tests for request extractors.

use http::StatusCode;
use rapina::prelude::*;
use rapina::testing::TestClient;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

// JSON Extractor Tests

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct User {
    name: String,
    email: String,
}

#[tokio::test]
async fn test_json_extraction() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::POST, "/users", |req, _, _| async move {
                use http_body_util::BodyExt;
                let body = req.into_body().collect().await.unwrap().to_bytes();
                let user: User = serde_json::from_slice(&body).unwrap();
                Json(user)
            }),
        );

    let client = TestClient::new(app).await;
    let response = client
        .post("/users")
        .json(&User {
            name: "Alice".to_string(),
            email: "alice@example.com".to_string(),
        })
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::OK);
    let user: User = response.json();
    assert_eq!(user.name, "Alice");
    assert_eq!(user.email, "alice@example.com");
}

#[tokio::test]
async fn test_json_extraction_invalid_json() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::POST, "/users", |req, _, _| async move {
                use http_body_util::BodyExt;
                let body = req.into_body().collect().await.unwrap().to_bytes();
                match serde_json::from_slice::<User>(&body) {
                    Ok(user) => Json(serde_json::json!(user)).into_response(),
                    Err(_) => Error::bad_request("invalid JSON").into_response(),
                }
            }),
        );

    let client = TestClient::new(app).await;
    let response = client
        .post("/users")
        .header("content-type", "application/json")
        .body("not valid json")
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn test_json_response() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::GET, "/user", |_, _, _| async {
                Json(User {
                    name: "Bob".to_string(),
                    email: "bob@test.com".to_string(),
                })
            }),
        );

    let client = TestClient::new(app).await;
    let response = client.get("/user").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert!(
        response
            .headers()
            .get("content-type")
            .unwrap()
            .to_str()
            .unwrap()
            .contains("application/json")
    );

    let user: User = response.json();
    assert_eq!(user.name, "Bob");
}

// Query Extractor Tests

#[derive(Debug, Deserialize)]
struct Pagination {
    page: Option<u32>,
    limit: Option<u32>,
}

#[tokio::test]
async fn test_query_extraction() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::GET, "/items", |req, _, _| async move {
                let query = req.uri().query().unwrap_or("");
                let params: Pagination = serde_urlencoded::from_str(query).unwrap_or(Pagination {
                    page: None,
                    limit: None,
                });
                format!(
                    "page={}, limit={}",
                    params.page.unwrap_or(1),
                    params.limit.unwrap_or(10)
                )
            }),
        );

    let client = TestClient::new(app).await;
    let response = client.get("/items?page=2&limit=20").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "page=2, limit=20");
}

#[tokio::test]
async fn test_query_extraction_optional_params() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::GET, "/items", |req, _, _| async move {
                let query = req.uri().query().unwrap_or("");
                let params: Pagination = serde_urlencoded::from_str(query).unwrap_or(Pagination {
                    page: None,
                    limit: None,
                });
                format!(
                    "page={}, limit={}",
                    params.page.unwrap_or(1),
                    params.limit.unwrap_or(10)
                )
            }),
        );

    let client = TestClient::new(app).await;

    // No query params - should use defaults
    let response = client.get("/items").send().await;
    assert_eq!(response.text(), "page=1, limit=10");

    // Only page param
    let response = client.get("/items?page=5").send().await;
    assert_eq!(response.text(), "page=5, limit=10");
}

// Path Extractor Tests

#[tokio::test]
async fn test_path_extraction_u64() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::GET, "/users/:id", |_, params, _| async move {
                let id = params.get("id").cloned().unwrap_or_default();
                format!("User ID: {}", id)
            }),
        );

    let client = TestClient::new(app).await;
    let response = client.get("/users/42").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "User ID: 42");
}

#[tokio::test]
async fn test_path_extraction_string() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(Router::new().route(
            http::Method::GET,
            "/users/:username",
            |_, params, _| async move {
                let username = params.get("username").cloned().unwrap_or_default();
                format!("Hello, {}!", username)
            },
        ));

    let client = TestClient::new(app).await;
    let response = client.get("/users/alice").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "Hello, alice!");
}

#[tokio::test]
async fn test_path_extraction_multiple_params() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(Router::new().route(
            http::Method::GET,
            "/users/:user_id/posts/:post_id",
            |_, params, _| async move {
                let user_id = params.get("user_id").cloned().unwrap_or_default();
                let post_id = params.get("post_id").cloned().unwrap_or_default();
                format!("User {} - Post {}", user_id, post_id)
            },
        ));

    let client = TestClient::new(app).await;
    let response = client.get("/users/10/posts/99").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "User 10 - Post 99");
}

// Headers Extractor Tests

#[tokio::test]
async fn test_headers_extraction() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::GET, "/auth", |req, _, _| async move {
                let auth = req
                    .headers()
                    .get("authorization")
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or("none");
                format!("Auth: {}", auth)
            }),
        );

    let client = TestClient::new(app).await;
    let response = client
        .get("/auth")
        .header("authorization", "Bearer secret-token")
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "Auth: Bearer secret-token");
}

#[tokio::test]
async fn test_headers_extraction_missing() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::GET, "/auth", |req, _, _| async move {
                match req.headers().get("authorization") {
                    Some(_) => "authenticated".to_string(),
                    None => "not authenticated".to_string(),
                }
            }),
        );

    let client = TestClient::new(app).await;
    let response = client.get("/auth").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "not authenticated");
}

#[tokio::test]
async fn test_custom_header() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::GET, "/custom", |req, _, _| async move {
                let custom = req
                    .headers()
                    .get("x-custom-header")
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or("missing");
                format!("Custom: {}", custom)
            }),
        );

    let client = TestClient::new(app).await;
    let response = client
        .get("/custom")
        .header("x-custom-header", "my-value")
        .send()
        .await;

    assert_eq!(response.text(), "Custom: my-value");
}

// Form Extractor Tests

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct LoginForm {
    username: String,
    password: String,
}

#[tokio::test]
async fn test_form_extraction() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::POST, "/login", |req, _, _| async move {
                use http_body_util::BodyExt;

                let content_type = req
                    .headers()
                    .get("content-type")
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or("");

                if !content_type.contains("application/x-www-form-urlencoded") {
                    return Error::bad_request("expected form data").into_response();
                }

                let body = req.into_body().collect().await.unwrap().to_bytes();
                match serde_urlencoded::from_bytes::<LoginForm>(&body) {
                    Ok(form) => format!("Welcome, {}!", form.username).into_response(),
                    Err(_) => Error::bad_request("invalid form").into_response(),
                }
            }),
        );

    let client = TestClient::new(app).await;
    let response = client
        .post("/login")
        .form(&serde_json::json!({
            "username": "alice",
            "password": "secret123"
        }))
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "Welcome, alice!");
}

// State Extractor Tests

struct AppConfig {
    app_name: String,
    version: String,
}

#[tokio::test]
async fn test_state_extraction() {
    use rapina::state::AppState;

    let app = Rapina::new()
        .with_introspection(false)
        .state(AppConfig {
            app_name: "MyApp".to_string(),
            version: "1.0.0".to_string(),
        })
        .router(Router::new().route(
            http::Method::GET,
            "/info",
            |_, _, state: Arc<AppState>| async move {
                let config = state.get::<AppConfig>().unwrap();
                format!("{} v{}", config.app_name, config.version)
            },
        ));

    let client = TestClient::new(app).await;
    let response = client.get("/info").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "MyApp v1.0.0");
}

#[tokio::test]
async fn test_multiple_state_types() {
    use rapina::state::AppState;

    struct DbConfig {
        url: String,
    }

    struct CacheConfig {
        ttl: u32,
    }

    let app = Rapina::new()
        .with_introspection(false)
        .state(DbConfig {
            url: "postgres://localhost".to_string(),
        })
        .state(CacheConfig { ttl: 3600 })
        .router(Router::new().route(
            http::Method::GET,
            "/config",
            |_, _, state: Arc<AppState>| async move {
                let db = state.get::<DbConfig>().unwrap();
                let cache = state.get::<CacheConfig>().unwrap();
                format!("DB: {}, Cache TTL: {}", db.url, cache.ttl)
            },
        ));

    let client = TestClient::new(app).await;
    let response = client.get("/config").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "DB: postgres://localhost, Cache TTL: 3600");
}

// Context Extractor Tests

#[tokio::test]
async fn test_context_trace_id() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::GET, "/trace", |req, _, _| async move {
                use rapina::context::RequestContext;
                let ctx = req.extensions().get::<RequestContext>().unwrap();
                format!("Trace ID length: {}", ctx.trace_id().len())
            }),
        );

    let client = TestClient::new(app).await;
    let response = client.get("/trace").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    // UUID is 36 characters
    assert_eq!(response.text(), "Trace ID length: 36");
}

// Validated Extractor Tests

#[derive(Debug, Deserialize, Validate)]
struct CreateUser {
    #[validate(length(min = 1, max = 50))]
    name: String,
    #[validate(email)]
    email: String,
}

#[tokio::test]
async fn test_validated_extraction_valid() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::POST, "/users", |req, _, _| async move {
                use http_body_util::BodyExt;
                let body = req.into_body().collect().await.unwrap().to_bytes();
                let user: CreateUser = match serde_json::from_slice(&body) {
                    Ok(u) => u,
                    Err(_) => return Error::bad_request("invalid JSON").into_response(),
                };

                if let Err(e) = user.validate() {
                    return Error::validation("validation failed")
                        .with_details(serde_json::to_value(e).unwrap_or_default())
                        .into_response();
                }

                format!("Created user: {}", user.name).into_response()
            }),
        );

    let client = TestClient::new(app).await;
    let response = client
        .post("/users")
        .json(&serde_json::json!({
            "name": "Alice",
            "email": "alice@example.com"
        }))
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "Created user: Alice");
}

#[tokio::test]
async fn test_validated_extraction_invalid_email() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::POST, "/users", |req, _, _| async move {
                use http_body_util::BodyExt;
                let body = req.into_body().collect().await.unwrap().to_bytes();
                let user: CreateUser = match serde_json::from_slice(&body) {
                    Ok(u) => u,
                    Err(_) => return Error::bad_request("invalid JSON").into_response(),
                };

                if let Err(e) = user.validate() {
                    return Error::validation("validation failed")
                        .with_details(serde_json::to_value(e).unwrap_or_default())
                        .into_response();
                }

                format!("Created user: {}", user.name).into_response()
            }),
        );

    let client = TestClient::new(app).await;
    let response = client
        .post("/users")
        .json(&serde_json::json!({
            "name": "Alice",
            "email": "not-an-email"
        }))
        .send()
        .await;

    assert_eq!(response.status(), 422); // Validation error
}

#[tokio::test]
async fn test_validated_extraction_empty_name() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::POST, "/users", |req, _, _| async move {
                use http_body_util::BodyExt;
                let body = req.into_body().collect().await.unwrap().to_bytes();
                let user: CreateUser = match serde_json::from_slice(&body) {
                    Ok(u) => u,
                    Err(_) => return Error::bad_request("invalid JSON").into_response(),
                };

                if let Err(e) = user.validate() {
                    return Error::validation("validation failed")
                        .with_details(serde_json::to_value(e).unwrap_or_default())
                        .into_response();
                }

                format!("Created user: {}", user.name).into_response()
            }),
        );

    let client = TestClient::new(app).await;
    let response = client
        .post("/users")
        .json(&serde_json::json!({
            "name": "",
            "email": "alice@example.com"
        }))
        .send()
        .await;

    assert_eq!(response.status(), 422); // Validation error
}

// Cookie Extractor Tests

#[tokio::test]
async fn test_cookie_extraction() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::GET, "/dashboard", |req, _, _| async move {
                let cookie_header = req
                    .headers()
                    .get("cookie")
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or("");

                // Parse session_id from cookie
                let session_id = cookie_header
                    .split(';')
                    .find_map(|pair| {
                        let (key, value) = pair.trim().split_once('=')?;
                        if key == "session_id" {
                            Some(value.to_string())
                        } else {
                            None
                        }
                    })
                    .unwrap_or_default();

                format!("Session: {}", session_id)
            }),
        );

    let client = TestClient::new(app).await;
    let response = client
        .get("/dashboard")
        .header("cookie", "session_id=abc123")
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "Session: abc123");
}

#[tokio::test]
async fn test_cookie_extraction_multiple_cookies() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::GET, "/user", |req, _, _| async move {
                let cookie_header = req
                    .headers()
                    .get("cookie")
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or("");

                let cookies: std::collections::HashMap<String, String> = cookie_header
                    .split(';')
                    .filter_map(|pair| {
                        let (key, value) = pair.trim().split_once('=')?;
                        Some((key.to_string(), value.to_string()))
                    })
                    .collect();

                let session = cookies.get("session_id").cloned().unwrap_or_default();
                let user = cookies.get("user_id").cloned().unwrap_or_default();

                format!("Session: {}, User: {}", session, user)
            }),
        );

    let client = TestClient::new(app).await;
    let response = client
        .get("/user")
        .header("cookie", "session_id=abc123; user_id=user456")
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "Session: abc123, User: user456");
}

#[tokio::test]
async fn test_cookie_extraction_missing() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(
            Router::new().route(http::Method::GET, "/dashboard", |req, _, _| async move {
                let cookie_header = req
                    .headers()
                    .get("cookie")
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or("");

                if cookie_header.is_empty() {
                    return Error::bad_request("missing cookies").into_response();
                }

                "ok".into_response()
            }),
        );

    let client = TestClient::new(app).await;
    let response = client.get("/dashboard").send().await;

    assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}