Home

Awesome

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

FlavorSupport
actix-webParse path, path parameters and query parameters, recognize request body and response body, utoipa-actix-web bindings. See more at docs
axumParse path and query parameters, recognize request body and response body, utoipa-axum bindings. See more at docs
rocketParse 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

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

Default Library Support

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());
<details> <summary><i><b>Above example will produce an OpenAPI doc like this:</b></i></summary>
{
  "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"
          }
        }
      }
    }
  }
}
</details>

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

Swagger UI returns 404 NotFound from built binary

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.

  1. Build your executable in --release mode
  2. or add debug-embed feature flag to your Cargo.toml for utoipa-swagger-ui. This will enable the debug-emebed feature flag for RustEmbed as well. Read more about this here and here.

Find utoipa-swagger-ui feature flags here.

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.