utoipa is a free, open source documentation & knowledge base project written in Rust and released under Apache-2.0. It has 4,141 GitHub stars, 416 forks and 248 open issues, and was last pushed 14 days ago. On this registry it ranks #33 of 100 tracked projects in Documentation & Knowledge Base, with 5 head-to-head comparisons available. It gained 31 stars over the last 30 tracked days.

What is utoipa?

utoipa is an Apache-2.0 licensed Rust crate that generates OpenAPI 3.1 documentation for REST APIs from code annotations at compile time, built for Rust developers who want their API specification to come from the code rather than from hand-maintained YAML or JSON files.

What it is

utoipa is a Rust library that produces OpenAPI documentation for REST APIs using procedural macros. Developers annotate their code, and the library derives the specification from those annotations at compile time, so the documentation tracks the implementation instead of sitting beside it as a separate artifact. The project describes itself as code-first, and treats that approach as a first-class citizen. It is framework-agnostic: it can be used with any web framework, or with no web framework at all. It also ships Rust types covering the OpenAPI spec, which means a specification can be written entirely in Rust when auto-generation does not fit the situation. The crate targets minimum supported Rust version 1.88 and is published on crates.io, with documentation hosted on docs.rs.

The concrete problem it solves is manual specification authoring. Rather than editing YAML or JSON by hand and keeping it in sync with the handlers it describes, a developer writes ordinary Rust and lets the macros do the heavy lifting. The project's stated aim is to let teams focus on API logic instead of documentation upkeep. Its long-term goal is to be the place to go whenever OpenAPI documentation is needed in a Rust codebase.

Key capabilities

  • Generates OpenAPI 3.1 output, as reflected in the openapi31 topic and the README feature list.
  • Uses simple proc macros to annotate code items so they become documented.
  • Provides Rust types of the OpenAPI spec, allowing a spec to be written only in Rust when auto-generation is not wanted.
  • Works framework-agnostically, including with no web framework present.
  • Ships utoipa-actix-web bindings for actix-web, parsing path, path parameters and query parameters, and recognizing request and response bodies.
  • Ships utoipa-axum bindings for axum, parsing path and query parameters and recognizing request and response bodies.
  • Supports Rocket directly, parsing path, path parameters and query parameters and recognizing request and response bodies.

Who uses it and how

  • Rust teams running actix-web APIs, who add the utoipa-actix-web bindings to get path, parameter and body recognition without extra wiring.
  • axum teams, who use utoipa-axum for the same style of annotation-driven generation.
  • Rocket teams, who get path, path parameter and query parameter parsing plus request and response body recognition without a separate bindings crate.
  • Teams on other frameworks such as warp, or teams with no framework, who use plain utoipa for the basic benefits with less automation, following the examples in the repository.
  • Library and service authors who want the specification expressed as Rust types rather than as a separate document.

Getting started

Install the utoipa crate from crates.io, adding utoipa-actix-web or utoipa-axum when using those frameworks. The crate requires Rust 1.88 or newer, and reference documentation and examples live on docs.rs and in the repository's examples directory.

How it compares

No comparable documentation tool is named in the facts provided, so utoipa stands alone in this registry. What it plainly displaces is the manual YAML and JSON tweaking workflow that the README calls out as the gap the project exists to fill.

When to use it — and when not to

There is nothing to operate: utoipa is a library, so no database, object storage, SMTP service or server process comes with it, which removes the hosting burden that self-hosted documentation platforms carry. It is not a fit for non-Rust projects, since the entire mechanism depends on Rust procedural macros and, for the framework integrations, on actix-web, axum or Rocket specifically. The honest caveats are that the repository carries 248 open issues and that the README excerpt available here documents features and framework bindings but shows no explicit installation command, so a new user should confirm current setup steps against the crate's docs.rs page before starting.

project readme (upstream, from github) — read inline

utoipa - Auto-generated OpenAPI documentation

Utoipa build crates.io docs.rs MSRV

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.

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 implementing ToSchema manually should not have generic arguments, as they are not composeable and will result compile error.
  • Automatic schema collection from usages recursively.
    • Request body from either handler function arguments (if supported by framework) or from request_body attribute.
    • Response body from response body attribute or response content attribute.
  • 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 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

  • macros Enable utoipa-gen macros. This is enabled by default.
  • yaml: Enables yaml_serde 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 docs 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 docs or examples for more details.
  • axum_extras: Enhances axum framework integration allowing users to use IntoParams without defining the parameter_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, NaiveDateTime, NaiveTime and Duration types. By default these types are parsed to string types with additional format information. format: date-time for DateTime and NaiveDateTime 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.
  • jiff_0_2 Add support for jiff 0.2 Timestamp, Zoned, and civil::Date types. By default these types are parsed as string. Timestamp and Zoned will use date-time format. civil::Date will use date 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 component derive docs.
  • decimal_float: Add support for rust_decimal Decimal type. By default it is interpreted as Number. This feature is mutually exclusive with decimal and allow to change the default type used in your documentation for Decimal much like serde_with_float feature exposed by rust_decimal.
  • bigdecimal: Add support for bigdecimal BigDecimal 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 component derive docs.
  • bigdecimal_float: Add support for bigdecimal BigDecimal type. By default it is interpreted as Number. This feature is mutually exclusive with bigdecimal and allows changing the default type used in your documentation for BigDecimal.
  • 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.
  • url: Add support for url. Url type will be presented as String with format uri 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. See the request_body docs for an example.
  • 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. However the operations order under the path will be always constant according to specification
  • 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 and Rc types. Note! serde rc feature flag must be enabled separately to allow serialization and deserialization of Arc and Rc types. See more about serde feature flags.
  • config Enables utoipa-config for the project which allows defining global configuration options for utoipa.

Default Library Support

  • Implicit partial support for serde attributes. See docs for more details.
  • Support for http StatusCode in 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>,
}

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) -> Result<Pet, NotFound> {
        Ok(Pet {
            id: pet_id,
            age: None,
            name: "lightning".to_string(),
        })
    }
}

#[derive(OpenApi)]
#[openapi(paths(pet_api::get_pet_by_id))]
struct ApiDoc;

println!("{}", ApiDoc::openapi().to_pretty_json().unwrap());
Above example will produce an OpenAPI doc like this:
{
  "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"
          }
        }
      }
    }
  }
}

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

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

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

Go beyond the surface

FAQ

How to implement ToSchema for external type?

There are few ways around this that are elaborated here in detail.

Auto discover for OpenAPI schemas and paths?

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.

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.

Frequently asked questions

Is utoipa free to use?

utoipa is open source under the Apache-2.0 licence. There is no licence fee and no seat count — you can self-host it or, where the project offers one, pay a vendor for a managed version instead.

What does utoipa do?

Simple, Fast, Code first and Compile time generated OpenAPI documentation for Rust

What is utoipa written in?

utoipa is primarily written in Rust. Its source is publicly available at https://github.com/juhaku/utoipa, and it has 4,141 GitHub stars.