### ExampleBuilder::new() Source: https://docs.rs/utoipa/latest/utoipa/openapi/example/struct.ExampleBuilder.html Constructs a new, empty ExampleBuilder instance. This is the starting point for configuring an Example. ```rust pub fn new() -> ExampleBuilder ``` -------------------------------- ### Set Array examples Source: https://docs.rs/utoipa/latest/utoipa/openapi/schema/struct.ArrayBuilder.html Use `examples()` to provide multiple example values for the array, which can be displayed in UI tools for better documentation. ```rust let _ = ArrayBuilder::new().examples(vec![Value::from(1), Value::from(2)]).build(); ``` -------------------------------- ### Construct Example Object with Builder Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/example.rs.html Demonstrates how to create an `Example` object using the `ExampleBuilder`. This is useful for defining a summary and a literal value for an API example. ```rust use utoipa::openapi::example::ExampleBuilder; let example = ExampleBuilder::new() .summary("Example string response") .value(Some(serde_json::json!("Example value"))) .build(); ``` -------------------------------- ### GET /user (Multiple Examples) Source: https://docs.rs/utoipa/latest/utoipa/attr.path.html Defines a GET endpoint for retrieving user information, showcasing multiple examples for a single response. ```APIDOC ## GET /user ### Description Retrieves user information with multiple examples provided for the response. ### Method GET ### Endpoint /user ### Response #### Success Response (200) - **User** ### Examples - **Demo** - Summary: This is summary - Description: Long description - Value: `{"name": "Demo"}` - **John** - Summary: Another user - Value: `{"name": "John"}` ``` -------------------------------- ### SwaggerUi Setup with Rocket Source: https://docs.rs/utoipa-swagger-ui/latest/src/utoipa_swagger_ui/lib.rs.html Example of setting up Swagger UI with the Rocket web framework. It mounts the Swagger UI at the root path and specifies the OpenAPI JSON endpoint. ```APIDOC ## POST /api/users ### Description This endpoint is used to create a new user. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The username for the new user. - **email** (string) - Required - The email address for the new user. ### Request Example { "username": "johndoe", "email": "john.doe@example.com" } ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. #### Response Example { "id": "123e4567-e89b-12d3-a456-426614174000", "username": "johndoe" } ``` -------------------------------- ### SwaggerUi Setup with Axum Source: https://docs.rs/utoipa-swagger-ui/latest/src/utoipa_swagger_ui/lib.rs.html Example of setting up Swagger UI with the Axum web framework. It merges the Swagger UI into the application router and defines the OpenAPI JSON endpoint. ```APIDOC ## GET /api/users/{id} ### Description Retrieves the details of a specific user by their ID. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. #### Response Example { "id": "123e4567-e89b-12d3-a456-426614174000", "username": "johndoe", "email": "john.doe@example.com" } ``` -------------------------------- ### Set Multiple Examples Source: https://docs.rs/utoipa/latest/utoipa/openapi/schema/struct.AllOfBuilder.html Sets multiple examples for the schema, providing richer documentation in UI tools. This is the preferred method for providing examples. ```rust pub fn examples, V: Into>( self, examples: I, ) -> Self ``` -------------------------------- ### Add Example to ContentBuilder Source: https://docs.rs/utoipa/latest/utoipa/openapi/content/struct.ContentBuilder.html Adds a single example value to the ContentBuilder. This is mutually exclusive with adding multiple examples. ```rust pub fn example(self, example: Option) -> Self ``` -------------------------------- ### Set Examples for AllOf Builder Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/schema.rs.html Sets multiple example values for the `AllOf` component to provide richer documentation in UI. ```rust pub fn examples, V: Into>(mut self, examples: I) -> Self { set_value!(self examples examples.into_iter().map(Into::into).collect()) } ``` -------------------------------- ### Example Builder Methods Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/example.rs.html Provides methods for configuring the `Example` object via its builder. Each method allows setting specific fields like summary, description, value, or external value. ```rust impl ExampleBuilder { /// Add or change a short description for the [`Example`]. Setting this to empty `String` /// will make it not render in the generated OpenAPI document. pub fn summary>(mut self, summary: S) -> Self { set_value!(self summary summary.into()) } /// Add or change a long description for the [`Example`]. Markdown syntax is supported for rich /// text representation. /// /// Setting this to empty `String` will make it not render in the generated /// OpenAPI document. pub fn description>(mut self, description: D) -> Self { set_value!(self description description.into()) } /// Add or change embedded literal example value. [`Example::value`] and [`Example::external_value`] /// are mutually exclusive. pub fn value(mut self, value: Option) -> Self { set_value!(self value value) } /// Add or change an URI that points to a literal example value. [`Example::external_value`] /// provides the capability to references an example that cannot be easily included /// in JSON or YAML. [`Example::value`] and [`Example::external_value`] are mutually exclusive. /// /// Setting this to an empty String will make the field not to render in the generated OpenAPI /// document. pub fn external_value>(mut self, external_value: E) -> Self { set_value!(self external_value external_value.into()) } } ``` -------------------------------- ### From for Example Source: https://docs.rs/utoipa/latest/utoipa/openapi/example/struct.ExampleBuilder.html Converts the ExampleBuilder into a final Example object. ```rust fn from(value: ExampleBuilder) -> Self ``` -------------------------------- ### From for ExampleBuilder Source: https://docs.rs/utoipa/latest/utoipa/openapi/example/struct.ExampleBuilder.html Converts an existing Example object into an ExampleBuilder, allowing for modification. ```rust fn from(value: Example) -> Self ``` -------------------------------- ### Set Multiple Example Values Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/schema.rs.html Sets multiple example values for richer documentation of a schema. ```rust pub fn examples, V: Into>(mut self, examples: I) -> Self { set_value!(self examples examples.into_iter().map(Into::into).collect()) } ``` -------------------------------- ### ContentBuilder Example Method Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/content.rs.html Sets a single example for the Content object using the builder pattern. ```rust pub fn example(mut self, example: Option) -> Self { set_value!(self example example) } ``` -------------------------------- ### HashMap Length Example Source: https://docs.rs/utoipa/latest/utoipa/openapi/extensions/struct.Extensions.html Demonstrates how to get the number of elements in a HashMap. ```rust use std::collections::HashMap; let mut a = HashMap::new(); assert_eq!(a.len(), 0); a.insert(1, "a"); assert_eq!(a.len(), 1); ``` -------------------------------- ### Utoipa Config Crate - Configuration Example Source: https://docs.rs/utoipa-config/latest/utoipa_config/index.html Example of how to create a `build.rs` file to configure utoipa, including defining type aliases. ```APIDOC ## Examples _**Create `build.rs` file with following content, then in your code you can just use `MyType` as alternative for `i32`.**_ ```rust use utoipa_config::Config; fn main() { Config::new() .alias_for("MyType", "i32") .write_to_file(); } ``` ``` -------------------------------- ### ExampleBuilder::build() Source: https://docs.rs/utoipa/latest/utoipa/openapi/example/struct.ExampleBuilder.html Finalizes the Example construction by consuming the builder and returning the configured Example object. ```rust pub fn build(self) -> Example ``` -------------------------------- ### Providing Multiple Examples for a Single Response Source: https://docs.rs/utoipa/latest/utoipa/attr.path.html Illustrates how to define multiple distinct examples for a single API response using the `examples` field within the `responses` block, each with its own summary and description. ```rust #[utoipa::path( get, path = "/user", responses( (status = 200, body = User, examples( ("Demo" = (summary = "This is summary", description = "Long description", value = json!(User{name: "Demo".to_string()}))), ("John" = (summary = "Another user", value = json!({"name": "John"}))) ) ) ) )] fn get_user() -> User { User {name: "John".to_string()} } ``` -------------------------------- ### Set Array example (Deprecated) Source: https://docs.rs/utoipa/latest/utoipa/openapi/schema/struct.ArrayBuilder.html The `example()` method is deprecated in favor of `examples()`. It was used to provide a single example value for the array. ```rust let _ = ArrayBuilder::new().example(Some(Value::Array(vec![Value::from(1), Value::from(2)]))).build(); ``` -------------------------------- ### Add Schema Example Source: https://docs.rs/utoipa/latest/utoipa/openapi/schema/struct.ComponentsBuilder.html Example demonstrating how to add a schema from a type that derives ToSchema. ```rust #[derive(ToSchema)] struct Value(String); let _ = ComponentsBuilder::new().schema_from::().build(); ``` -------------------------------- ### Set Single Example Value (Deprecated) Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/schema.rs.html Sets a single example value for richer documentation. Deprecated since 3.0.x, prefer `examples`. ```rust pub fn example(mut self, example: Option) -> Self { set_value!(self example example) } ``` -------------------------------- ### Get Pet by ID Example Source: https://docs.rs/utoipa/latest/src/utoipa/lib.rs.html Demonstrates how to define a path operation for retrieving a pet by its ID using `#[utoipa::path(...)]` and derive `ToSchema` for request/response bodies. ```APIDOC ## GET /pets/{id} ### Description Get pet from database by pet id ### Method GET ### Endpoint /pets/{id} ### Parameters #### Path Parameters - **id** (u64) - Required - Pet database id to get Pet for ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **body** (Pet) - Pet found successfully #### Response Example ```json { "example": "{\n \"id\": 1,\n \"name\": \"lightning\",\n \"age\": null\n}" } ``` #### Error Response (NOT_FOUND) - **description** - Pet was not found ``` -------------------------------- ### Object with Examples Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/schema.rs.html Adds example request or response bodies to an object schema. Examples clarify the expected data structure and content for consumers of the API. ```rust let json_value = ObjectBuilder::new() .examples([Some(json!({"age": 20, "name": "bob the cat"}))]) .build(); assert_json_snapshot!(json_value, @r#"" { "type": "object", "examples": [ { "age": 20, "name": "bob the cat" } ] } "#); ``` -------------------------------- ### Manual OpenAPI PathItem Implementation Source: https://docs.rs/utoipa/latest/src/utoipa/lib.rs.html Provides a manual implementation example of an OpenAPI `PathItem` for getting a pet by ID, mirroring the functionality of the `#[utoipa::path]` macro. This shows the underlying structure generated by the macro. ```rust utoipa::openapi::PathsBuilder::new().path( "/pets/{id}", utoipa::openapi::PathItem::new( utoipa::openapi::HttpMethod::Get, utoipa::openapi::path::OperationBuilder::new() .responses( utoipa::openapi::ResponsesBuilder::new() .response( "200", utoipa::openapi::ResponseBuilder::new() .description("Pet found successfully") .content("application/json", utoipa::openapi::Content::new( Some(utoipa::openapi::Ref::from_schema_name("Pet")), ), ), ) .response("404", utoipa::openapi::Response::new("Pet was not found")), ) .operation_id(Some("get_pet_by_id")) .deprecated(Some(utoipa::openapi::Deprecated::False)) .summary(Some("Get pet by id")) .description(Some("Get pet by id\n\nGet pet from database by pet database id\n")) .parameter( utoipa::openapi::path::ParameterBuilder::new() .name("id") .parameter_in(utoipa::openapi::path::ParameterIn::Path) .required(utoipa::openapi::Required::True) .deprecated(Some(utoipa::openapi::Deprecated::False)) .description(Some("Pet database id to get Pet for")) .schema( Some(utoipa::openapi::ObjectBuilder::new() .schema_type(utoipa::openapi::schema::Type::Integer) .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(utoipa::openapi::KnownFormat::Int64)))), ), ) .tag("pet_api"), ), ); ``` -------------------------------- ### ContentBuilder ExamplesFromIter Method Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/content.rs.html Adds multiple examples to the Content object from an iterator, using the builder pattern. Note that this will override any previously set single example. ```rust pub fn examples_from_iter< E: IntoIterator, N: Into, V: Into>, >( mut self, examples: E, ) -> Self { self.examples.extend( examples .into_iter() .map(|(name, example)| (name.into(), example.into())), ); self } ``` -------------------------------- ### Example Struct Definition Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/example.rs.html The `Example` struct represents an OpenAPI Example Object. It includes fields for summary, description, a literal value, and an external value URI. ```rust #[non_exhaustive] #[derive(Serialize, Deserialize, Default, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[serde(rename_all = "camelCase")] pub struct Example { /// Short description for the [`Example`]. #[serde(skip_serializing_if = "String::is_empty", default)] pub summary: String, /// Long description for the [`Example`]. Value supports markdown syntax for rich text /// representation. #[serde(skip_serializing_if = "String::is_empty", default)] pub description: String, /// Embedded literal example value. [`Example::value`] and [`Example::external_value`] are /// mutually exclusive. #[serde(skip_serializing_if = "Option::is_none")] pub value: Option, /// An URI that points to a literal example value. [`Example::external_value`] provides the /// capability to references an example that cannot be easily included in JSON or YAML. /// [`Example::value`] and [`Example::external_value`] are mutually exclusive. #[serde(skip_serializing_if = "String::is_empty", default)] pub external_value: String, } ``` -------------------------------- ### Simple Pet Schema with Object Level Example Source: https://docs.rs/utoipa/latest/utoipa/derive.ToSchema.html Defines a `Pet` struct with descriptions and an example value for the entire object using `#[schema(example = ...)]`. ```rust /// This is a pet. #[derive(ToSchema)] #[schema(example = json!({"name": "bob the cat", "id": 0}))] struct Pet { /// Unique id of a pet. id: u64, /// Name of a pet. name: String, /// Age of a pet if known. age: Option, } ``` -------------------------------- ### Convert ExampleBuilder to RefOr Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/example.rs.html Shows how to convert an `ExampleBuilder` into a `RefOr` type, which is commonly used in OpenAPI structures. ```rust impl From for RefOr { fn from(example_builder: ExampleBuilder) -> Self { Self::T(example_builder.build()) } } ``` -------------------------------- ### Parameter Builder - Setting Example Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/path.rs.html Sets or updates an example value for the Parameter using a builder pattern. Accepts an Option of a Value. ```rust impl ParameterBuilder { // ... other methods /// Add or change example of [`Parameter`]'s potential value. pub fn example(mut self, example: Option) -> Self { set_value!(self example example) } // ... other methods } ``` -------------------------------- ### Response Example Definition Source: https://docs.rs/utoipa/latest/utoipa/attr.path.html Defines a response example with a name, summary, and a JSON value. ```rust ("John" = (summary = "This is John", value = json!({"name": "John"}))) ``` -------------------------------- ### Complete Response with Body and Example Source: https://docs.rs/utoipa/latest/utoipa/attr.path.html Defines a response with status, description, body type, content type, and an example. ```rust responses( (status = 200, description = "Success response", body = Pet, content_type = "application/json", headers(...), example = json!({"id": 1, "name": "bob the cat"}) ) ) ``` -------------------------------- ### Paint Foreground Color Examples Source: https://docs.rs/utoipa-swagger-ui/latest/utoipa_swagger_ui/struct.SwaggerFile.html Examples for setting foreground colors using the Paint trait. ```rust use yansi::{Paint, Color}; painted.fg(Color::White); ``` ```rust use yansi::Paint; painted.white(); ``` ```rust println!("{}", value.primary()); ``` ```rust println!("{}", value.fixed(color)); ``` ```rust println!("{}", value.rgb(r, g, b)); ``` ```rust println!("{}", value.black()); ``` ```rust println!("{}", value.red()); ``` -------------------------------- ### OpenAPI Server Object Configuration Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/server.rs.html Example of defining server objects with URL, description, and variables for OpenAPI. ```rust servers: [ Server { url: "/api/v1".to_string(), description: "api version".to_string(), variables: Some(HashMap::from([ ("version".to_string(), ServerVariable { enum_values: Some(vec!["v1".to_string(), "v2".to_string()]), default_value: Some("v1".to_string()), description: Some("api version".to_string()), ..Default::default() }), ("username".to_string(), ServerVariable { default_value: Some("the_user".to_string()), ..Default::default() }) ])), ..Default::default() } ] ``` -------------------------------- ### User API Endpoint Example Source: https://docs.rs/utoipa-actix-web/latest/utoipa_actix_web/index.html This example demonstrates how to collect handlers annotated with `#[utoipa::path]` recursively from `service(...)` calls to compose an OpenAPI spec. ```APIDOC ## GET /api/v1/user ### Description Retrieves user information. ### Method GET ### Endpoint /api/v1/user ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **body** (User) - User object containing user details. #### Response Example ```json { "id": 1 } ``` ``` -------------------------------- ### HashMap Capacity Example Source: https://docs.rs/utoipa/latest/utoipa/openapi/extensions/struct.Extensions.html Demonstrates how to check the capacity of a HashMap. The returned value is a lower bound. ```rust use std::collections::HashMap; let map: HashMap = HashMap::with_capacity(100); assert!(map.capacity() >= 100); ``` -------------------------------- ### Install utoipa-swagger-ui dependency Source: https://docs.rs/utoipa-swagger-ui/latest/index.html Add the base dependency to your Cargo.toml file. ```toml [dependencies] utoipa-swagger-ui = "9" ``` -------------------------------- ### GET /user (Multiple Return Types) Source: https://docs.rs/utoipa/latest/utoipa/attr.path.html Defines a GET endpoint for retrieving user information, supporting multiple content types and examples for different user versions. ```APIDOC ## GET /user ### Description Retrieves user information, supporting different versions and content types. ### Method GET ### Endpoint /user ### Response #### Success Response (200) - **User1** (application/vnd.user.v1+json) - Example: `{"id": "id".to_string()}` - **User2** (application/vnd.user.v2+json) - Example: `{"id": 2}` ``` -------------------------------- ### Initialize Config Source: https://docs.rs/utoipa-swagger-ui/latest/utoipa_swagger_ui/struct.Config.html Create a configuration instance from a single URL or multiple API documentation paths. ```rust let config = Config::from("/api-doc.json"); ``` ```rust let config = Config::new(["/api-docs/openapi1.json", "/api-docs/openapi2.json"]); ``` ```rust let config = Config::new([ Url::new("api1", "/api-docs/openapi1.json"), Url::new("api2", "/api-docs/openapi2.json") ]); ``` -------------------------------- ### GET /pet/{id} Source: https://docs.rs/utoipa/latest/utoipa/attr.path.html Defines a GET endpoint to retrieve a pet by its ID. This example demonstrates the use of the `#[deprecated]` attribute to mark the operation as deprecated in the OpenAPI specification. ```APIDOC ## GET /pet/{id} ### Description Retrieves a pet from the database by its unique identifier. ### Method GET ### Endpoint /pet/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - Pet id ### Response #### Success Response (200) - **Pet found from database** ### Deprecated This operation is deprecated. ``` -------------------------------- ### ExampleBuilder::summary() Source: https://docs.rs/utoipa/latest/utoipa/openapi/example/struct.ExampleBuilder.html Sets a short description for the Example. An empty string will prevent the summary from rendering in the OpenAPI document. ```rust pub fn summary>(self, summary: S) -> Self ``` -------------------------------- ### HashMap Is Empty Example Source: https://docs.rs/utoipa/latest/utoipa/openapi/extensions/struct.Extensions.html Demonstrates how to check if a HashMap is empty. ```rust use std::collections::HashMap; let mut a = HashMap::new(); assert!(a.is_empty()); a.insert(1, "a"); assert!(!a.is_empty()); ``` -------------------------------- ### Serve Swagger UI with Rocket Source: https://docs.rs/utoipa-swagger-ui/latest/src/utoipa_swagger_ui/lib.rs.html This example shows how to serve Swagger UI and OpenAPI documentation with the Rocket framework. Make sure `rocket` and `utoipa` are included in your dependencies. ```rust # use rocket::{Build, Rocket}; # use utoipa_swagger_ui::SwaggerUi; # use utoipa::OpenApi; #[rocket::launch] fn rocket() -> Rocket { # # #[derive(OpenApi)] # #[openapi()] # struct ApiDoc; # ``` -------------------------------- ### SwaggerUi Initialization and Configuration Source: https://docs.rs/utoipa-swagger-ui/latest/utoipa_swagger_ui/struct.SwaggerUi.html Demonstrates how to initialize SwaggerUi and configure API documentation URLs. ```APIDOC ## SwaggerUi Entry point for serving Swagger UI and api docs in application. It provides builder style chainable configuration methods for configuring api doc urls. ### Method `new` ### Endpoint Configurable via the `path` argument in `SwaggerUi::new()`. ### Parameters #### Path Parameters - **path** (string) - Required - The base path for the Swagger UI. #### Query Parameters None #### Request Body None ### Request Example ```rust let swagger = SwaggerUi::new("/swagger-ui/{_:.*}"); ``` ## SwaggerUi::url ### Description Add API doc `Url` into `SwaggerUi`. Method takes two arguments where first one is path which exposes the `OpenApi` to the user. Second argument is the actual Rust implementation of the OpenAPI doc which is being exposed. Calling this again will add another url to the Swagger UI. ### Method `url` ### Endpoint Configurable via the `url` argument. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Expose manually created OpenAPI doc. let swagger = SwaggerUi::new("/swagger-ui/{_:.*}") .url("/api-docs/openapi.json", utoipa::openapi::OpenApi::new( utoipa::openapi::Info::new("my application", "0.1.0"), utoipa::openapi::Paths::new(), )); // Expose derived OpenAPI doc. struct ApiDoc; impl utoipa::OpenApi for ApiDoc { // ... implementation ... fn openapi() -> utoipa::openapi::OpenApi { // ... implementation ... utoipa::openapi::OpenApi::new( utoipa::openapi::Info::new("my application", "0.1.0"), utoipa::openapi::Paths::new(), ) } } let swagger = SwaggerUi::new("/swagger-ui/{_:.*}") .url("/api-docs/openapi.json", ApiDoc::openapi()); ``` ## SwaggerUi::urls ### Description Add multiple `Url`s to Swagger UI. Takes one `Vec` argument containing tuples of `Url` and `OpenApi`. Situations where this comes handy is when there is a need or wish to separate different parts of the api to separate api docs. ### Method `urls` ### Endpoint Configurable via the `urls` argument. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Assuming ApiDoc and ApiDoc2 are implementations of utoipa::OpenApi let swagger = SwaggerUi::new("/swagger-ui/{_:.*}") .urls( vec![ (Url::with_primary("api doc 1", "/api-docs/openapi.json", true), ApiDoc::openapi()), (Url::new("api doc 2", "/api-docs/openapi2.json"), ApiDoc2::openapi()) ] ); ``` ## SwaggerUi::external_url_unchecked ### Description Add external API doc to the `SwaggerUi`. This operation is unchecked and so it does not check any validity of provided content. Users are required to do their own check if any regarding validity of the external OpenAPI document. Method accepts two arguments, one is `Url` the API doc is served at and the second one is the `serde_json::Value` of the OpenAPI doc to be served. ### Method `external_url_unchecked` ### Endpoint Configurable via the `url` argument. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use serde_json::json; let external_openapi = json!({"openapi": "3.0.0"}); let swagger = SwaggerUi::new("/swagger-ui/{_:.*}") .external_url_unchecked("/api-docs/openapi.json", external_openapi); ``` ## SwaggerUi::external_urls_from_iter_unchecked ### Description Add external API docs to the `SwaggerUi` from iterator. This operation is unchecked and so it does not check any validity of provided content. Users are required to do their own check if any regarding validity of the external OpenAPI documents. Method accepts one argument, an `iter` of `Url` and `serde_json::Value` tuples. The `Url` will point to location the OpenAPI document is served and the `serde_json::Value` is the OpenAPI document to be served. ### Method `external_urls_from_iter_unchecked` ### Endpoint Configurable via the `external_urls` argument. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use serde_json::json; let external_openapi = json!({"openapi": "3.0.0"}); let external_openapi2 = json!({"openapi": "3.0.0"}); let swagger = SwaggerUi::new("/swagger-ui/{_:.*}") .external_urls_from_iter_unchecked([ ("/api-docs/openapi.json", external_openapi), ("/api-docs/openapi2.json", external_openapi2) ]); ``` ## SwaggerUi::oauth ### Description Add oauth `oauth::Config` into `SwaggerUi`. Method takes one argument which exposes the `oauth::Config` to the user. ### Method `oauth` ### Endpoint Configurable via the `oauth` argument. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Assuming oauth::Config is defined and imported // let swagger = SwaggerUi::new("/swagger-ui/{_:.*}") // .oauth(oauth::Config::new()); ``` ``` -------------------------------- ### Create type with ToSchema and use it in #[utoipa::path(...)] Source: https://docs.rs/utoipa This example shows how to define a Pet struct with `ToSchema`, use it in a `#[utoipa::path]` macro for a GET endpoint, and register it with `OpenApi`. ```APIDOC ## GET /pets/{id} ### Description Get pet from database by pet id ### Method GET ### Endpoint /pets/{id} ### Parameters #### Path Parameters - **id** (u64) - Required - Pet database id to get Pet for ### Response #### Success Response (200) - **body** (Pet) - Pet found successfully #### Response Example { "example": { "id": 1, "name": "lightning", "age": null } } ``` -------------------------------- ### Get Todo by ID and Name Source: https://docs.rs/utoipa/latest/utoipa/attr.path.html Retrieves a specific todo item using its ID and name as path parameters. This example demonstrates resolving path argument types from tuple-style handler arguments. ```APIDOC ## GET /todo/{id} ### Description Get todo by id and name. ### Method GET ### Endpoint /todo/{id} ### Parameters #### Path Parameters - **id** (i32) - Required - Todo id - **name** (String) - Required - Todo name ### Response #### Success Response (200) - **body** (String) - Get todo success ``` -------------------------------- ### Serve Swagger UI with Actix-web Source: https://docs.rs/utoipa-swagger-ui/latest/src/utoipa_swagger_ui/lib.rs.html This example demonstrates how to serve Swagger UI and OpenAPI documentation using actix-web. Ensure you have the `actix-web` and `utoipa` dependencies in your project. ```rust # use actix_web::{App, HttpServer}; # use utoipa_swagger_ui::SwaggerUi; # use utoipa::OpenApi; # use std::net::Ipv4Addr; # #[derive(OpenApi)] # #[openapi()] # struct ApiDoc; HttpServer::new(move || { App::new() .service( SwaggerUi::new("/swagger-ui/{_:.*}") .url("/api-docs/openapi.json", ApiDoc::openapi()), ) }) .bind((Ipv4Addr::UNSPECIFIED, 8989)).unwrap() .run(); ``` -------------------------------- ### Compose Service and Form OpenAPI Spec with OpenApiRouter Source: https://docs.rs/utoipa-axum/latest/utoipa_axum Use `OpenApiRouter` to collect axum handlers annotated with `#[utoipa::path]` and simultaneously generate an OpenAPI specification. This example demonstrates registering a GET endpoint for retrieving user information. ```rust #[derive(utoipa::ToSchema, serde::Serialize)] struct User { id: i32, } #[utoipa::path(get, path = "/user", responses((status = OK, body = User)))] async fn get_user() -> Json { Json(User { id: 1 }) } let (router, api): (axum::Router, OpenApi) = OpenApiRouter::new() .routes(routes!(get_user)) .split_for_parts(); ``` -------------------------------- ### Use OpenApiRouter with utoipa::path Macro Source: https://docs.rs/utoipa-axum/latest/index.html Collect axum handlers annotated with `#[utoipa::path]` using `OpenApiRouter` to compose a service and generate an OpenAPI specification. This example demonstrates defining a User schema and a GET endpoint for retrieving a user. ```rust #[derive(utoipa::ToSchema, serde::Serialize)] struct User { id: i32, } #[utoipa::path(get, path = "/user", responses((status = OK, body = User)))] async fn get_user() -> Json { Json(User { id: 1 }) } let (router, api): (axum::Router, OpenApi) = OpenApiRouter::new() .routes(routes!(get_user)) .split_for_parts(); ``` -------------------------------- ### Swagger UI Configuration Usage Source: https://docs.rs/utoipa-swagger-ui/latest/src/utoipa_swagger_ui/lib.rs.html Example of initializing the configuration with multiple OpenAPI JSON files and OAuth settings. ```rust ["/api-docs/openapi1.json", "/api-docs/openapi2.json"], oauth::Config::new(), ); ``` -------------------------------- ### Set OneOf Example (Deprecated) Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/schema.rs.html Sets a single example for the `OneOf` component to be shown in the UI. This method is deprecated in favor of `examples`. ```rust use utoipa::openapi::schema::OneOfBuilder; use utoipa::serde_json::Value; let one_of = OneOfBuilder::new() .example(Some(Value::from("example_user"))); ``` -------------------------------- ### Add Multiple Examples from Iterator Source: https://docs.rs/utoipa/latest/utoipa/openapi/content/struct.ContentBuilder.html Adds multiple named examples to the ContentBuilder from an iterator. This overrides any single example set previously. ```rust pub fn examples_from_iter, N: Into, V: Into>>( self, examples: E, ) -> Self ``` -------------------------------- ### Serve Swagger UI with actix-web Source: https://docs.rs/utoipa-swagger-ui/latest/utoipa_swagger_ui/fn.serve.html This example shows how to use the `serve` function within an `actix-web` handler to serve Swagger UI files. Ensure the `Config` is initialized before creating the handler. ```rust let config = Arc::new(Config::from("/api-doc.json")); // This "/" is for demonstrative purposes only. The actual path should point to // file within Swagger UI. In real implementation this is the `tail` path from root of the // Swagger UI to the file served. let tail_path = "/"; fn get_swagger_ui(tail_path: String, config: Arc) -> HttpResponse { match utoipa_swagger_ui::serve(tail_path.as_ref(), config) { Ok(swagger_file) => swagger_file .map(|file| { HttpResponse::Ok() .content_type(file.content_type) .body(file.bytes.to_vec()) }) .unwrap_or_else(|| HttpResponse::NotFound().finish()), Err(error) => HttpResponse::InternalServerError().body(error.to_string()), } } ``` -------------------------------- ### Swagger UI Initialization with OAuth Source: https://docs.rs/utoipa-swagger-ui/latest/src/utoipa_swagger_ui/oauth.rs.html Example of Swagger UI bundle initialization, including OAuth configuration. This snippet shows how to set up the UI with client ID and other options. ```javascript window.ui = SwaggerUIBundle({ dom_id: '#swagger-ui', deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: "StandaloneLayout" }); ``` -------------------------------- ### Basic OpenAPI Router with Routes Source: https://docs.rs/utoipa-axum/latest/src/utoipa_axum/lib.rs.html Demonstrates creating an OpenAPI router and adding routes to it. This is a foundational example for setting up API endpoints with OpenAPI support. ```rust use utoipa::OpenApi; #[derive(utoipa::ToSchema)] #[allow(unused)] struct Todo { id: i32, } #[derive(utoipa::OpenApi)] #[openapi(components(schemas(Todo)))] struct Api; let mut router: OpenApiRouter = OpenApiRouter::with_openapi(Api::openapi()) .routes(routes!(search_user)) .routes(routes!(get_user)); let paths = router.to_openapi().paths; let expected_paths = utoipa::openapi::path::PathsBuilder::new() .path( "/", utoipa::openapi::PathItem::new( utoipa::openapi::path::HttpMethod::Get, utoipa::openapi::path::OperationBuilder::new().operation_id(Some("get_user")), ), ) .path( "/search", utoipa::openapi::PathItem::new( utoipa::openapi::path::HttpMethod::Get, utoipa::openapi::path::OperationBuilder::new() .operation_id(Some("search_user")), ), ); assert_eq!(expected_paths.build(), paths); ``` -------------------------------- ### Derive ToSchema Trait with Example Source: https://docs.rs/utoipa/latest/src/utoipa/lib.rs.html Derive the `ToSchema` trait for a struct to automatically generate its OpenAPI schema. Includes an example of how to define a schema with an example JSON object. ```rust # use utoipa::ToSchema; #[derive(ToSchema)] #[schema(example = json!({"name": "bob the cat", "id": 1}))] struct Pet { id: u64, name: String, age: Option, } ``` -------------------------------- ### Routes Macro Example Source: https://docs.rs/utoipa-axum/latest/src/utoipa_axum/lib.rs.html Illustrates how to use the `routes` macro to collect multiple Axum handlers annotated with `utoipa::path` into an `OpenApiRouter`. ```rust # use utoipa_axum::{routes, router::{OpenApiRouter, UtoipaMethodRouter}}; # use utoipa::path; #[utoipa::path(get, path = "")] async fn get_user() {} #[utoipa::path(post, path = "")] async fn post_user() {} let _: OpenApiRouter = OpenApiRouter::new().routes(routes!(get_user, post_user)); ``` -------------------------------- ### ExampleBuilder::description() Source: https://docs.rs/utoipa/latest/utoipa/openapi/example/struct.ExampleBuilder.html Sets a detailed description for the Example, supporting Markdown for rich text. An empty string will prevent the description from rendering. ```rust pub fn description>(self, description: D) -> Self ``` -------------------------------- ### Initialization and Styling Source: https://docs.rs/utoipa-swagger-ui/latest/utoipa_swagger_ui/struct.SwaggerUi.html Methods for creating new styled objects and applying styles. ```APIDOC ## fn new(self) -> Painted ### Description Create a new `Painted` with a default `Style`. Read more ### Method GET (Conceptual - this is a method call, not an HTTP endpoint) ### Endpoint N/A ### Parameters None ### Request Example ```rust let painted = Painted::new(); ``` ### Response #### Success Response (200) - **Painted** (Painted) - A new `Painted` object with default styling. #### Response Example ``` // A new Painted object is returned. ``` ``` ```APIDOC ## fn paint(&self, style: S) -> Painted<&Self> ### Description Apply a style wholesale to `self`. Any previous style is replaced. Read more ### Method GET (Conceptual - this is a method call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let styled_text = self.paint(Style::new().bold()); ``` ### Response #### Success Response (200) - **Painted<&Self>** (Painted<&Self>) - The painted object with the applied style. #### Response Example ``` // The painted object with the new style applied. ``` ``` -------------------------------- ### Add Schemas from Iterator Example Source: https://docs.rs/utoipa/latest/utoipa/openapi/schema/struct.ComponentsBuilder.html Example showing how to add multiple schemas using schemas_from_iter. ```rust ComponentsBuilder::new().schemas_from_iter([ ( "Pet", Schema::from( ObjectBuilder::new() .property( "name", ObjectBuilder::new().schema_type(Type::String), ) .required("name") ), ) ]); ``` -------------------------------- ### Create Http Security Schema with Basic Authentication Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/security.rs.html Demonstrates how to create a new HTTP security schema using the `Http::new` function with `HttpAuthScheme::Basic`. ```rust SecurityScheme::Http(Http::new(HttpAuthScheme::Basic)); ``` -------------------------------- ### Enum Schema with Object Level Example Source: https://docs.rs/utoipa/latest/utoipa/derive.ToSchema.html Defines an enum `VehicleType` with an example value for the enum itself. ```rust #[derive(ToSchema)] #[schema(example = "Bus")] enum VehicleType { Rocket, Car, Bus, Submarine } ``` -------------------------------- ### Config::new Source: https://docs.rs/utoipa-config/latest/utoipa_config Initializes a new configuration instance to define global settings for utoipa. ```APIDOC ## Config::new ### Description Creates a new instance of the global configuration builder. ### Method Rust Method ### Request Example ```rust use utoipa_config::Config; fn main() { Config::new() .alias_for("MyType", "i32") .write_to_file(); } ``` ``` -------------------------------- ### Create OpenApiRouter with Multiple Routes Source: https://docs.rs/utoipa-axum/latest/utoipa_axum/macro.routes.html Shows how to use the `routes` macro to collect multiple handlers (`get_user`, `post_user`) and integrate them into an `OpenApiRouter`. ```rust #[utoipa::path(get, path = "")] async fn get_user() {} #[utoipa::path(post, path = "")] async fn post_user() {} let _: OpenApiRouter = OpenApiRouter::new().routes(routes!(get_user, post_user)); ``` -------------------------------- ### GET /test-links Source: https://docs.rs/utoipa/latest/utoipa/attr.path.html Defines a GET endpoint to demonstrate the use of links in responses, allowing for hypermedia controls. ```APIDOC ## GET /test-links ### Description An endpoint demonstrating the use of links in response objects for hypermedia controls. ### Method GET ### Endpoint /test-links ### Response #### Success Response (200) - **success response** ### Links - **getFoo** - Operation ID: test_links - Parameters: - key: value - json_value: 1 - Request Body: this is body - Server: - url: http://localhost - **getBar** - Operation Ref: this is ref ``` -------------------------------- ### Allow Only GET Operations for 'Try it out' Source: https://docs.rs/utoipa-swagger-ui/latest/utoipa_swagger_ui/struct.Config.html Restrict the 'Try it out' functionality to only GET requests. This is useful for read-only operations. ```rust let config = Config::new(["/api-docs/openapi.json"]) .supported_submit_methods(["get"]); ``` -------------------------------- ### Extensions Builder Example Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/extensions.rs.html Demonstrates how to use the `ExtensionsBuilder` to add custom extensions to an OpenAPI specification. Keys are automatically prefixed with 'x-' if not already present. ```rust let expected = json!("value"); let extensions = ExtensionsBuilder::new() .add("x-some-extension", expected.clone()) .add("another-extension", expected.clone()) .build(); let value = serde_json::to_value(&extensions).unwrap(); assert_eq!(value.get("x-some-extension"), Some(&expected)); assert_eq!(value.get("x-another-extension"), Some(&expected)); ``` -------------------------------- ### Create Swagger UI URL Objects Source: https://docs.rs/utoipa-swagger-ui/latest/src/utoipa_swagger_ui/lib.rs.html Create Url instances to define the location and display name of OpenAPI documentation files. ```rust # use utoipa_swagger_ui::Url; let url = Url::new("My Api", "/api-docs/openapi.json"); ``` ```rust # use utoipa_swagger_ui::Url; let url = Url::with_primary("My Api", "/api-docs/openapi.json", true); ``` -------------------------------- ### Set OneOf Examples Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/schema.rs.html Adds or modifies a list of examples for the `OneOf` component to be displayed in the UI for richer documentation. ```rust use utoipa::openapi::schema::OneOfBuilder; use utoipa::serde_json::Value; let one_of = OneOfBuilder::new() .examples(vec![Value::from("example1"), Value::from("example2")]); ``` -------------------------------- ### Configure OAuth Source: https://docs.rs/utoipa-swagger-ui/latest/utoipa_swagger_ui/struct.Config.html Initialize a configuration with OAuth settings. ```rust let config = Config::with_oauth_config( ["/api-docs/openapi1.json", "/api-docs/openapi2.json"], oauth::Config::new(), ); ``` -------------------------------- ### Creating OpenApiRouter with Handlers Source: https://docs.rs/utoipa-axum/latest/src/utoipa_axum/lib.rs.html Demonstrates how to create an `OpenApiRouter` and register handlers using the `routes` macro, splitting the router and API spec into separate parts. ```rust # use axum::Json; # use utoipa::openapi::OpenApi; # use utoipa_axum::{routes, PathItemExt, router::OpenApiRouter}; #[derive(utoipa::ToSchema, serde::Serialize)] struct User { id: i32, } #[utoipa::path(get, path = "/user", responses((status = OK, body = User)))] async fn get_user() -> Json { Json(User { id: 1 }) } let (router, api): (axum::Router, OpenApi) = OpenApiRouter::new() .routes(routes!(get_user)) .split_for_parts(); ``` -------------------------------- ### Construct OpenApi with Info and Paths Source: https://docs.rs/utoipa/latest/utoipa/openapi/struct.OpenApi.html Creates a new OpenApi object using provided Info metadata and Paths containing operations. This is a fundamental way to initialize an OpenAPI document. ```rust let openapi = OpenApi::new(Info::new("pet api", "0.1.0"), Paths::new()); ``` -------------------------------- ### Multiple Response Content Types with Examples Source: https://docs.rs/utoipa/latest/utoipa/attr.path.html Defines multiple response return types for a single status code, each with its own example. ```rust responses( (status = 200, content( (User = "application/vnd.user.v1+json", example = json!(User {id: "id".to_string()})), (User2 = "application/vnd.user.v2+json", example = json!(User2 {id: 2})) )) ) ``` -------------------------------- ### ServerBuilder::new Source: https://docs.rs/utoipa/latest/utoipa/openapi/server/struct.ServerBuilder.html Constructs a new, empty ServerBuilder instance. This is the starting point for configuring a new Server object. ```APIDOC ## ServerBuilder::new ### Description Constructs a new `ServerBuilder`. ### Method ```rust ServerBuilder::new() ``` ### Returns A new `ServerBuilder` instance. ``` -------------------------------- ### Helper Function to Create Authorized GET Request Source: https://docs.rs/utoipa-swagger-ui/latest/src/utoipa_swagger_ui/axum.rs.html A utility function to create an HTTP GET request with an Authorization header. ```rust fn authorized_get(url: &str, authorization: &str) -> Request { Request::builder() .uri(url) .header(AUTHORIZATION, HeaderValue::from_str(authorization).unwrap()) .body(Body::empty()) .unwrap() } ``` -------------------------------- ### Helper Function to Create GET Request Source: https://docs.rs/utoipa-swagger-ui/latest/src/utoipa_swagger_ui/axum.rs.html A utility function to create a basic HTTP GET request with a specified URI and an empty body. ```rust fn get(url: &str) -> Request { Request::builder().uri(url).body(Body::empty()).unwrap() } ``` -------------------------------- ### Test: Create Server with Builder and Variable Substitution Source: https://docs.rs/utoipa/latest/src/utoipa/openapi/server.rs.html Demonstrates creating a Server object using ServerBuilder and defining server variables with enum values, descriptions, and default values. ```rust test_fn! { create_server_with_builder_and_variable_substitution: ServerBuilder::new().url("/api/{version}/{username}") .parameter("version", ServerVariableBuilder::new() .enum_values(Some(["v1", "v2"])) .description(Some("api version")) .default_value("v1")) .parameter("username", ServerVariableBuilder::new() .default_value("the_user")).build(); r###"{ "url": "/api/{version}/{username}", "variables": { "version": { ```