Created
May 8, 2025 19:28
-
-
Save seesharprun/6ea3ca5cebe9fefaad083d67c2b21021 to your computer and use it in GitHub Desktop.
Rust Swagger REST API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [package] | |
| name = "rustapi" | |
| version = "0.1.0" | |
| edition = "2024" | |
| [dependencies] | |
| rocket = "0.5.1" | |
| rocket_okapi = { version = "0.9.0", features = ["swagger"] } | |
| serde = "1.0.219" | |
| lazy_static = "1.4.0" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use rocket::get; | |
| use rocket::serde::json::Json; | |
| use rocket_okapi::okapi::schemars; | |
| use rocket_okapi::okapi::schemars::JsonSchema; | |
| use rocket_okapi::{openapi, openapi_get_routes, swagger_ui::*}; | |
| use serde::{Deserialize, Serialize}; | |
| use lazy_static::lazy_static; | |
| // Define item structure | |
| #[derive(Serialize, Deserialize, JsonSchema, Clone)] | |
| #[serde(rename_all = "camelCase")] | |
| struct Item { | |
| id: i32, | |
| name: String, | |
| } | |
| // Define static collection of items | |
| lazy_static! { | |
| static ref ITEMS: Vec<Item> = vec![ | |
| Item { | |
| id: 1, | |
| name: "Item 1".to_string(), | |
| }, | |
| Item { | |
| id: 2, | |
| name: "Item 2".to_string(), | |
| }, | |
| ]; | |
| } | |
| /// # Generate static message | |
| /// Returns a string with the static message "Hello, internet user!". | |
| #[openapi(tag = "root")] | |
| #[get("/")] | |
| fn index() -> &'static str { | |
| "Hello, internet user!" | |
| } | |
| /// # Retrieve static item | |
| /// Returns a JSON object with the item details. | |
| #[openapi(tag = "item")] | |
| #[get("/item")] | |
| fn get_item() -> Option<Json<Item>> { | |
| ITEMS.get(0).cloned().map(Json) | |
| } | |
| /// # Retrieve multiple static items | |
| /// Returns a JSON array of items. | |
| #[openapi(tag = "items")] | |
| #[get("/items")] | |
| fn get_items() -> Json<Vec<Item>> { | |
| Json(ITEMS.clone()) | |
| } | |
| #[rocket::main] | |
| async fn main() { | |
| let _ = rocket::build() | |
| .mount("/api", openapi_get_routes![index, get_item, get_items]) | |
| .mount( | |
| "/", | |
| make_swagger_ui(&SwaggerUIConfig { | |
| url: "/api/openapi.json".to_string(), | |
| ..Default::default() | |
| }), | |
| ) | |
| .launch() | |
| .await; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment