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
| Flavor | Support |
|---|---|
| actix-web | Parse path, path parameters and query parameters, recognize request body and response body, utoipa-actix-web bindings. See more at docs |
| axum | Parse path and query parameters, recognize request body and response body, utoipa-axum bindings. See more at docs |
| rocket | Parse path, path parameters and query parameters, recognize request body and response body. See more at docs |
| Others* | Plain utoipa without extra flavor. This gives you all the basic benefits listed below in Features section but with little less automation. |
Others* = For example warp but could be anything.
Refer to the existing examples to find out more.
§Features
- OpenAPI 3.1
- Pluggable, easy setup and integration with frameworks.
- No bloat, enable what you need.
- Support for generic types
- Note!
Tuples, arrays and slices cannot be used as generic arguments on types. Types implementingToSchemamanually should not have generic arguments, as they are not composeable and will result compile error.
- Note!
- Automatic schema collection from usages recursively.
- Request body from either handler function arguments (if supported by framework) or from
request_bodyattribute. - Response body from response
bodyattribute or responsecontentattribute.
- Request body from either handler function arguments (if supported by framework) or from
- Various OpenAPI visualization tools supported out of the box.
- Rust type aliases via
utoipa-config.
§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
macrosEnableutoipa-genmacros. This is enabled by default.yamlEnables serde_norway serialization of OpenAPI objects.actix_extrasEnhances actix-web integration with being able to parsepath,pathandqueryparameters from actix web path attribute macros. See actix extras support or examples for more details.rocket_extrasEnhances rocket framework integration with being able to parsepath,pathandqueryparameters from rocket path attribute macros. See rocket extras support or examples for more detailsaxum_extrasEnhances axum framework integration allowing users to useIntoParamswithout defining theparameter_inattribute. See axum extras support or examples for more details.debugAdd extra traits such as debug traits to openapi definitions and elsewhere.chronoAdd support for chronoDateTime,Date,NaiveDate,NaiveTimeandDurationtypes. By default these types are parsed tostringtypes with additionalformatinformation.format: date-timeforDateTimeandformat: dateforDateandNaiveDateaccording RFC3339 asISO-8601. To override defaultstringrepresentation users have to usevalue_typeattribute to override the type. See docs for more details.timeAdd support for timeOffsetDateTime,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.jiff_0_2Add support for jiff 0.2Zoned, andcivil::Datetypes. By default these types are parsed asstring.Zonedwill usedate-timeformat.civil::Datewill usedateformat. To override defaultstringrepresentation users have to usevalue_typeattribute to override the type. See docs for more details.decimalAdd support for rust_decimalDecimaltype. By default it is interpreted asString. If you wish to change the format you need to override the type. See thevalue_typeinToSchemaderive docs.decimal_floatAdd support for rust_decimalDecimaltype. By default it is interpreted asNumber. This feature is mutually exclusive with decimal and allow to change the default type used in your documentation forDecimalmuch likeserde_with_floatfeature exposed by rust_decimal.uuidAdd support for uuid.Uuidtype will be presented asStringwith formatuuidin OpenAPI spec.ulidAdd support for ulid.Ulidtype will be presented asStringwith formatulidin OpenAPI spec.urlAdd support for url.Urltype will be presented asStringwith formaturiin OpenAPI spec.smallvecAdd support for smallvec.SmallVecwill be treated asVec.openapi_extensionsAdds convenience functions for documenting common scenarios, such as JSON request bodies and responses. See therequest_bodyandresponsedocs for examples.reprAdd support for repr_serde’srepr(u*)andrepr(i*)attributes to unit type enums for C-like enum representation. See docs for more details.preserve_orderPreserve 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_orderPreserve 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. However the operations order under the path will be always constant according to specificationindexmapAdd support for indexmap. When enabledIndexMapwill be rendered as a map similar toBTreeMapandHashMap.non_strict_integersAdd support for non-standard integer formatsint8,int16,uint8,uint16,uint32, anduint64.rc_schemaAddToSchemasupport 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.configEnablesutoipa-configfor the project which allows defining global configuration options forutoipa.
§Default Library Support
- Implicit partial support for
serdeattributes. SeeToSchemaderive for more details. - Support for http
StatusCodein responses.
§Install
Add dependency declaration to Cargo.toml.
[dependencies]
utoipa = "5"§Examples
Create type with ToSchema and use it in #[utoipa::path(...)] that is registered to the OpenApi.
use utoipa::{OpenApi, ToSchema};
#[derive(ToSchema)]
struct Pet {
id: u64,
name: String,
age: Option<i32>,
}
/// 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) -> Result<Pet, NotFound> {
Ok(Pet {
id: pet_id,
age: None,
name: "lightning".to_string(),
})
}
#[derive(OpenApi)]
#[openapi(paths(get_pet_by_id))]
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
- See how to serve OpenAPI doc via Swagger UI check
utoipa-swagger-uicrate for more details. - Browse to examples for more comprehensive examples.
- Check
IntoResponsesandToResponsefor examples on deriving responses. - More about OpenAPI security in security documentation.
- Dump generated API doc to file at build time. See issue 214 comment.
Modules§
- openapi
- Rust implementation of Openapi Spec V3.1.
Macros§
- schema
macros - Create OpenAPI Schema from arbitrary type.
Enums§
- Number
- Flexible number wrapper used by validation schema attributes to seamlessly support different number syntaxes.
Traits§
- Into
Params - Trait used to convert implementing type to OpenAPI parameters.
- Into
Responses - This trait is implemented to document a type (like an enum) which can represent multiple responses, to be used in operation.
- Modify
- Trait that allows OpenApi modification at runtime.
- OpenApi
- Trait for implementing OpenAPI specification in Rust.
- Partial
Schema - Trait used to implement only
Schemapart of the OpenAPI doc. - Path
- Trait for implementing OpenAPI PathItem object with path.
- ToResponse
- 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.
- ToSchema
- Trait for implementing OpenAPI Schema object.
Type Aliases§
- Tuple
Unit - Represents
nullabletype. This can be used anywhere where “nothing” needs to be evaluated. This will serialize tonullin JSON andopenapi::schema::emptyis used to create theopenapi::schema::Schemafor the type.
Attribute Macros§
- path
macros - Path attribute macro implements OpenAPI path for the decorated function.
Derive Macros§
- Into
Params macros - Generate path parameters from struct’s fields.
- Into
Responses macros - Generate responses with status codes what
can be attached to the
utoipa::path. - OpenApi
macros - Generate OpenApi base object with defaults from project settings.
- ToResponse
macros - Generate reusable OpenAPI response that can be used
in
utoipa::pathor inOpenApi. - ToSchema
macros - Generate reusable OpenAPI schema to be used
together with
OpenApi.