utoipa - Auto-generated OpenAPI documentation
Pronounced /ju:ˈtoʊ:i.pɑ/ or /ju:ˈtoʊˌaɪ.piˈeɪ/ whatever works better for you.
Want to have your API documented with OpenAPI? But don't want to be bothered
with manual YAML or JSON tweaking? Would like it to be so easy that it would almost
be utopic? Don't worry: utoipa is here to fill this gap. It aims to do, if not all, then
most of the heavy lifting for you, enabling you to focus on writing the actual API logic instead of
documentation. It aims to be minimal, simple and fast. It uses simple proc macros which
you can use to annotate your code to have items documented.
The utoipa crate provides auto-generated OpenAPI documentation for Rust REST APIs. It treats
code-first approach as a first class citizen and simplifies API documentation by providing
simple macros for generating the documentation from your code.
It also contains Rust types of the OpenAPI spec, allowing you to write the OpenAPI spec only using Rust if auto generation is not your flavor or does not fit your purpose.
Long term goal of the library is to be the place to go when OpenAPI documentation is needed in any Rust codebase.
Utoipa is framework-agnostic, and could be used together with any web framework, or even without one. While being portable and standalone, one of its key aspects is simple integration with web frameworks.
Choose your flavor and document your API with ice-cold IPA
Refer to the existing examples for building the "todo" app in the following frameworks:
All examples include a Swagger-UI unless stated otherwise.
There are also examples of building multiple OpenAPI docs in one application, each separated in Swagger UI. These examples exist only for the actix and warp frameworks.
Even if there is no example for your favourite framework, utoipa can be used with any
web framework which supports decorating functions with macros similarly to the warp and tide examples.
Community examples
What's up with the word play?
The name comes from the words utopic and api where uto are the first three letters of utopic
and the ipa is api reversed. Aaand... ipa is also an awesome type of beer :beer:.
Crate Features
- yaml Enables serde_yaml serialization of OpenAPI objects.
- actix_extras Enhances actix-web integration with being able to
parse
path,pathandqueryparameters from actix web path attribute macros. See docs or examples for more details. - rocket_extras Enhances rocket framework integration with being
able to parse
path,pathandqueryparameters from rocket path attribute macros. See docs or examples for more details. - axum_extras Enhances axum framework integration allowing users to use
IntoParamswithout defining theparameter_inattribute. See docs or examples for more details. - debug Add extra traits such as debug traits to openapi definitions and elsewhere.
- chrono Add support for chrono
DateTime,Date,NaiveDate,NaiveDateTime,NaiveTimeandDurationtypes. By default these types are parsed tostringtypes with additionalformatinformation.format: date-timeforDateTimeandNaiveDateTimeandformat: dateforDateandNaiveDateaccording RFC3339 asISO-8601. To override defaultstringrepresentation users have to usevalue_typeattribute to override the type. See docs for more details. - time Add support for time
OffsetDateTime,PrimitiveDateTime,Date, andDurationtypes. By default these types are parsed asstring.OffsetDateTimeandPrimitiveDateTimewill usedate-timeformat.Datewill usedateformat andDurationwill not have any format. To override defaultstringrepresentation users have to usevalue_typeattribute to override the type. See docs for more details. - decimal Add support for rust_decimal
Decimaltype. By default it is interpreted asString. If you wish to change the format you need to override the type. See thevalue_typein component derive docs. - uuid Add support for uuid.
Uuidtype will be presented asStringwith formatuuidin OpenAPI spec. - ulid Add support for ulid.
Ulidtype will be presented asStringwith formatulidin OpenAPI spec. - smallvec Add support for smallvec.
SmallVecwill be treated asVec. - openapi_extensions Adds traits and functions that provide extra convenience functions.
See the
request_bodydocs for an example. - repr Add support for repr_serde's
repr(u*)andrepr(i*)attributes to unit type enums for C-like enum representation. See docs for more details. - preserve_order Preserve order of properties when serializing the schema for a component. When enabled, the properties are listed in order of fields in the corresponding struct definition. When disabled, the properties are listed in alphabetical order.
- preserve_path_order Preserve order of OpenAPI Paths according to order they have been
introduced to the
#[openapi(paths(...))]macro attribute. If disabled the paths will be ordered in alphabetical order. - indexmap Add support for indexmap. When enabled
IndexMapwill be rendered as a map similar toBTreeMapandHashMap. - non_strict_integers Add support for non-standard integer formats
int8,int16,uint8,uint16,uint32, anduint64. - rc_schema Add
ToSchemasupport forArc<T>andRc<T>types. Note! serdercfeature flag must be enabled separately to allow serialization and deserialization ofArc<T>andRc<T>types. See more about serde feature flags.
Utoipa implicitly has partial support for serde attributes. See docs for more details.
Install
Add minimal dependency declaration to Cargo.toml.
[]
= "3"
To enable more features such as use actix framework extras you could define the dependency as follows.
[]
= { = "3", = ["actix_extras"] }
Note! To use utoipa together with Swagger UI you can use the utoipa-swagger-ui crate.
Examples
Create a struct, or it could also be an enum. Add ToSchema derive macro to it, so it can be registered
as an OpenAPI schema.
use ToSchema;
Create a handler that would handle your business logic and add path proc attribute macro over it.
Utoipa has support for http StatusCode in responses.
This attribute macro will create another struct named with __path_ prefix + handler function name.
So when you implement some_handler function in different file and want to export this, make sure __path_some_handler
in the module can also be accessible from the root.
Tie the Schema and the endpoint above to the OpenAPI schema with following OpenApi derive proc macro.
use OpenApi;
;
println!;
This would produce api doc something similar to:
Modify OpenAPI at runtime
You can modify generated OpenAPI at runtime either via generated types directly or using Modify trait.
Modify generated OpenAPI via types directly.
;
let mut doc = openapi;
doc.info.title = Stringfrom;
You can even convert the generated OpenApi to OpenApiBuilder.
let builder: OpenApiBuilder = openapi.into;
See Modify trait for examples on how to modify generated OpenAPI via it.
Go beyond the surface
- See how to serve OpenAPI doc via Swagger UI check utoipa-swagger-ui crate for more details.
- Browse to examples for more comprehensive examples.
- Check IntoResponses and ToResponse for examples on deriving responses.
- More about OpenAPI security in security documentation.
- Dump generated API doc to file at build time. See issue 214 comment.
General Pitfalls
Swagger UI returns 404 NotFound from built binary
This is highly probably due to RustEmbed not embedding the Swagger UI to the executable. This is natural since the RustEmbed
library does not by default embed files on debug builds. To get around this you can do one of the following.
- Build your executable in
--releasemode - or add
debug-embedfeature flag to yourCargo.tomlforutoipa-swagger-ui. This will enable thedebug-emebedfeature flag forRustEmbedas well. Read more about this here and here.
Find utoipa-swagger-ui feature flags here.
License
Licensed under either of Apache 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, shall be dual licensed, without any additional terms or conditions.