getting_started/
getting_started.rs1use fastapi::core::{
8 App, AppConfig, Request, RequestContext, RequestIdMiddleware, Response, ResponseBody,
9 SecurityHeaders, TestClient,
10};
11
12fn hello(_ctx: &RequestContext, _req: &mut Request) -> std::future::Ready<Response> {
14 std::future::ready(Response::ok().body(ResponseBody::Bytes(b"Hello, World!".to_vec())))
15}
16
17fn health(_ctx: &RequestContext, _req: &mut Request) -> std::future::Ready<Response> {
19 std::future::ready(
20 Response::ok().body(ResponseBody::Bytes(b"{\"status\":\"healthy\"}".to_vec())),
21 )
22}
23
24fn main() {
25 println!("Getting Started Guide - Code Validation\n");
26
27 println!("1. Basic app with two routes:");
29 let app = App::builder()
30 .get("/", hello)
31 .get("/health", health)
32 .build();
33
34 println!(" Routes: {}", app.route_count());
35 let client = TestClient::new(app);
36
37 let response = client.get("/").send();
38 println!(
39 " GET / -> {} ({})",
40 response.status().as_u16(),
41 response.text()
42 );
43 assert_eq!(response.status().as_u16(), 200);
44 assert_eq!(response.text(), "Hello, World!");
45
46 let response = client.get("/health").send();
47 println!(
48 " GET /health -> {} ({})",
49 response.status().as_u16(),
50 response.text()
51 );
52 assert_eq!(response.status().as_u16(), 200);
53
54 println!("\n2. App with middleware:");
56 let app = App::builder()
57 .middleware(RequestIdMiddleware::new())
58 .middleware(SecurityHeaders::new())
59 .get("/", hello)
60 .build();
61
62 let client = TestClient::new(app);
63 let response = client.get("/").send();
64 println!(" GET / -> {}", response.status().as_u16());
65 assert_eq!(response.status().as_u16(), 200);
66
67 println!("\n3. App with configuration:");
69 let config = AppConfig::new()
70 .name("My API")
71 .version("1.0.0")
72 .debug(true)
73 .max_body_size(10 * 1024 * 1024)
74 .request_timeout_ms(30_000);
75
76 let app = App::builder().config(config).get("/", hello).build();
77
78 println!(" App name: {}", app.config().name);
79 println!(" Version: {}", app.config().version);
80 assert_eq!(app.config().name, "My API");
81 assert_eq!(app.config().version, "1.0.0");
82
83 println!("\n4. 404 for unknown routes:");
85 let app = App::builder().get("/", hello).build();
86
87 let client = TestClient::new(app);
88 let response = client.get("/nonexistent").send();
89 println!(" GET /nonexistent -> {}", response.status().as_u16());
90 assert_eq!(response.status().as_u16(), 404);
91
92 println!("\nAll getting started examples validated successfully!");
93}