### ExampleBuilder::new() Source: https://docs.rs/utoipa/5.5.0/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 ``` -------------------------------- ### New Example Instance Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.Example.html Creates a new, empty `Example` instance. This is equivalent to calling `Example::default`. ```rust pub fn new() -> Self ``` -------------------------------- ### Construct Example via Builder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.ExampleBuilder.html Demonstrates how to create a new Example object using the ExampleBuilder's chainable methods. This is the primary way to instantiate an Example with specific configurations. ```rust let example = ExampleBuilder::new() .summary("Example string response") .value(Some(serde_json::json!("Example value"))) .build(); ``` -------------------------------- ### GET User with Multiple Examples Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html Retrieves user information with multiple distinct examples provided for the success response. ```APIDOC ## GET /user ### Description Retrieves user information. ### Method GET ### Endpoint /user ### Parameters #### Path Parameters None #### Query Parameters None ### Response #### Success Response (200) - **User** (object) - User information - **name** (string) #### Response Example ```json { "name": "Demo" } ``` #### Response Example ```json { "name": "John" } ``` ``` -------------------------------- ### From for ExampleBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.ExampleBuilder.html Converts an existing Example object into an ExampleBuilder, allowing for modification of a pre-existing example. ```rust fn from(value: Example) -> Self ``` -------------------------------- ### From for Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.ExampleBuilder.html Converts an ExampleBuilder into a final Example object. This is equivalent to calling the `build()` method. ```rust fn from(value: ExampleBuilder) -> Self ``` -------------------------------- ### Basic Path Definition with `#[path]` Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html This example demonstrates the basic usage of the `#[path]` attribute macro to define an OpenAPI path for a GET operation. The doc comment provides the summary and description for the operation. ```rust /// This is a summary of the operation /// /// The rest of the doc comment will be included to operation description. #[utoipa::path(get, path = "/operation")] fn operation() {} ``` -------------------------------- ### Add Schema Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.ComponentsBuilder.html Example demonstrating how to add a schema from a custom type that derives ToSchema. ```rust #[derive(ToSchema)] struct Value(String); let _ = ComponentsBuilder::new().schema_from::().build(); ``` -------------------------------- ### Add Example to ContentBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/content/struct.ContentBuilder.html Adds a single example value for the schema to the ContentBuilder. This is mutually exclusive with `examples_from_iter`. ```rust pub fn example(self, example: Option) -> Self ``` -------------------------------- ### Manual Path Implementation Example Source: https://docs.rs/utoipa/5.5.0/utoipa/trait.Path.html A detailed example illustrating how the `#[utoipa::path(...)]` macro might manually construct an OpenAPI PathItem object. This is for understanding the underlying structure. ```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 by 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"), ), ); ``` -------------------------------- ### HashMap Length Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/extensions/struct.Extensions.html Demonstrates how to get the number of elements currently 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); ``` -------------------------------- ### Define Multiple Response Examples Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.ToResponse.html Use the `examples` attribute to define multiple named examples for a single response. This attribute is mutually exclusive with the `example` attribute. ```rust ("John" = (summary = "This is John", value = json!({"name": "John"}))) ``` -------------------------------- ### Add Multiple Examples from Iterator Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/content/struct.ContentBuilder.html Adds multiple named examples to the ContentBuilder from an iterator. If `example` was also set, these examples will override it. ```rust pub fn examples_from_iter, N: Into, V: Into>>( self, examples: E, ) -> Self ``` -------------------------------- ### Example: Define servers to OpenApi Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.OpenApi.html Illustrates how to define server URLs, descriptions, and variables for an OpenAPI specification. ```APIDOC _**Define servers to OpenApi.**_ ``` #[derive(OpenApi)] #[openapi( servers( (url = "http://localhost:8989", description = "Local server"), (url = "http://api.{username}:{port}", description = "Remote API", variables( ("username" = (default = "demo", description = "Default username for API")), ("port" = (default = "8080", enum_values("8080", "5000", "3030"), description = "Supported ports for API")) ) ) ) )] struct ApiDoc; ``` ``` -------------------------------- ### AllOf With Capacity Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.AllOf.html Demonstrates creating an AllOf component with an initial capacity of 5. ```rust let one_of = AllOf::with_capacity(5); ``` -------------------------------- ### Default Example Value Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.Example.html Returns the default value for the `Example` type, typically an empty or initial state. ```rust fn default() -> Example ``` -------------------------------- ### Set Array Examples Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.ArrayBuilder.html Adds multiple example values for the array, which are displayed in the UI for richer documentation. Accepts an iterator of values. ```rust let _ = ArrayBuilder::new().examples(vec![Value::from(1), Value::from(2)]); ``` -------------------------------- ### Multiple Examples for a Single Response Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html Use this to provide multiple distinct examples for a single API response, each with its own summary and description, aiding client understanding. ```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/5.5.0/utoipa/openapi/schema/struct.ArrayBuilder.html Adds a single example value for the array. Note: This method is deprecated in favor of `examples` for OpenAPI 3.1+. ```rust let _ = ArrayBuilder::new().example(Some(Value::Array(vec![Value::from(1), Value::from(2)]))); ``` -------------------------------- ### Set Examples for AllOf Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.AllOfBuilder.html Sets or changes multiple example values for the object, shown in the UI for richer documentation. Accepts an iterator of values. ```rust pub fn examples, V: Into>( self, examples: I, ) -> Self ``` -------------------------------- ### Pet Struct with Field-Level Example and Default Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.ToSchema.html Demonstrates applying the `schema` attribute at the field level for examples and default values. ```rust #[derive(ToSchema)] struct Pet { #[schema(example = 1, default = 0)] id: u64, name: String, age: Option, } ``` -------------------------------- ### Complete Response with Example Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html Defines a complete response including status, description, body type, content type, headers, and an example value. ```rust responses( (status = 200, description = "Success response", body = Pet, content_type = "application/json", headers(...), example = json!({"id": 1, "name": "bob the cat"}) ) ) ``` -------------------------------- ### Handling Multiple Return Types with Content Negotiation Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html This example shows how to define an endpoint that can return multiple types based on content negotiation, specifying different media types and examples for each. ```rust #[utoipa::path( get, path = "/user", responses( (status = 200, content( (User1 = "application/vnd.user.v1+json", example = json!({"id": "id".to_string()})), (User2 = "application/vnd.user.v2+json", example = json!({"id": 2})) ) ) ) )] fn get_user() -> Box { Box::new(User1 {id: "id".to_string()}) } ``` -------------------------------- ### ExampleBuilder::build() Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.ExampleBuilder.html Finalizes the ExampleBuilder configuration and constructs the Example object. This method consumes the builder. ```rust pub fn build(self) -> Example ``` -------------------------------- ### Example Builder Construction Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.Example.html Constructs a new `ExampleBuilder` to facilitate the creation of `Example` objects. This is an alternative to directly calling `ExampleBuilder::new`. ```rust pub fn builder() -> ExampleBuilder ``` -------------------------------- ### Serialize Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.Example.html Implements the `Serialize` trait for the `Example` struct, allowing it to be serialized into various data formats using Serde. ```rust fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where __S: Serializer, ``` -------------------------------- ### From for RefOr Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.ExampleBuilder.html Converts an ExampleBuilder into a `RefOr` type, which can represent either a direct Example or a reference to one. ```rust fn from(example_builder: ExampleBuilder) -> Self ``` -------------------------------- ### ExampleBuilder::summary() Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.ExampleBuilder.html Adds or updates 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 ``` -------------------------------- ### Example Server Variable Definition Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.OpenApi.html Demonstrates how to define variables for server URLs, including default values and enumerated options. ```rust ("username" = (default = "demo", description = "Default username for API")), ("port" = (enum_values("8080", "5000", "4545"))) ``` -------------------------------- ### GET Test Links Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html An example endpoint demonstrating the use of links in responses to refer to other operations or provide related resources. ```APIDOC ## GET /test-links ### Description Success response with links to other operations. ### Method GET ### Endpoint /test-links ### Parameters #### Path Parameters None #### Query Parameters None ### Response #### Success Response (200) - **Links** - **getFoo** - **operation_id**: test_links - **parameters**: - key: value - json_value: 1 - **request_body**: this is body - **server**: http://localhost - **getBar** - **operation_ref**: this is ref #### Response Example "success response" ``` -------------------------------- ### Pet Struct with Object-Level Example Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.ToSchema.html Defines a `Pet` struct with an example provided at the object level 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, } ``` -------------------------------- ### Example Parameter Definitions using Tuples Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html Demonstrates defining various parameters with their types, locations, and additional attributes like description, deprecation, and serialization styles. ```rust params( ("limit" = i32, Query), ("x-custom-header" = String, Header, description = "Custom header"), ("id" = String, Path, deprecated, description = "Pet database id"), ("name", Path, deprecated, description = "Pet name"), ( "value" = inline(Option<[String]>), Query, description = "Value description", style = Form, allow_reserved, deprecated, explode, example = json!(["Value"])), max_length = 10, min_items = 1 ) ) ``` -------------------------------- ### Example Nest Definition Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.OpenApi.html Shows how to nest another OpenAPI definition into the current one, optionally specifying tags. ```rust (path = "path/to/nest", api = path::to::NestableApi), (path = "path/to/nest", api = path::to::NestableApi, tags = ["nestableapi", ...]) ``` -------------------------------- ### PartialEq Implementation for Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.Example.html Implements the `PartialEq` trait, enabling equality comparisons between `Example` instances. Includes methods for both equality (`eq`) and inequality (`ne`). ```rust fn eq(&self, other: &Example) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Example: Define OpenApi schema with paths and components Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.OpenApi.html Demonstrates how to define an OpenAPI schema with paths, components, security, tags, and external documentation. ```APIDOC _**Define OpenApi schema with some paths and components.**_ ``` #[derive(ToSchema)] struct Pet { name: String, age: i32, } #[derive(ToSchema)] enum Status { Active, InActive, Locked, } #[utoipa::path(get, path = "/pet")] fn get_pet() -> Pet { Pet { name: "bob".to_string(), age: 8, } } #[utoipa::path(get, path = "/status")] fn get_status() -> Status { Status::Active } #[derive(OpenApi)] #[openapi( paths(get_pet, get_status), components(schemas(Pet, Status)), security( (), ("my_auth" = ["read:items", "edit:items"]), ("token_jwt" = []) ), tags( (name = "pets::api", description = "All about pets", external_docs(url = "http://more.about.pets.api", description = "Find out more")) ), external_docs(url = "http://more.about.our.apis", description = "More about our APIs") )] struct ApiDoc; ``` ``` -------------------------------- ### Constructing a New ExtensionsBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/extensions/struct.ExtensionsBuilder.html Initializes a new ExtensionsBuilder. This is the starting point for configuring extensions. ```rust pub fn new() -> ExtensionsBuilder ``` -------------------------------- ### Equivalent Implementation for Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.Example.html Implements the `Equivalent` trait for comparing `Example` instances with other types. ```rust fn equivalent(&self, key: &K) -> bool ``` -------------------------------- ### Construct New ServerBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/server/struct.ServerBuilder.html Creates a new instance of ServerBuilder. This is the starting point for configuring a Server. ```rust pub fn new() -> ServerBuilder ``` -------------------------------- ### HashMap Capacity Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/extensions/struct.Extensions.html Demonstrates how to check the capacity of a HashMap, which indicates the number of elements it can hold without reallocating. ```rust use std::collections::HashMap; let map: HashMap = HashMap::with_capacity(100); assert!(map.capacity() >= 100); ``` -------------------------------- ### Example: Create OpenAPI with reusable response Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.OpenApi.html Demonstrates creating an OpenAPI specification with reusable response definitions. ```APIDOC _**Create OpenAPI with reusable response.**_ ``` #[derive(utoipa::ToSchema)] struct Person { name: String, } /// Person list response #[derive(utoipa::ToResponse)] struct PersonList(Vec); #[utoipa::path( get, path = "/person-list", responses( (status = 200, response = PersonList) ) )] fn get_persons() -> Vec { vec![] } #[derive(utoipa::OpenApi)] #[openapi( components( schemas(Person), responses(PersonList) ) )] struct ApiDoc; ``` ``` -------------------------------- ### Add Schemas from Iterator Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.ComponentsBuilder.html Example showing how to add multiple schemas using schemas_from_iter, defining a 'Pet' schema with a 'name' property. ```rust ComponentsBuilder::new().schemas_from_iter([ ( "Pet", Schema::from( ObjectBuilder::new() .property( "name", ObjectBuilder::new().schema_type(Type::String), ) .required("name") ), ) ]); ``` -------------------------------- ### Deserialize Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.Example.html Implements the `Deserialize` trait for the `Example` struct, allowing it to be deserialized from various data formats using Serde. ```rust fn deserialize<__D>(__deserializer: __D) -> Result where __D: Deserializer<'de>, ``` -------------------------------- ### Initialize ComponentsBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.ComponentsBuilder.html Constructs a new ComponentsBuilder to start defining OpenAPI components. ```rust pub fn new() -> ComponentsBuilder ``` -------------------------------- ### ExampleBuilder::value() Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.ExampleBuilder.html Sets a literal example value for the Example. This is mutually exclusive with `external_value`. ```rust pub fn value(self, value: Option) -> Self ``` -------------------------------- ### Mixed Enum with Field-Level Examples and Defaults Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.ToSchema.html Demonstrates a mixed enum with examples and defaults applied at the variant and field levels. ```rust #[derive(ToSchema)] enum ErrorResponse { InvalidCredentials, #[schema(default = String::default, example = "Pet not found")] NotFound(String), System { #[schema(example = "Unknown system failure")] details: String, } } ``` -------------------------------- ### Enum with Object-Level Example Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.ToSchema.html Illustrates defining an example for an enum using the `schema` attribute at the type level. ```rust #[derive(ToSchema)] #[schema(example = "Bus")] enum VehicleType { Rocket, Car, Bus, Submarine } ``` -------------------------------- ### Create Http Security Scheme with Basic Auth Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/security/struct.Http.html Example of creating an Http security scheme using the `new` constructor with `HttpAuthScheme::Basic` for basic authentication. ```rust SecurityScheme::Http(Http::new(HttpAuthScheme::Basic)); ``` -------------------------------- ### Example Struct Definition Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.Example.html Defines the structure for an OpenAPI Example Object, used to describe possible response bodies. Note that this struct is non-exhaustive. ```rust #[non_exhaustive] pub struct Example { pub summary: String, pub description: String, pub value: Option, pub external_value: String, } ``` -------------------------------- ### ExampleBuilder::description() Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.ExampleBuilder.html Adds or updates a long 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 ``` -------------------------------- ### Constructing a New ParameterBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/path/struct.ParameterBuilder.html Initializes a new instance of ParameterBuilder. This is the starting point for configuring a parameter. ```rust pub fn new() -> ParameterBuilder ``` -------------------------------- ### Constructing a New HeaderBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/header/struct.HeaderBuilder.html Initializes a new instance of HeaderBuilder. This is the starting point for configuring a Header. ```rust pub fn new() -> HeaderBuilder ``` -------------------------------- ### Clone Implementation Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/example/struct.Example.html Provides methods for creating a duplicate of an `Example` instance (`clone`) and for performing copy-assignment from another instance (`clone_from`). ```rust fn clone(&self) -> Example ``` ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### New ExternalDocsBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/external_docs/struct.ExternalDocsBuilder.html Constructs a new, empty ExternalDocsBuilder. Use this to start configuring external documentation. ```rust pub fn new() -> ExternalDocsBuilder ``` -------------------------------- ### Example: Nest UserApi to the current api doc instance Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.OpenApi.html Illustrates how to nest a separate OpenAPI definition (`UserApi`) into the main `ApiDoc`. ```APIDOC _**Nest _`UserApi`_to the current api doc instance.**_ ``` #[utoipa::path(get, path = "/api/v1/status")] fn test_path_status() {} #[utoipa::path(get, path = "/test")] fn user_test_path() {} #[derive(OpenApi)] #[openapi(paths(user_test_path))] struct UserApi; #[derive(OpenApi)] #[openapi( paths( test_path_status ), nest( (path = "/api/v1/user", api = UserApi), ) )] struct ApiDoc; ``` ``` -------------------------------- ### Construct New AllOfBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.AllOfBuilder.html Initializes a new instance of the AllOfBuilder. This is the starting point for configuring an AllOf schema. ```rust pub fn new() -> AllOfBuilder ``` -------------------------------- ### Struct with Method Reference for Default Values Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.ToSchema.html Shows how to use method references for `example` and `default` attributes within the `schema` macro. ```rust #[derive(ToSchema)] struct Pet { #[schema(example = u64::default, default = u64::default)] id: u64, #[schema(default = default_name)] name: String, age: Option, } fn default_name() -> String { "bob".to_string() } ``` -------------------------------- ### New ContentBuilder Instance Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/content/struct.ContentBuilder.html Constructs a new, empty ContentBuilder. This is the starting point for configuring a Content object. ```rust pub fn new() -> ContentBuilder ``` -------------------------------- ### New ServerVariableBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/server/struct.ServerVariableBuilder.html Constructs a new, empty ServerVariableBuilder. This is the starting point for configuring a ServerVariable. ```rust pub fn new() -> ServerVariableBuilder ``` -------------------------------- ### HashMap Keys Iteration Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/extensions/struct.Extensions.html Iterate over all keys in a HashMap in arbitrary order. Note that iteration performance is O(capacity). ```rust use std::collections::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); for key in map.keys() { println!("{key}"); } ``` -------------------------------- ### Example: Append Path from Path trait Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/path/struct.PathsBuilder.html Demonstrates how to use `path_from` to add a custom path definition (MyPath) to the PathsBuilder. ```rust let paths = utoipa::openapi::path::PathsBuilder::new(); let _ = paths.path_from::(); ``` -------------------------------- ### Manual Implementation of ToSchema and PartialSchema Source: https://docs.rs/utoipa/5.5.0/utoipa/trait.ToSchema.html A manual implementation of `ToSchema` and `PartialSchema` for a struct, demonstrating how to define schema properties, types, formats, and examples programmatically. ```rust impl utoipa::ToSchema for Pet { fn name() -> std::borrow::Cow<'static, str> { std::borrow::Cow::Borrowed("Pet") } } impl utoipa::PartialSchema for Pet { fn schema() -> utoipa::openapi::RefOr { utoipa::openapi::ObjectBuilder::new() .property( "id", utoipa::openapi::ObjectBuilder::new() .schema_type(utoipa::openapi::schema::Type::Integer) .format(Some(utoipa::openapi::SchemaFormat::KnownFormat( utoipa::openapi::KnownFormat::Int64, ))), ) .required("id") .property( "name", utoipa::openapi::ObjectBuilder::new() .schema_type(utoipa::openapi::schema::Type::String), ) .required("name") .property( "age", utoipa::openapi::ObjectBuilder::new() .schema_type(utoipa::openapi::schema::Type::Integer) .format(Some(utoipa::openapi::SchemaFormat::KnownFormat( utoipa::openapi::SchemaFormat::KnownFormat::Int32, ))), ) .example(Some(serde_json::json!({ "name":"bob the cat","id":1 }))) .into() } } ``` -------------------------------- ### Manual PartialSchema Implementation Source: https://docs.rs/utoipa/5.5.0/utoipa/trait.PartialSchema.html Example of manually implementing the PartialSchema trait for a custom type `MyType`. ```rust struct MyType; impl PartialSchema for MyType { fn schema() -> RefOr { // ... impl schema generation here RefOr::T(Schema::Object(ObjectBuilder::new().build())) } } ``` -------------------------------- ### Define Servers to OpenApi Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.OpenApi.html Configures server definitions for an OpenAPI specification, including local and remote server examples with variables. ```rust #[derive(OpenApi)] #[openapi( servers( (url = "http://localhost:8989", description = "Local server"), (url = "http://api.{username}:{port}", description = "Remote API", variables( ("username" = (default = "demo", description = "Default username for API")), ("port" = (default = "8080", enum_values("8080", "5000", "3030"), description = "Supported ports for API")) ) ) ) )] struct ApiDoc; ``` -------------------------------- ### HashMap Values Iteration Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/extensions/struct.Extensions.html Iterate over all values in a HashMap in arbitrary order. Note that iteration performance is O(capacity). ```rust use std::collections::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); for val in map.values() { println!("{val}"); } ``` -------------------------------- ### Construct a new PathsBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/path/struct.PathsBuilder.html Use `new()` to create an empty PathsBuilder instance. This is the starting point for configuring OpenAPI paths. ```rust pub struct PathsBuilder { /* private fields */ } ``` -------------------------------- ### Parameter Explode Examples Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/path/struct.Parameter.html Illustrates the difference in serialization for array and object types when the 'explode' field is false versus true. ```text With explode _`false`_: ``` color=blue,black,brown ``` ``` ```text With explode _`true`_: ``` color=blue&color=black&color=brown ``` ``` -------------------------------- ### ToSchema Example for Generic Types Source: https://docs.rs/utoipa/5.5.0/utoipa/trait.ToSchema.html Demonstrates how the `name()` method behaves for generic types, highlighting potential name collisions when the default implementation is used for generic parameters. ```rust struct Foo(T); impl ToSchema for Foo {} assert_eq!(Foo::<()>::name(), std::borrow::Cow::Borrowed("Foo")); assert_eq!(Foo::<()>::name(), Foo::::name()); // WARNING: these types have the same name ``` -------------------------------- ### License Construction with Name Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/info/struct.License.html Creates a new License object, requiring the license name as an argument. For example, 'MIT'. ```rust pub fn new>(name: S) -> Self ``` -------------------------------- ### Complete Path Definition with Request Body and Responses Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html Use this snippet for a comprehensive definition of a POST endpoint including detailed request body, responses with headers and examples, parameters, and security. ```rust #[utoipa::path( post, operation_id = "custom_post_pet", path = "/pet", tag = "pet_handlers", request_body(content = Pet, description = "Pet to store the database", content_type = "application/json"), responses( (status = 200, description = "Pet stored successfully", body = Pet, content_type = "application/json", headers( ("x-cache-len" = String, description = "Cache length") ), example = json!({"id": 1, "name": "bob the cat"}) ), ), params( ("x-csrf-token" = String, Header, deprecated, description = "Current csrf token of user"), ), security( (), ("my_auth" = ["read:items", "edit:items"]), ("token_jwt" = []) ) )] fn post_pet(pet: Pet) -> Pet { Pet { id: 4, name: "bob the cat".to_string(), } } ``` -------------------------------- ### Construct New LicenseBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/info/struct.LicenseBuilder.html Creates a new instance of LicenseBuilder. This is the starting point for configuring a License object. ```rust pub fn new() -> LicenseBuilder ``` -------------------------------- ### Create OAuth2 Security Scheme Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/security/enum.SecurityScheme.html Example of creating an OAuth2 security scheme with an implicit flow, specifying the authorization URL, scopes, and a description. ```rust SecurityScheme::OAuth2( OAuth2::with_description([Flow::Implicit( Implicit::new( "https://localhost/auth/dialog", Scopes::from_iter([ ("edit:items", "edit my items"), ("read:items", "read my items") ]), ), )], "my oauth2 flow") ); ``` -------------------------------- ### Actix-web Path Operation with Parameters Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html Demonstrates using utoipa's path attribute with actix-web, including defining responses and parameters for a GET request. ```rust use actix_web::{get, web, HttpResponse, Responder}; use serde_json::json; /// Get Pet by id #[utoipa::path( responses(("status" = 200, "description" = "Pet found from database")), params(("id", "description" = "Pet id")), )] #[get("/pet/{id}")] async fn get_pet_by_id(id: web::Path) -> impl Responder { HttpResponse::Ok().json(json!({ "pet": format!(‘{:?}‘, &id.into_inner()) })) } ``` -------------------------------- ### Example: Define info attribute values Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.OpenApi.html Shows how to override auto-generated info attributes like title and description using the `info` attribute. ```APIDOC _**Define info attribute values used to override auto generated ones from Cargo environment variables.**_ ⓘ``` #[derive(OpenApi)] #[openapi(info( title = "title override", description = include_str!("./path/to/content"), // fail compile cause no such file contact(name = "Test") ))] struct ApiDoc; ``` ``` -------------------------------- ### Construct a new RefBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.RefBuilder.html Use the `new` function to create a new instance of RefBuilder. This is the starting point for configuring a Ref object. ```rust pub fn new() -> RefBuilder ``` -------------------------------- ### Initialize LinkBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/link/struct.LinkBuilder.html Constructs a new, empty LinkBuilder instance. ```rust pub fn new() -> LinkBuilder ``` -------------------------------- ### Implementing Path Trait with Attribute Macro Source: https://docs.rs/utoipa/5.5.0/utoipa/trait.Path.html Example of using the `#[utoipa::path(...)]` attribute macro to automatically implement the Path trait for a function. This is the recommended approach. ```rust /// Get pet by id /// /// Get pet from database by pet database id #[utoipa::path( get, path = "/pets/{id}", responses(("status" = 200, "description" = "Pet found successfully", "body" = Pet), ("status" = 404, "description" = "Pet was not found") ), params( ("id" = u64, Path, "description" = "Pet database id to get Pet for"), ) )] async fn get_pet_by_id(pet_id: u64) -> Pet { Pet { id: pet_id, name: "lightning".to_string(), } } ``` -------------------------------- ### Multiple Request Body Definitions (Explicit Content Types) Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html Shows how to explicitly define content types for multiple request bodies, including JSON and XML, along with examples and descriptions. ```rust request_body(description = "Common description", content( (Pet = "application/json", examples(..., ...), example = ...), (Pet2 = "text/xml", examples(..., ...), example = ...) ) ) ``` -------------------------------- ### AnyOf Struct Definition Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.AnyOf.html Defines the structure of the AnyOf composite object, including its items, schema type, description, default, example, examples, discriminator, and extensions. ```rust pub struct AnyOf { pub items: Vec>, pub schema_type: SchemaType, pub description: Option, pub default: Option, pub example: Option, pub examples: Vec, pub discriminator: Option, pub extensions: Option, } ``` -------------------------------- ### Create Info using InfoBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/info/struct.InfoBuilder.html Demonstrates how to construct an Info object using the InfoBuilder's chainable methods for title, version, and contact information. ```rust let info = InfoBuilder::new() .title("My api") .version("1.0.0") .contact(Some(ContactBuilder::new() .name(Some("Admin Admin")) .email(Some("amdin@petapi.com")) .build() )) .build(); ``` -------------------------------- ### Retrieve Value from HashMap with `get` Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/extensions/struct.Extensions.html Use the `get` method to retrieve an optional reference to a value associated with a key. The key can be any borrowed form of the map's key type. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### Define OpenApi Schema with Paths and Components Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.OpenApi.html Illustrates defining a complete OpenAPI schema including paths, components, security schemes, tags, and external documentation. ```rust #[derive(ToSchema)] struct Pet { name: String, age: i32, } #[derive(ToSchema)] enum Status { Active, InActive, Locked, } #[utoipa::path(get, path = "/pet")] fn get_pet() -> Pet { Pet { name: "bob".to_string(), age: 8, } } #[utoipa::path(get, path = "/status")] fn get_status() -> Status { Status::Active } #[derive(OpenApi)] #[openapi( paths(get_pet, get_status), components(schemas(Pet, Status)), security( (), ("my_auth" = ["read:items", "edit:items"]), ("token_jwt" = []) ), tags( (name = "pets::api", description = "All about pets", external_docs(url = "http://more.about.pets.api", description = "Find out more")) ), external_docs(url = "http://more.about.our.apis", description = "More about our APIs") )] struct ApiDoc; ``` -------------------------------- ### IntoParams with Path and Query Parameters using Actix-web Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.IntoParams.html Demonstrates how to use IntoParams to resolve Path and Query parameters with actix-web. Ensure serde and utoipa are included as dependencies. ```rust use actix_web::{get, HttpResponse, Responder}; use actix_web::web::{Path, Query}; use serde::Deserialize; use serde_json::json; use utoipa::IntoParams; #[derive(Deserialize, IntoParams)] struct PetPathArgs { /// Id of pet id: i64, /// Name of pet name: String, } #[derive(Deserialize, IntoParams)] struct Filter { /// Age filter for pets #[deprecated] #[param(style = Form, explode, allow_reserved, example = json!([10]))] age: Option>, } #[utoipa::path( params(PetPathArgs, Filter), responses=( (status = 200, description = "success response") ) )] #[get("/pet/{id}/{name}")] async fn get_pet(pet: Path, query: Query) -> impl Responder { HttpResponse::Ok().json(json!({ "id": pet.id })) } ``` -------------------------------- ### OneOf Struct Definition Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.OneOf.html Defines the structure of a OneOf schema component, including its items, schema type, and optional fields like title, description, default, example, examples, discriminator, and extensions. ```rust pub struct OneOf { pub items: Vec>, pub schema_type: SchemaType, pub title: Option, pub description: Option, pub default: Option, pub example: Option, pub examples: Vec, pub discriminator: Option, pub extensions: Option, } ``` -------------------------------- ### Constructing Info Object Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/info/struct.Info.html Demonstrates how to create a new Info object using the `Info::new` constructor, which requires the API title and version. ```rust let info = Info::new("Pet api", "1.1.0"); ``` -------------------------------- ### Enum Variant Optional Configuration Source: https://docs.rs/utoipa/5.5.0/utoipa/derive.ToSchema.html Various optional configurations like `example`, `examples`, `default`, `title`, `xml`, `rename`, `rename_all`, `deprecated`, `max_properties`, `min_properties`, and `no_recursion` can be applied to enum variants. ```rust #[serde(schema( title = "MyEnumVariantTitle", rename = "MyVariantName", deprecated = true, max_properties = 10, min_properties = 1, example = json!({ "key": "value" }), examples( json!({ "key1": "value1" }), json!({ "key2": "value2" }) ), default = json!({ "default_key": "default_value" }), xml(name = "MyXmlName"), no_recursion ))] MyVariantName { field1: String, field2: i32 } ``` -------------------------------- ### HashMap Is Empty Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/extensions/struct.Extensions.html Checks if a HashMap is empty, returning true if it contains no elements. ```rust use std::collections::HashMap; let mut a = HashMap::new(); assert!(a.is_empty()); a.insert(1, "a"); assert!(!a.is_empty()); ``` -------------------------------- ### Create Server with Alternative Server URL Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/server/struct.Server.html Constructs a new Server instance with a full alternative server URL. This allows specifying a complete base URL for API requests. ```rust Server::new("https://alternative.pet-api.test/api/v1"); ``` -------------------------------- ### Construct TagBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/tag/struct.TagBuilder.html Creates a new instance of TagBuilder. This is the starting point for configuring a Tag. ```rust pub fn new() -> TagBuilder ``` -------------------------------- ### Create Server with Relative Path Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/server/index.html Use `Server::new()` to create a server object with a relative path. This path will be appended to the server address. ```rust Server::new("/api/v1"); ``` -------------------------------- ### Construct RequestBodyBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/request_body/struct.RequestBodyBuilder.html Creates a new instance of RequestBodyBuilder. This is the starting point for building a RequestBody. ```rust pub fn new() -> RequestBodyBuilder ``` -------------------------------- ### Create Server with Variable Substitution using Builder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/server/index.html Configure a server URL with variable placeholders using `ServerBuilder` and `ServerVariableBuilder`. This allows for dynamic URL generation based on provided parameters. ```rust ServerBuilder::new().url("/api/{version}/{username}") .parameter("version", ServerVariableBuilder::new() .enum_values(Some(["v1", "v2"])) .default_value("v1")) .parameter("username", ServerVariableBuilder::new() .default_value("the_user")).build(); ``` -------------------------------- ### HashMap Iterator Example Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/extensions/struct.Extensions.html Iterate over key-value pairs in a HashMap. Note that iteration performance is O(capacity). ```rust use std::collections::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); for (key, val) in map.iter() { println!("key: {key} val: {val}"); } ``` -------------------------------- ### Deprecated GET Pet by ID Endpoint Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html Retrieves a pet by its ID. This operation is marked as deprecated. ```APIDOC ## GET /pet/{id} ### Description Retrieves a pet by its ID from the database. ### Method GET ### Endpoint /pet/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - Pet id #### Query Parameters None ### Response #### Success Response (200) - **Pet** (object) - Pet found from database #### Response Example ```json { "pet": "1" } ``` ### Deprecated This operation is deprecated. ``` -------------------------------- ### Using Links in Response Definitions Source: https://docs.rs/utoipa/5.5.0/utoipa/attr.path.html This example demonstrates how to define links within an API response, allowing clients to discover related operations. It includes specifying operation IDs, parameters, request bodies, and servers. ```rust #[utoipa::path( get, path = "/test-links", responses( (status = 200, description = "success response", links( ("getFoo" = ( operation_id = "test_links", parameters(("key" = "value"), ("json_value" = json!(1))), request_body = "this is body", server(url = "http://localhost") )), ("getBar" = ( operation_ref = "this is ref" )) ) ) ), )] async fn test_links() -> &'static str { "" } ``` -------------------------------- ### Create a New ObjectBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.ObjectBuilder.html Constructs a new instance of ObjectBuilder to start configuring an OpenAPI Object. ```rust pub fn new() -> ObjectBuilder ``` -------------------------------- ### Manual OpenApi Implementation Source: https://docs.rs/utoipa/5.5.0/utoipa/trait.OpenApi.html A manual implementation of the OpenApi trait, demonstrating how to construct the OpenAPI specification programmatically using `OpenApiBuilder`. ```rust struct OpenApiDoc; impl utoipa::OpenApi for OpenApiDoc { fn openapi() -> utoipa::openapi::OpenApi { use utoipa::{ToSchema, Path}; utoipa::openapi::OpenApiBuilder::new() .info(utoipa::openapi::InfoBuilder::new() .title("application name") .version("version") .description(Some("application description")) .license(Some(utoipa::openapi::License::new("MIT"))) .contact( Some(utoipa::openapi::ContactBuilder::new() .name(Some("author name")) .email(Some("author email")).build()), ).build()) .paths(utoipa::openapi::path::Paths::new()) .components(Some(utoipa::openapi::Components::new())) .build() } } ``` -------------------------------- ### Construct HttpBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/security/struct.HttpBuilder.html Creates a new instance of HttpBuilder. This is the starting point for configuring an Http security scheme. ```rust pub struct HttpBuilder { /* private fields */ } ``` -------------------------------- ### Build Server from ServerBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/server/struct.ServerBuilder.html Constructs a Server object using the configuration set in the ServerBuilder. This consumes the builder. ```rust pub fn build(self) -> Server ``` -------------------------------- ### Create Xml with XmlBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/xml/struct.XmlBuilder.html Demonstrates how to create an Xml object using XmlBuilder by setting the name and prefix. This is a common pattern for configuring Xml elements. ```rust let xml = XmlBuilder::new() .name(Some("some_name")) .prefix(Some("prefix")) .build(); ``` -------------------------------- ### Construct New ArrayBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/struct.ArrayBuilder.html Creates a new instance of ArrayBuilder. This is the starting point for configuring an Array schema. ```rust let _ = ArrayBuilder::new(); ``` -------------------------------- ### Manual ToSchema Implementation with Schema References Source: https://docs.rs/utoipa/5.5.0/utoipa/trait.ToSchema.html Shows how to manually implement `ToSchema` and `PartialSchema` for a type that references other types, ensuring that nested schemas are correctly included in the OpenAPI document. ```rust #[derive(ToSchema)] struct Owner { name: String } struct Pet { owner: Owner, name: String } impl PartialSchema for Pet { fn schema() -> utoipa::openapi::RefOr { utoipa::openapi::schema::Object::builder() .property("owner", Owner::schema()) .property("name", String::schema()) .into() } } impl ToSchema for Pet { fn schemas( schemas: &mut Vec<(String, utoipa::openapi::RefOr)>) { schemas.push((Owner::name().into(), Owner::schema())); ::schemas(schemas); } } ``` -------------------------------- ### Construct OpenApi Instance Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/struct.OpenApi.html Creates a new `OpenApi` object using the `new` constructor, which requires `Info` metadata and `Paths` for the API. This is a fundamental way to initialize an OpenAPI document. ```rust let openapi = OpenApi::new(Info::new("pet api", "0.1.0"), Paths::new()); ``` -------------------------------- ### Create OpenApi using OpenApiBuilder Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/struct.OpenApiBuilder.html Demonstrates the basic usage of OpenApiBuilder to create an OpenAPI object with essential information like API title, version, paths, and components. ```rust let openapi = OpenApiBuilder::new() .info(Info::new("My api", "1.0.0")) .paths(Paths::new()) .components(Some( Components::new() )) .build(); ``` -------------------------------- ### Create String SchemaType Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/schema/enum.Type.html Shows how to create a `SchemaType` for a string using the `SchemaType::new` constructor. ```rust let _ = SchemaType::new(Type::String); ``` -------------------------------- ### get Source: https://docs.rs/utoipa/5.5.0/utoipa/openapi/extensions/struct.Extensions.html Returns a reference to the value corresponding to the key. The key can be any borrowed form of the map’s key type. ```APIDOC ## pub fn get(&self, k: &Q) -> Option<&V> ### Description Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map’s key type, but `Hash` and `Eq` on the borrowed form must match those for the key type. ### Method `get` ### Parameters #### Path Parameters - **k** (&Q) - Required - The key to look up. ### Response - **Option<&V>** - Returns `Some(&V)` if the key exists, `None` otherwise. ``` -------------------------------- ### Derive IntoParams for Struct Source: https://docs.rs/utoipa/5.5.0/utoipa/trait.IntoParams.html Demonstrates how to derive the IntoParams trait for a struct. This requires additional setup with endpoint definitions. ```rust use utoipa::{IntoParams}; #[derive(IntoParams)] struct PetParams { /// Id of pet id: i64, /// Name of pet name: String, } ```