Crate utoipa

source ·
Expand description

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 autogenerated 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 it’s key aspects is simple integration with web frameworks.

Currently utoipa provides simple integration with actix-web framework but is not limited to the actix-web framework. All functionalities are not restricted to any specific framework.

§Choose your flavor and document your API with ice cold IPA

Existing examples for following frameworks:

  • actix-web
  • axum
  • warp
  • tide
  • rocket

Even if there is no example for your favorite framework utoipa can be used with any web framework which supports decorating functions with macros similarly to warp and tide examples.

§What’s up with the word play?

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.

§Crate Features

  • yaml Enables serde_yaml serialization of OpenAPI objects.
  • actix_extras Enhances actix-web integration with being able to parse path, path and query parameters from actix web path attribute macros. See actix extras support or examples for more details.
  • rocket_extras Enhances rocket framework integration with being able to parse path, path and query parameters from rocket path attribute macros. See rocket extras support or examples for more details
  • axum_extras Enhances axum framework integration allowing users to use IntoParams without defining the parameter_in attribute. See axum extras support 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, NaiveTime and Duration types. By default these types are parsed to string types with additional format information. format: date-time for DateTime and format: date for Date and NaiveDate according RFC3339 as ISO-8601. To override default string representation users have to use value_type attribute to override the type. See docs for more details.
  • time Add support for time OffsetDateTime, PrimitiveDateTime, Date, and Duration types. By default these types are parsed as string. OffsetDateTime and PrimitiveDateTime will use date-time format. Date will use date format and Duration will not have any format. To override default string representation users have to use value_type attribute to override the type. See docs for more details.
  • decimal Add support for rust_decimal Decimal type. By default it is interpreted as String. If you wish to change the format you need to override the type. See the value_type in ToSchema derive docs.
  • uuid Add support for uuid. Uuid type will be presented as String with format uuid in OpenAPI spec.
  • ulid Add support for ulid. Ulid type will be presented as String with format ulid in OpenAPI spec.
  • smallvec Add support for smallvec. SmallVec will be treated as Vec.
  • openapi_extensions Adds convenience functions for documenting common scenarios, such as JSON request bodies and responses. See the request_body and response docs for examples.
  • repr Add support for repr_serde’s repr(u*) and repr(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 IndexMap will be rendered as a map similar to BTreeMap 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 allow serialization and deserialization of Arc<T> and Rc<T> types. See more about serde feature flags.

Utoipa implicitly has partial support for serde attributes. See ToSchema derive for more details.

§Install

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.

§Examples

Create a struct, or it could be an enum also. Add ToSchema derive macro to it so it can be registered as a component in openapi schema.

use utoipa::ToSchema;
#[derive(ToSchema)]
struct Pet {
   id: u64,
   name: String,
   age: Option<i32>,
}

Create an 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.

Tie the above component and api 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());

§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.

#[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 openapi::OpenApiBuilder.

#[derive(OpenApi)]
#[openapi(
    info(description = "My Api description"),
)]
struct ApiDoc;

let builder: OpenApiBuilder = ApiDoc::openapi().into();

See Modify trait for examples on how to modify generated OpenAPI via it.

§Go beyond the surface

Modules§

  • Rust implementation of Openapi Spec V3.

Macros§

  • Create OpenAPI Schema from arbitrary type.

Traits§

  • Trait used to convert implementing type to OpenAPI parameters.
  • This trait is implemented to document a type (like an enum) which can represent multiple responses, to be used in operation.
  • Trait that allows OpenApi modification at runtime.
  • Trait for implementing OpenAPI specification in Rust.
  • Trait used to implement only Schema part of the OpenAPI doc.
  • Trait for implementing OpenAPI PathItem object with path.
  • This trait is implemented to document a type which represents a single response which can be referenced or reused as a component in multiple operations.
  • Trait for implementing OpenAPI Schema object.

Type Aliases§

Attribute Macros§

  • Path attribute macro implements OpenAPI path for the decorated function.

Derive Macros§