Skip to content

Commit

Permalink
Misc document improvements (#814)
Browse files Browse the repository at this point in the history
  • Loading branch information
jayvdb authored Dec 3, 2023
1 parent beb68fa commit 7e49344
Show file tree
Hide file tree
Showing 14 changed files with 87 additions and 86 deletions.
50 changes: 26 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ and the `ipa` is _api_ reversed. Aaand... `ipa` is also an awesome type of beer
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](https://docs.rs/utoipa/latest/utoipa/derive.ToSchema.html).
- **decimal_float** Add support for [rust_decimal](https://crates.io/crates/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
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.
- **uuid** Add support for [uuid](https://github.com/uuid-rs/uuid). `Uuid` type will be presented as `String` with
format `uuid` in OpenAPI spec.
Expand All @@ -106,14 +106,14 @@ and the `ipa` is _api_ reversed. Aaand... `ipa` is also an awesome type of beer
- **indexmap** Add support for [indexmap](https://crates.io/crates/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
- **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](https://serde.rs/feature-flags.html).

Utoipa implicitly has partial support for `serde` attributes. See [docs](https://docs.rs/utoipa/latest/utoipa/derive.ToSchema.html#partial-serde-attributes-support) for more details.

## Install

Add minimal dependency declaration to Cargo.toml.
Add minimal dependency declaration to `Cargo.toml`.

```toml
[dependencies]
Expand Down Expand Up @@ -173,6 +173,7 @@ mod pet_api {
}
}
```

Utoipa has support for [http](https://crates.io/crates/http) `StatusCode` in responses.

_This attribute macro will create another struct named with `__path_` prefix + handler function name.
Expand All @@ -191,7 +192,7 @@ struct ApiDoc;
println!("{}", ApiDoc::openapi().to_pretty_json().unwrap());
```

This would produce api doc something similar to:
This would produce an API doc something similar to:

```json
{
Expand Down Expand Up @@ -274,29 +275,31 @@ This would produce api doc something similar to:
}
```

## Modify OpenAPI at runtime
## Modify OpenAPI at runtime

You can modify generated OpenAPI at runtime either via generated types directly or using
[Modify](https://docs.rs/utoipa/latest/utoipa/trait.Modify.html) trait.

_Modify generated OpenAPI via types directly._

You can modify generated OpenAPI at runtime either via generated types directly or using
[Modify](https://docs.rs/utoipa/latest/utoipa/trait.Modify.html) trait.
```rust
#[derive(OpenApi)]
#[openapi(
info(description = "My Api description"),
)]
struct ApiDoc;

_Modify generated OpenAPI via types directly._
```rust
#[derive(OpenApi)]
#[openapi(
info(description = "My Api description"),
)]
struct ApiDoc;
let mut doc = ApiDoc::openapi();
doc.info.title = String::from("My Api");
```

let mut doc = ApiDoc::openapi();
doc.info.title = String::from("My Api");
```
_You can even convert the generated [OpenApi](https://docs.rs/utoipa/latest/utoipa/openapi/struct.OpenApi.html) to [OpenApiBuilder](https://docs.rs/utoipa/latest/utoipa/openapi/struct.OpenApiBuilder.html)._

_You can even convert the generated [OpenApi](https://docs.rs/utoipa/latest/utoipa/openapi/struct.OpenApi.html) to [OpenApiBuilder](https://docs.rs/utoipa/latest/utoipa/openapi/struct.OpenApiBuilder.html)._
```rust
let builder: OpenApiBuilder = ApiDoc::openapi().into();
```
```rust
let builder: OpenApiBuilder = ApiDoc::openapi().into();
```

See [Modify](https://docs.rs/utoipa/latest/utoipa/trait.Modify.html) trait for examples on how to modify generated OpenAPI via it.
See [Modify](https://docs.rs/utoipa/latest/utoipa/trait.Modify.html) trait for examples on how to modify generated OpenAPI via it.

## Go beyond the surface

Expand All @@ -319,14 +322,13 @@ library **does not** by default embed files on debug builds. To get around this

Find `utoipa-swagger-ui` [feature flags here](https://github.com/juhaku/utoipa/tree/master/utoipa-swagger-ui#crate-features).


### How to implement `ToSchema` for external type?

There are few ways around this that are elaborated [here in detail](https://github.com/juhaku/utoipa/issues/790#issuecomment-1787754185).

### How to use Rust's type aliases?

At the moment that is not possible due to there is no way to evaluate the actual type behind the type token that is visible to the proc macro code generation.
At the moment that is not possible due to there is no way to evaluate the actual type behind the type token that is visible to the proc macro code generation.
This might be possible in future if a global alias registry can be implemented. Here is an issue related to the topic [#766](https://github.com/juhaku/utoipa/issues/766).

## License
Expand Down
30 changes: 15 additions & 15 deletions utoipa-gen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ use self::{
///
/// # Generic schemas with aliases
///
/// Schemas can also be generic which allows reusing types. This enables certain behaviour patters
/// Schemas can also be generic which allows reusing types. This enables certain behaviour patterns
/// where super type declares common code for type aliases.
///
/// In this example we have common `Status` type which accepts one generic type. It is then defined
Expand Down Expand Up @@ -703,16 +703,16 @@ pub fn derive_to_schema(input: TokenStream) -> TokenStream {
/// With _`inline(...)`_ the schema will be inlined instead of a referenced which is the default for
/// [`ToSchema`][to_schema] types. _`ref("./external.json")`_ can be used to reference external
/// json file for body schema. **Note!** Utoipa does **not** guarantee that free form _`ref`_ is accessbile via
/// OpenAPI doc or Swagger UI, users are eligible to make these guarantees.
/// OpenAPI doc or Swagger UI, users are responsible for making these guarantees.
///
/// **Advanced format definition by `request_body(...)`**
/// * `content = ...` Can be _`content = Type`_, _`content = inline(Type)`_ or _`content = ref("...")`_. The
/// given _`Type`_ can be any Rust type that is JSON parseable. It can be Option, Vec
/// or Map etc. With _`inline(...)`_ the schema will be inlined instead of a referenced
/// which is the default for [`ToSchema`][to_schema] types. _`ref("./external.json")`_
/// can be used to reference external json file for body schema. **Note!** Utoipa does **not** guarantee
/// that free form _`ref`_ is accessible via OpenAPI doc or Swagger UI, users are eligible
/// to make these guarantees.
/// that free form _`ref`_ is accessible via OpenAPI doc or Swagger UI, users are responsible for making
/// these guarantees.
///
/// * `description = "..."` Define the description for the request body object as str.
///
Expand Down Expand Up @@ -751,8 +751,8 @@ pub fn derive_to_schema(input: TokenStream) -> TokenStream {
/// With _`inline(...)`_ the schema will be inlined instead of a referenced which is the default for
/// [`ToSchema`][to_schema] types. _`ref("./external.json")`_
/// can be used to reference external json file for body schema. **Note!** Utoipa does **not** guarantee
/// that free form _`ref`_ is accessible via OpenAPI doc or Swagger UI, users are eligible
/// to make these guarantees.
/// that free form _`ref`_ is accessible via OpenAPI doc or Swagger UI, users are responsible for making
/// these guarantees.
///
/// * `content_type = "..." | content_type = [...]` Can be used to override the default behavior of auto resolving the content type
/// from the `body` attribute. If defined the value should be valid content type such as
Expand Down Expand Up @@ -1267,7 +1267,7 @@ pub fn derive_to_schema(input: TokenStream) -> TokenStream {
/// ````
///
/// _**Example with multiple examples on single response.**_
///```rust
/// ```rust
/// # #[derive(serde::Serialize, serde::Deserialize)]
/// # struct User {
/// # name: String
Expand All @@ -1288,7 +1288,7 @@ pub fn derive_to_schema(input: TokenStream) -> TokenStream {
/// fn get_user() -> User {
/// User {name: "John".to_string()}
/// }
///```
/// ```
///
/// [in_enum]: openapi/path/enum.ParameterIn.html
/// [path]: trait.Path.html
Expand Down Expand Up @@ -1458,8 +1458,8 @@ pub fn path(attr: TokenStream, item: TokenStream) -> TokenStream {
/// * `enum_values(...)` Define list of possible values for the variable. Values must be
/// literal strings.
///
/// _**Example server variable definition.**_
/// ```text
/// _**Example server variable definition.**_
/// ```text
/// ("username" = (default = "demo", description = "Default username for API")),
/// ("port" = (enum_values("8080", "5000", "4545")))
/// ```
Expand Down Expand Up @@ -1513,7 +1513,7 @@ pub fn path(attr: TokenStream, item: TokenStream) -> TokenStream {
/// ```
///
/// _**Define servers to OpenApi.**_
///```rust
/// ```rust
/// # use utoipa::OpenApi;
/// #[derive(OpenApi)]
/// #[openapi(
Expand All @@ -1528,7 +1528,7 @@ pub fn path(attr: TokenStream, item: TokenStream) -> TokenStream {
/// )
/// )]
/// struct ApiDoc;
///```
/// ```
///
/// _**Define info attribute values used to override auto generated ones from Cargo environment
/// variables.**_
Expand Down Expand Up @@ -1690,9 +1690,9 @@ pub fn openapi(input: TokenStream) -> TokenStream {
/// an open value as a string. By default the format is derived from the type of the property
/// according OpenApi spec.
///
/// * `write_only` Defines property is only used in **write** operations *POST,PUT,PATCH* but not in *GET*
/// * `write_only` Defines property is only used in **write** operations *POST,PUT,PATCH* but not in *GET*.
///
/// * `read_only` Defines property is only used in **read** operations *GET* but not in *POST,PUT,PATCH*
/// * `read_only` Defines property is only used in **read** operations *GET* but not in *POST,PUT,PATCH*.
///
/// * `xml(...)` Can be used to define [`Xml`][xml] object properties applicable to named fields.
/// See configuration options at xml attributes of [`ToSchema`][to_schema_xml]
Expand Down Expand Up @@ -1965,7 +1965,7 @@ pub fn into_params(input: TokenStream) -> TokenStream {

#[proc_macro_error]
#[proc_macro_derive(ToResponse, attributes(response, content, to_schema))]
/// Generate reusable OpenAPI response what can be used
/// Generate reusable OpenAPI response that can be used
/// in [`utoipa::path`][path] or in [`OpenApi`][openapi].
///
/// This is `#[derive]` implementation for [`ToResponse`][to_response] trait.
Expand Down
2 changes: 1 addition & 1 deletion utoipa-rapidoc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ const DEFAULT_HTML: &str = include_str!("../res/rapidoc.html");

/// Is [RapiDoc][rapidoc] UI.
///
/// This is an antry point for serving [RapiDoc][rapidoc] via predefined framework integration or
/// This is an entry point for serving [RapiDoc][rapidoc] via predefined framework integration or
/// in standalone fashion by calling [`RapiDoc::to_html`] within custom HTTP handler handles
/// serving the [RapiDoc][rapidoc] UI. See more at [running standalone][standalone]
///
Expand Down
18 changes: 9 additions & 9 deletions utoipa-redoc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,15 +210,15 @@ pub trait Servable<'u, 's, S>
where
S: Spec,
{
/// Consruct a new [`Servable`] instance of _`openapi`_ with given _`url`_.
/// Construct a new [`Servable`] instance of _`openapi`_ with given _`url`_.
///
/// * **url** Must point to location where the [`Servable`] is served.
/// * **openapi** Is [`Spec`] that is served via this [`Servable`] from the _**url**_.
fn with_url(url: &'u str, openapi: S) -> Self
where
'u: 's;

/// Consruct a new [`Servable`] instance of _`openapi`_ with given _`url`_ and _`config`_.
/// Construct a new [`Servable`] instance of _`openapi`_ with given _`url`_ and _`config`_.
///
/// * **url** Must point to location where the [`Servable`] is served.
/// * **openapi** Is [`Spec`] that is served via this [`Servable`] from the _**url**_.
Expand Down Expand Up @@ -303,7 +303,7 @@ impl<'s, 'u, S: Spec> Redoc<'s, 'u, S> {
}
}

/// Override the [ default HTML template][redoc_html_quickstart] with new one. See
/// Override the [default HTML template][redoc_html_quickstart] with new one. See
/// [customization] for more details.
///
/// [redoc_html_quickstart]: <https://redocly.com/docs/redoc/quickstart/>
Expand Down Expand Up @@ -339,7 +339,7 @@ impl<'s, 'u, S: Spec> Redoc<'s, 'u, S> {

/// Trait defines OpenAPI spec resource types supported by [`Redoc`].
///
/// By deafult this trait is implemented for [`utoipa::openapi::OpenApi`], [`String`], [`&str`] and
/// By default this trait is implemented for [`utoipa::openapi::OpenApi`], [`String`], [`&str`] and
/// [`serde_json::Value`].
///
/// * **OpenApi** implementation allows using utoipa's OpenApi struct as a OpenAPI spec resource
Expand All @@ -352,7 +352,7 @@ impl<'s, 'u, S: Spec> Redoc<'s, 'u, S> {
/// # Examples
///
/// _**Use [`Redoc`] to serve utoipa's OpenApi.**_
///```no_run
/// ```no_run
/// # use utoipa_redoc::Redoc;
/// # use utoipa::openapi::OpenApiBuilder;
/// #
Expand Down Expand Up @@ -388,7 +388,7 @@ impl Spec for Value {}
/// config. The [`Config`] must be able to load and serialize valid JSON.
///
/// * **EmptyConfig** is the default config and serializes to empty JSON object _`{}`_.
/// * **FileConfig** Allows [`Redoc`] to be configred via user defined file which serializes to
/// * **FileConfig** Allows [`Redoc`] to be configured via user defined file which serializes to
/// JSON.
/// * **FnOnce** closure config allows inlining JSON serializable config directly to [`Redoc`]
/// declaration.
Expand Down Expand Up @@ -430,7 +430,7 @@ impl Spec for Value {}
/// [redoc]: <https://redocly.com/>
/// [redoc_config]: <https://redocly.com/docs/api-reference-docs/configuration/functionality/#configuration-options-for-api-docs>
pub trait Config {
/// Implementor must implement the logic which loads the configuration of choice and coverts it
/// Implementor must implement the logic which loads the configuration of choice and converts it
/// to serde's [`serde_json::Value`].
fn load(self) -> Value;
}
Expand All @@ -441,11 +441,11 @@ impl<S: Serialize, F: FnOnce() -> S> Config for F {
}
}

/// Makes [`Redoc`] to load it's configuration from a user defined file.
/// Makes [`Redoc`] load it's configuration from a user defined file.
///
/// The config file must be defined via _**`UTOIPA_REDOC_CONFIG_FILE`**_ env variable for your
/// application. It can either be defined in runtime before the [`Redoc`] declaration or before
/// application starup or at compile time via `build.rs` file.
/// application startup or at compile time via `build.rs` file.
///
/// The file must be located relative to your application runtime directory.
///
Expand Down
16 changes: 8 additions & 8 deletions utoipa-swagger-ui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ use utoipa::openapi::OpenApi;
#[folder = "$UTOIPA_SWAGGER_DIR/$UTOIPA_SWAGGER_UI_VERSION/dist/"]
struct SwaggerUiDist;

/// Entry point for serving Swagger UI and api docs in application. It uses provides
/// Entry point for serving Swagger UI and api docs in application. It provides
/// builder style chainable configuration methods for configuring api doc urls.
///
/// # Examples
Expand Down Expand Up @@ -276,15 +276,15 @@ impl SwaggerUi {
/// # Examples
///
/// Add external API doc to the [`SwaggerUi`].
///```rust
/// ```rust
/// # use utoipa_swagger_ui::{SwaggerUi, Url};
/// # use utoipa::OpenApi;
/// # use serde_json::json;
/// let external_openapi = json!({"openapi": "3.0.0"});
///
/// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}")
/// .external_url_unchecked("/api-docs/openapi.json", external_openapi);
///```
/// ```
pub fn external_url_unchecked<U: Into<Url<'static>>>(
mut self,
url: U,
Expand All @@ -308,7 +308,7 @@ impl SwaggerUi {
/// # Examples
///
/// Add external API docs to the [`SwaggerUi`].
///```rust
/// ```rust
/// # use utoipa_swagger_ui::{SwaggerUi, Url};
/// # use utoipa::OpenApi;
/// # use serde_json::json;
Expand All @@ -320,7 +320,7 @@ impl SwaggerUi {
/// ("/api-docs/openapi.json", external_openapi),
/// ("/api-docs/openapi2.json", external_openapi2)
/// ]);
///```
/// ```
pub fn external_urls_from_iter_unchecked<
I: IntoIterator<Item = (U, serde_json::Value)>,
U: Into<Url<'static>>,
Expand Down Expand Up @@ -486,13 +486,13 @@ const SWAGGER_BASE_LAYOUT: &str = "BaseLayout";
///
/// # Examples
///
/// In simple case create config directly from url that points to the api doc json.
/// In simple case, create config directly from url that points to the api doc json.
/// ```rust
/// # use utoipa_swagger_ui::Config;
/// let config = Config::from("/api-doc.json");
/// ```
///
/// If there is multiple api docs to serve config can be also directly created with [`Config::new`]
/// If there is multiple api docs to serve config, the [`Config`] can be also be directly created with [`Config::new`]
/// ```rust
/// # use utoipa_swagger_ui::Config;
/// let config = Config::new(["/api-docs/openapi1.json", "/api-docs/openapi2.json"]);
Expand Down Expand Up @@ -632,7 +632,7 @@ pub struct Config<'a> {
#[serde(skip)]
oauth: Option<oauth::Config>,

/// The layout of Swagger UI uses, default is `"StandaloneLayout"`
/// The layout of Swagger UI uses, default is `"StandaloneLayout"`.
layout: &'a str,
}

Expand Down
Loading

0 comments on commit 7e49344

Please sign in to comment.