Want to have your API documented with OpenAPI? But you don't want to see the trouble with manual YAML or JSON tweaking? Would like it to be so easy that it would almost be like utopic? Don't worry utoipa is just there to fill this gap. It aims to do if not all then the most of heavy lifting for you enabling you to focus 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.
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 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 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.
Existing examples for following 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 warp and tide examples.
The name comes from words utopic
and api
where uto
is the first three letters of utopic
and the ipa
is api reversed. Aaand... ipa
is also awesome type of beer 🍺.
- yaml Enables serde_yaml serialization of OpenAPI objects.
- actix_extras Enhances actix-web integration with being able to
parse
path
,path
andquery
parameters 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
,path
andquery
parameters from rocket path attribute macros. See docs or examples for more details. - axum_extras Enhances axum framework integration allowing users to use
IntoParams
without defining theparameter_in
attribute. 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
andDuration
types. By default these types are parsed tostring
types with additionalformat
information.format: date-time
forDateTime
andformat: date
forDate
andNaiveDate
according RFC3339 asISO-8601
. To override defaultstring
representation users have to usevalue_type
attribute to override the type. See docs for more details. - time Add support for time
OffsetDateTime
,PrimitiveDateTime
,Date
, andDuration
types. By default these types are parsed asstring
.OffsetDateTime
andPrimitiveDateTime
will usedate-time
format.Date
will usedate
format andDuration
will not have any format. To override defaultstring
representation users have to usevalue_type
attribute to override the type. See docs for more details. - decimal Add support for rust_decimal
Decimal
type. By default it is interpreted asString
. If you wish to change the format you need to override the type. See thevalue_type
in component derive docs. - uuid Add support for uuid.
Uuid
type will be presented asString
with formatuuid
in OpenAPI spec. - smallvec Add support for smallvec.
SmallVec
will be treated asVec
. - openapi_extensions Adds traits and functions that provide extra convenience functions.
See the
request_body
docs 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.
Utoipa implicitly has partial support for serde
attributes. See docs for more details.
Add minimal dependency declaration to Cargo.toml.
[dependencies]
utoipa = "3"
To enable more features such as use actix framework extras you could define the dependency as follows.
[dependencies]
utoipa = { version = "3", 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 be an enum also. 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 succesfully", 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 substantially 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 api doc something similar to:
{
"openapi": "3.0.3",
"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 by id\n\nGet pet from database by pet id\n",
"operationId": "get_pet_by_id",
"parameters": [
{
"name": "id",
"in": "path",
"description": "Pet database id to get Pet for",
"required": true,
"deprecated": false,
"schema": {
"type": "integer",
"format": "int64"
}
}
],
"responses": {
"200": {
"description": "Pet found succesfully",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Pet"
}
}
}
},
"404": {
"description": "Pet was not found"
}
},
"deprecated": false
}
}
},
"components": {
"schemas": {
"Pet": {
"type": "object",
"required": ["id", "name"],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"age": {
"type": "integer",
"format": "int32"
}
}
}
}
}
}
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.
- 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.
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.