Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

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

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
NotificationsYou must be signed in to change notification settings

juhaku/utoipa

Repository files navigation

Utoipa buildcrates.iodocs.rsMSRV

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 botheredwith manual YAML or JSON tweaking? Would like it to be so easy that it would almostbe utopic? Don't worry: utoipa is here to fill this gap. It aims to do, if not all, thenmost of the heavy lifting for you, enabling you to focus on writing the actual API logic instead ofdocumentation. It aims to beminimal,simple andfast. It uses simpleproc macros whichyou can use to annotate your code to have items documented.

Theutoipa crate provides auto-generated OpenAPI documentation for Rust REST APIs. It treatscode-first approach as a first class citizen and simplifies API documentation by providingsimple 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 usingRust 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 Rustcodebase.

Utoipa is framework-agnostic, and could be used together with any web framework, or even without one. Whilebeing 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 atdocs
axumParse path and query parameters, recognize request body and response body,utoipa-axum bindings. See more atdocs
rocketParse path, path parameters and query parameters, recognize request body and response body. See more atdocs
Others*Plainutoipa without extra flavor. This gives you all the basic benefits listed below inFeatures section but with little less automation.

Others* = For examplewarp but could be anything.

Refer to the existingexamples 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 implementingToSchema manually should not have generic arguments, asthey 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 fromrequest_body attribute.
    • Response body from responsebody attribute or responsecontent attribute.
  • Various OpenAPI visualization tools supported out of the box.
  • Rust type aliases viautoipa-config.

What's up with the word play?

The name comes from the wordsutopic andapi whereuto are the first three letters ofutopicand theipa isapi reversed. Aaand...ipa is also an awesome type of beer 🍺.

Crate Features

  • macros Enableutoipa-gen macros.This is enabled by default.
  • yaml: Enablesserde_norway serialization of OpenAPI objects.
  • actix_extras: Enhancesactix-web integration with being able toparsepath,path andquery parameters from actix web path attribute macros. Seedocs orexamples for more details.
  • rocket_extras: Enhancesrocket framework integration with beingable to parsepath,path andquery parameters from rocket path attribute macros. Seedocsorexamples for more details.
  • axum_extras: Enhancesaxum framework integration allowing users to useIntoParams withoutdefining theparameter_in attribute. Seedocsorexamples for more details.
  • debug: Add extra traits such as debug traits to openapi definitions and elsewhere.
  • chrono: Add support forchronoDateTime,Date,NaiveDate,NaiveDateTime,NaiveTime andDurationtypes. By default these types are parsed tostring types with additionalformat information.format: date-time forDateTime andNaiveDateTime andformat: date forDate andNaiveDate accordingRFC3339 asISO-8601. Tooverride defaultstring representation users have to usevalue_type attribute to override the type.Seedocs for more details.
  • time: Add support fortimeOffsetDateTime,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 attributeto override the type. Seedocs for more details.
  • decimal: Add support forrust_decimalDecimal type.By defaultit is interpreted asString. If you wish to change the format you need to override the type.See thevalue_type incomponent derive docs.
  • decimal_float: Add support forrust_decimalDecimal type.By defaultit is interpreted asNumber. This feature is mutually exclusive withdecimal and allow to change the default type used in yourdocumentation forDecimal much likeserde_with_float feature exposed by rust_decimal.
  • uuid: Add support foruuid.Uuid type will be presented asString withformatuuid in OpenAPI spec.
  • ulid: Add support forulid.Ulid type will be presented asString withformatulid in OpenAPI spec.
  • url: Add support forurl.Url type will be presented asString withformaturi in OpenAPI spec.
  • smallvec: Add support forsmallvec.SmallVec will be treated asVec.
  • openapi_extensions: Adds traits and functions that provide extra convenience functions.See therequest_body docs for an example.
  • repr: Add support forrepr_serde'srepr(u*) andrepr(i*) attributes to unit type enums forC-like enum representation. Seedocs 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 beenintroduced to the#[openapi(paths(...))] macro attribute. If disabled the paths will beordered in alphabetical order.However the operations order under the pathwill be always constant according tospecification
  • indexmap: Add support forindexmap. When enabledIndexMap will be rendered as a map similar toBTreeMap andHashMap.
  • non_strict_integers: Add support for non-standard integer formatsint8,int16,uint8,uint16,uint32, anduint64.
  • rc_schema: AddToSchema support forArc<T> andRc<T> types.Note! serderc feature flag must be enabled separately to allowserialization and deserialization ofArc<T> andRc<T> types. See more aboutserde feature flags.
  • config Enablesutoipa-config for the project which allows defining global configuration options forutoipa.

Default Library Support

  • Implicit partial support forserde attributes. Seedocs for more details.
  • Support forhttpStatusCode in responses.

Install

Add dependency declaration toCargo.toml.

[dependencies]utoipa ="5"

Examples

Create type withToSchema and use it in#[utoipa::path(...)] that is registered to theOpenApi.

use utoipa::{OpenApi,ToSchema};#[derive(ToSchema)]structPet{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"),))]asyncfnget_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))]structApiDoc;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 usingModify trait.

Modify generated OpenAPI via types directly.

#[derive(OpenApi)]#[openapi(    info(description ="My Api description"),)]structApiDoc;letmut doc =ApiDoc::openapi();doc.info.title =String::from("My Api");

You can even convert the generatedOpenApi toOpenApiBuilder.

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

SeeModify 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 toRustEmbed not embedding the Swagger UI to the executable. This is natural since theRustEmbedlibrarydoes 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 adddebug-embed feature flag to yourCargo.toml forutoipa-swagger-ui. This will enable thedebug-emebed feature flag forRustEmbed as well. Read more about thishere andhere.

Findutoipa-swagger-uifeature flags here.

How to implementToSchema for external type?

There are few ways around this that are elaboratedhere 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 thatjust does this for you calledutoipauto.

License

Licensed under either ofApache 2.0 orMIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crateby you, shall be dual licensed, without any additional terms or conditions.


[8]ページ先頭

©2009-2025 Movatter.jp