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
//! Integration tests for error handling functionality.

use http::StatusCode;
use rapina::prelude::*;
use rapina::testing::TestClient;

#[tokio::test]
async fn test_error_400_bad_request() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/bad", |_, _, _| async {
                Error::bad_request("invalid input")
            }),
        );

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

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

    let json: serde_json::Value = response.json();
    assert_eq!(json["type"], "https://userapina.com/errors/bad-request");
    assert_eq!(json["title"], "Bad Request");
    assert_eq!(json["detail"], "invalid input");
    assert!(json["trace_id"].is_string());
}

#[tokio::test]
async fn test_error_401_unauthorized() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/protected", |_, _, _| async {
                Error::unauthorized("authentication required")
            }),
        );

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

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

    let json: serde_json::Value = response.json();
    assert_eq!(json["type"], "https://userapina.com/errors/unauthorized");
    assert_eq!(json["title"], "Unauthorized");
    assert_eq!(json["detail"], "authentication required");
}

#[tokio::test]
async fn test_error_403_forbidden() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/admin", |_, _, _| async {
                Error::forbidden("access denied")
            }),
        );

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

    assert_eq!(response.status(), StatusCode::FORBIDDEN);

    let json: serde_json::Value = response.json();
    assert_eq!(json["type"], "https://userapina.com/errors/forbidden");
    assert_eq!(json["title"], "Forbidden");
    assert_eq!(json["detail"], "access denied");
}

#[tokio::test]
async fn test_error_404_not_found() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/users/:id", |_, _, _| async {
                Error::not_found("user not found")
            }),
        );

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

    assert_eq!(response.status(), StatusCode::NOT_FOUND);

    let json: serde_json::Value = response.json();
    assert_eq!(json["type"], "https://userapina.com/errors/not-found");
    assert_eq!(json["title"], "Not Found");
    assert_eq!(json["detail"], "user not found");
}

#[tokio::test]
async fn test_error_409_conflict() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::POST, "/users", |_, _, _| async {
                Error::conflict("user already exists")
            }),
        );

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

    assert_eq!(response.status(), StatusCode::CONFLICT);

    let json: serde_json::Value = response.json();
    assert_eq!(json["type"], "https://userapina.com/errors/conflict");
    assert_eq!(json["title"], "Conflict");
    assert_eq!(json["detail"], "user already exists");
}

#[tokio::test]
async fn test_error_422_validation() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::POST, "/users", |_, _, _| async {
                Error::validation("validation failed")
            }),
        );

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

    assert_eq!(response.status(), 422);

    let json: serde_json::Value = response.json();
    assert_eq!(
        json["type"],
        "https://userapina.com/errors/validation-error"
    );
    assert_eq!(json["title"], "Validation Error");
    assert_eq!(json["detail"], "validation failed");
}

#[tokio::test]
async fn test_error_429_rate_limited() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/api", |_, _, _| async {
                Error::rate_limited("too many requests")
            }),
        );

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

    assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);

    let json: serde_json::Value = response.json();
    assert_eq!(json["type"], "https://userapina.com/errors/rate-limited");
    assert_eq!(json["title"], "Rate Limited");
    assert_eq!(json["detail"], "too many requests");
}

#[tokio::test]
async fn test_error_500_internal() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/crash", |_, _, _| async {
                Error::internal("something went wrong")
            }),
        );

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

    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);

    let json: serde_json::Value = response.json();
    assert_eq!(json["type"], "https://userapina.com/errors/internal-error");
    assert_eq!(json["title"], "Internal Error");
    assert_eq!(json["detail"], "something went wrong");
}

#[tokio::test]
async fn test_error_with_details() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::POST, "/users", |_, _, _| async {
                Error::validation("validation failed").with_details(serde_json::json!({
                    "errors": [
                        {"field": "email", "message": "invalid email format"},
                        {"field": "password", "message": "too short"}
                    ]
                }))
            }),
        );

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

    assert_eq!(response.status(), 422);

    let json: serde_json::Value = response.json();
    assert_eq!(
        json["type"],
        "https://userapina.com/errors/validation-error"
    );
    assert_eq!(json["title"], "Validation Error");
    assert!(json["errors"].is_array());

    let errors = json["errors"].as_array().unwrap();
    assert_eq!(errors.len(), 2);
    assert_eq!(errors[0]["field"], "email");
}

