Simple, Fast, Code first and Compile time generated OpenAPI documentation for Rust
APACHE-2.0 License
Pronounced /u:ˈtoʊ:i.pɑ/ or /u:ˈ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.
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.
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 🍺.
macros
Enable utoipa-gen
macros. This is enabled by default.
yaml
: Enables serde_yaml serialization of OpenAPI objects.actix_extras
: Enhances actix-web integration with being able topath
, path
and query
parameters from actix web path attribute macros. Seerocket_extras
: Enhances rocket framework integration with beingpath
, path
and query
parameters from rocket path attribute macros. See docsaxum_extras
: Enhances axum framework integration allowing users to use IntoParams
withoutparameter_in
attribute. See docsdebug
: Add extra traits such as debug traits to openapi definitions and elsewhere.chrono
: Add support for chrono DateTime
, Date
, NaiveDate
, NaiveDateTime
, NaiveTime
and Duration
string
types with additional format
information.format: date-time
for DateTime
and NaiveDateTime
and format: date
for Date
and NaiveDate
accordingISO-8601
. Tostring
representation users have to use value_type
attribute to override the type.time
: Add support for time OffsetDateTime
, PrimitiveDateTime
, Date
, and Duration
types.string
. OffsetDateTime
and PrimitiveDateTime
will use date-time
format. Date
will usedate
format and Duration
will not have any format. To override default string
representation users have to use value_type
attributedecimal
: Add support for rust_decimal Decimal
type. By defaultString
. If you wish to change the format you need to override the type.value_type
in component derive docs.decimal_float
: Add support for rust_decimal Decimal
type. By defaultNumber
. This feature is mutually exclusive with decimal and allow to change the default type used in yourDecimal
much like serde_with_float
feature exposed by rust_decimal.uuid
: Add support for uuid. Uuid
type will be presented as String
withuuid
in OpenAPI spec.ulid
: Add support for ulid. Ulid
type will be presented as String
withulid
in OpenAPI spec.url
: Add support for url. Url
type will be presented as String
withuri
in OpenAPI spec.smallvec
: Add support for smallvec. SmallVec
will be treated as Vec
.openapi_extensions
: Adds traits and functions that provide extra convenience functions.request_body
docs for an example.repr
: Add support for repr_serde's repr(u*)
and repr(i*)
attributes to unit type enums forpreserve_order
: Preserve order of properties when serializing the schema for a component.preserve_path_order
: Preserve order of OpenAPI Paths according to order they have been#[openapi(paths(...))]
macro attribute. If disabled the paths will beindexmap
: Add support for indexmap. When enabled IndexMap
will be rendered as a map similar toBTreeMap
and HashMap
.non_strict_integers
: Add support for non-standard integer formats int8
, int16
, uint8
, uint16
, uint32
, and uint64
.rc_schema
: Add ToSchema
support for Arc<T>
and Rc<T>
types. Note! serde rc
feature flag must be enabled separately to allowArc<T>
and Rc<T>
types. See more about serde feature flags.config
Enables utoipa-config
for the project which allows defining global configuration options for utoipa
.Utoipa implicitly has partial support for serde
attributes. See docs for more details.
Add minimal dependency declaration to Cargo.toml
.
[dependencies]
utoipa = "4"
To enable more features such as use actix framework extras you could define the dependency as follows.
[dependencies]
utoipa = { version = "4", features = ["actix_extras"] }
Note! To use utoipa
together with Swagger UI you can use the utoipa-swagger-ui crate.
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 utoipa::ToSchema;
#[derive(ToSchema)]
struct Pet {
id: u64,
name: String,
age: Option<i32>,
}
Create a handler that would handle your business logic and add path
proc attribute macro over it.
mod pet_api {
/// Get pet by id
///
/// Get pet from database by pet id
#[utoipa::path(
get,
path = "/pets/{id}",
responses(
(status = 200, description = "Pet found successfully", body = Pet),
(status = NOT_FOUND, 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,
age: None,
name: "lightning".to_string(),
}
}
}
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 utoipa::OpenApi;
#[derive(OpenApi)]
#[openapi(paths(pet_api::get_pet_by_id), components(schemas(Pet)))]
struct ApiDoc;
println!("{}", ApiDoc::openapi().to_pretty_json().unwrap());
This would produce an API doc something similar to:
{
"openapi": "3.1.0",
"info": {
"title": "application name from Cargo.toml",
"description": "description from Cargo.toml",
"contact": {
"name": "author name from Cargo.toml",
"email": "author email from Cargo.toml"
},
"license": {
"name": "license from Cargo.toml"
},
"version": "version from Cargo.toml"
},
"paths": {
"/pets/{id}": {
"get": {
"tags": [
"pet_api"
],
"summary": "Get pet by id",
"description": "Get pet from database by pet id",
"operationId": "get_pet_by_id",
"parameters": [
{
"name": "id",
"in": "path",
"description": "Pet database id to get Pet for",
"required": true,
"schema": {
"type": "integer",
"format": "int64",
"minimum": 0
}
}
],
"responses": {
"200": {
"description": "Pet found successfully",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Pet"
}
}
}
},
"404": {
"description": "Pet was not found"
}
}
}
}
},
"components": {
"schemas": {
"Pet": {
"type": "object",
"required": [
"id",
"name"
],
"properties": {
"age": {
"type": [
"integer",
"null"
],
"format": "int32"
},
"id": {
"type": "integer",
"format": "int64",
"minimum": 0
},
"name": {
"type": "string"
}
}
}
}
}
}
You can modify generated OpenAPI at runtime either via generated types directly or using Modify trait.
Modify generated OpenAPI via types directly.
#[derive(OpenApi)]
#[openapi(
info(description = "My Api description"),
)]
struct ApiDoc;
let mut doc = ApiDoc::openapi();
doc.info.title = String::from("My Api");
You can even convert the generated OpenApi to OpenApiBuilder.
let builder: OpenApiBuilder = ApiDoc::openapi().into();
See Modify trait for examples on how to modify generated OpenAPI via it.
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.
--release
modedebug-embed
feature flag to your Cargo.toml
for utoipa-swagger-ui
. This will enable the debug-emebed
feature flag forRustEmbed
as well. Read more about this here and here.Find utoipa-swagger-ui
feature flags here.
ToSchema
for external type?There are few ways around this that are elaborated here in detail.
config
feature flag.Currently there is no build in solution to automatically discover the OpenAPI types but for your luck there is a pretty neat crate that just does this for you called utoipauto.
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.