#[tokio::test]
async fn test_error_with_custom_trace_id() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/error", |_, _, _| async {
                Error::bad_request("test error").with_trace_id("custom-trace-123")
            }),
        );

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

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

    let json: serde_json::Value = response.json();
    assert_eq!(json["trace_id"], "custom-trace-123");
}

#[tokio::test]
async fn test_error_trace_id_is_uuid_by_default() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/error", |_, _, _| async {
                Error::bad_request("test error")
            }),
        );

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

    let json: serde_json::Value = response.json();
    let trace_id = json["trace_id"].as_str().unwrap();

    // UUID format: 8-4-4-4-12 = 36 characters
    assert_eq!(trace_id.len(), 36);
    assert_eq!(trace_id.chars().filter(|c| *c == '-').count(), 4);
}

#[tokio::test]
async fn test_error_response_content_type() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/error", |_, _, _| async {
                Error::bad_request("test")
            }),
        );

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

    let content_type = response
        .headers()
        .get("content-type")
        .unwrap()
        .to_str()
        .unwrap();
    assert!(content_type.contains("application/problem+json"));
}

#[tokio::test]
async fn test_result_ok_returns_success() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/result", |_, _, _| async {
                let result: std::result::Result<&str, Error> = Ok("success");
                result
            }),
        );

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

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

#[tokio::test]
async fn test_result_err_returns_error() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/result", |_, _, _| async {
                let result: std::result::Result<&str, Error> = Err(Error::not_found("not found"));
                result
            }),
        );

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

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

#[tokio::test]
async fn test_custom_error_status() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/custom", |_, _, _| async {
                Error::new(418, "IM_A_TEAPOT", "I'm a teapot")
            }),
        );

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

    assert_eq!(response.status().as_u16(), 418);

    let json: serde_json::Value = response.json();
    assert_eq!(json["type"], "https://userapina.com/errors/im-a-teapot");
    assert_eq!(json["title"], "Im A Teapot");
    assert_eq!(json["detail"], "I'm a teapot");
}

#[tokio::test]
async fn test_error_without_details_omits_field() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::GET, "/error", |_, _, _| async {
                Error::bad_request("simple error")
            }),
        );

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

    let json: serde_json::Value = response.json();
    // detail is always present, but extensions should be omitted if None
    assert_eq!(json["detail"], "simple error");
    assert!(json.as_object().unwrap().get("details").is_none());
}

#[tokio::test]
async fn test_error_chaining() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .router(
            Router::new().route(http::Method::POST, "/users", |_, _, _| async {
                Error::validation("invalid input")
                    .with_details(serde_json::json!({"field": "email"}))
                    .with_trace_id("trace-abc-123")
            }),
        );

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

    assert_eq!(response.status(), 422);

    let json: serde_json::Value = response.json();
    assert_eq!(
        json["type"],
        "https://userapina.com/errors/validation-error"
    );
    assert_eq!(json["detail"], "invalid input");
    assert_eq!(json["field"], "email");
    assert_eq!(json["trace_id"], "trace-abc-123");
}

#[tokio::test]
async fn test_router_404_response() {
    let app = Rapina::new()
        .with_introspection(false)
        .router(Router::new().route(http::Method::GET, "/exists", |_, _, _| async { "found" }));

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

    // Router returns plain 404, not JSON error
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn test_standard_error_format() {
    let app = Rapina::new()
        .with_introspection(false)
        // Default is now standard format
        .router(
            Router::new().route(http::Method::GET, "/standard", |_, _, _| async {
                Error::not_found("user not found")
            }),
        );

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

    assert_eq!(response.status(), StatusCode::NOT_FOUND);

    // Should be application/json, not application/problem+json
    let content_type = response
        .headers()
        .get("content-type")
        .unwrap()
        .to_str()
        .unwrap();
    assert!(content_type.contains("application/json"));
    assert!(!content_type.contains("application/problem+json"));

    let json: serde_json::Value = response.json();
    // Standard format: { "error": { "code": "NOT_FOUND", "message": "user not found" }, "trace_id": "..." }
    assert_eq!(json["error"]["code"], "NOT_FOUND");
    assert_eq!(json["error"]["message"], "user not found");
    assert!(json["trace_id"].is_string());

    // Should NOT have RFC 7807 fields at the root
    assert!(json.get("type").is_none());
    assert!(json.get("title").is_none());
    assert!(json.get("detail").is_none());
}