Skip to content

Commit

Permalink
document the library (#18)
Browse files Browse the repository at this point in the history
Add Component documentation
Add OpenApi documentation
Add project overview documentation
  • Loading branch information
juhaku authored Feb 8, 2022
1 parent 16bc0f3 commit f456ade
Show file tree
Hide file tree
Showing 11 changed files with 396 additions and 70 deletions.
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,7 @@ paste = "1.0.6"
[workspace]
members = [
"utoipa-gen"
]
]

[package.metadata.docs.rs]
features = ["swagger_ui", "json", "actix-web", "actix_extras"]
8 changes: 3 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
[![crates.io](https://img.shields.io/static/v1?label=crates.io&message=0.1.0-beta.0&color=orange&logo=rust)](https://crates.io/crates/utoipa/0.1.0-beta.0)
[![docs.rs](https://img.shields.io/static/v1?label=docs.rs&message=utoipa&color=blue&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K)](https://docs.rs/utoipa/0.1.0-beta.0/utoipa/)



Want to document your utopic api? Want it to feel as fuzzy as cold ipa? Then you are probably in need of utoipa.

Utoipa crate provides autogenerated OpenAPI documentation for Rust REST APIs. It treats code first appoach as a
Expand Down Expand Up @@ -43,7 +41,7 @@ Create your Get pet API.
mod pet_api {
/// Get pet by id
///
/// Get pet from database by pet database id
/// Get pet from database by pet id
#[utoipa::path(
get,
path = "/pets/{id}"
Expand Down Expand Up @@ -85,7 +83,7 @@ This would produce api doc something similar to:
"name": "author name from Cargo.toml",
"email":"author email from Cargo.toml"
},
"licence": {
"license": {
"name": "license from Cargo.toml"
},
"version": "version from Cargo.toml"
Expand All @@ -97,7 +95,7 @@ This would produce api doc something similar to:
"pet_api"
],
"summary": "Get pet by id",
"description": "Get pet by id\n\nGet pet from database by pet database id\n",
"description": "Get pet by id\n\nGet pet from database by pet id\n",
"operationId": "get_pet_by_id",
"parameters": [
{
Expand Down
4 changes: 4 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# utoipa examples

This is folder will contain a set of examples of utoipa library which should help people to get started
with the library.
39 changes: 0 additions & 39 deletions src/error.rs

This file was deleted.

222 changes: 220 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,233 @@
pub mod error;
//! Want to have your API documented with OpenAPI? But you dont 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 appoach 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 autogeneration 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.
//!
//! # 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.
//!
//! # Features
//!
//! * **default** Default enabled features are **json**.
//! * **json** Enables some advanced features for openapi which otherwise are not available. Thus is
//! enabled by default.
//! * **swagger_ui** Enables the embedded Swagger UI to view openapi api documentation.
//! * **actix-web** Enables actix-web integration with pre-configured SwaggerUI service factory allowing
//! users to use the Swagger UI without a hazzle.
//! * **actix_extras** Enhances actix-web intgration with being able to parse some documentation
//! from actix web macro attributes and types.
//! * **debug** Add extra traits such as debug traits to openapi definitions and elsewhere.
//!
//! # Install
//!
//! Add minimal dependency declaration to Cargo.toml.
//! ```text
//! [dependencies]
//! utoipa = "0.1.beta.0"
//! ```
//!
//! To enable more features such as use of swagger together with actix-web framework you could define the
//! dependency as follows.
//! ```text
//! [dependencies]
//! utoipa = { version = "0.1.beta.0", features = ["swagger_ui", "actix-web", "actix_extras"] }
//! ```
//!
//! # Examples
//!
//! Create a struct or it could be an enum also. Add `Component` derive macro to it so it can be registered
//! as a component in openapi schema.
//! ```rust
//! use utoipa::Component;
//! #[derive(Component)]
//! struct Pet {
//! id: u64,
//! name: String,
//! age: Option<i32>,
//! }
//! ```
//!
//! Create an handler that would handle your business logic and add `path` proc attribute macro over it.
//! ```compile_fail
//! 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 succesfully", body = Pet),
//! (status = 404, description = "Pet was not found", body = NotFoundError)
//! ],
//! params = [
//! ("id" = u64, path, description = "Pet database id to get Pet for"),
//! ]
//! )]
//! async fn get_pet_by_id(pet_id: u64) -> Pet {
//! Pet {
//! id: pet_id,
//! age: None,
//! name: "lightning".to_string(),
//! }
//! }
//! }
//! ```
//!
//! Tie the component and the above api to the openapi schema with following `OpenApi` derive proc macro.
//! ```compile_fail
//! use utoipa::OpenApi;
//! use crate::Pet;
//!
//! #[derive(OpenApi)]
//! #[openapi(handlers = [pet_api::get_pet_by_id], components = [Pet])]
//! struct ApiDoc;
//!
//! println!("{}", ApiDoc::openapi().to_pretty_json().unwrap());
//! ```
//!
//! If you have *swagger_ui* and the *actix-web* features enabled you can display the openapi documentation
//! as easily as follows:
//! ```compile_fail
//! HttpServer::new(move || {
//! App::new()
//! .service(
//! SwaggerUi::new("/swagger-ui/{_:.*}")
//! .with_url("/api-doc/openapi.json", ApiDoc::openapi()),
//! )
//! })
//! .bind(format!("{}:{}", Ipv4Addr::UNSPECIFIED, 8989))?
//! .run()
//! .await
//! ```
//!
//! See more details in [`swagger_ui`] module. You can also browse to
//! [examples](https://github.com/juhaku/utoipa/tree/master/examples) for more comprehensinve examples.
/// Openapi module contains Rust implementation of Openapi Spec V3
pub mod openapi;
#[cfg(feature = "swagger_ui")]
/// Swagger UI module contains embedded Swagger UI and extensions for actix-web
pub mod swagger_ui;
pub mod types;

pub use utoipa_gen::*;

/// OpenApi trait for implementing Openapi specification in Rust.
///
/// This trait is derivable and can be used with `#[derive]` attribute. The derived implementation
/// will use Cargo provided environment variables to implement the default information. For a details of
/// `#[derive(Component)]` refer to [derive documentation][derive].
///
/// # Examples
///
/// Below is derived example of `OpenApi`.
/// ```rust
/// use utoipa::OpenApi;
/// #[derive(OpenApi)]
/// #[openapi(handlers = [])]
/// struct OpenApiDoc;
/// ```
///
/// This manual `OpenApi` trait implementation is approximately equal to the above derived one except the derive
/// implementation will by default use the Cargo environment variables to set defaults for *application name,
/// version, application description, license, author name & email*.
///
///```rust
/// struct OpenApiDoc;
///
/// impl utoipa::OpenApi for OpenApiDoc {
/// fn openapi() -> utoipa::openapi::OpenApi {
/// use utoipa::{Component, Path};
/// utoipa::openapi::OpenApi::new(
/// utoipa::openapi::Info::new("application name", "version")
/// .with_description("application description")
/// .with_license(utoipa::openapi::License::new("MIT"))
/// .with_contact(
/// utoipa::openapi::Contact::new()
/// .with_name("author name")
/// .with_email("author email"),
/// ),
/// utoipa::openapi::path::Paths::new(),
/// )
/// .with_components(utoipa::openapi::Schema::new())
/// }
/// }
/// ```
/// [derive]: derive.OpenApi.html
pub trait OpenApi {
fn openapi() -> openapi::OpenApi;
}

/// Component trait for implementing swagger specification schema object for a type.
///
/// This trait is deriveable and can be used with `[#derive]` attribute. For a details of
/// `#[derive(Component)]` refer to [derive documentation][derive].
///
/// [derive]: derive.Component.html
///
/// # Examples
///
/// Use `#[derive]` to implement `Component` trait.
/// ```rust
/// # use utoipa::Component;
/// #[derive(Component)]
/// #[component(example = json!({"name": "bob the cat", "id": 1}))]
/// struct Pet {
/// id: u64,
/// name: String,
/// age: Option<i32>,
/// }
/// ```
///
/// Following manual implementation is equal to above derive one.
/// ```rust
/// # struct Pet {
/// # id: u64,
/// # name: String,
/// # age: Option<i32>,
/// # }
/// #
/// impl utoipa::Component for Pet {
/// fn component() -> utoipa::openapi::schema::Component {
/// use utoipa::openapi::ToArray;
/// utoipa::openapi::Object::new()
/// .with_property(
/// "id",
/// utoipa::openapi::Property::new(utoipa::openapi::ComponentType::Integer)
/// .with_format(utoipa::openapi::ComponentFormat::Int64),
/// )
/// .with_required("id")
/// .with_property(
/// "name",
/// utoipa::openapi::Property::new(utoipa::openapi::ComponentType::String),
/// )
/// .with_required("name")
/// .with_property(
/// "age",
/// utoipa::openapi::Property::new(utoipa::openapi::ComponentType::Integer)
/// .with_format(utoipa::openapi::ComponentFormat::Int32),
/// )
/// .with_example(serde_json::json!({
/// "name":"bob the cat","id":1
/// }))
/// .into()
/// }
/// }
/// ```
pub trait Component {
fn component() -> openapi::schema::Component;
}
Expand Down
24 changes: 9 additions & 15 deletions src/openapi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ use std::collections::BTreeMap;

use serde::{Deserialize, Serialize, Serializer};

use crate::error::Error;

pub use self::{
contact::Contact,
content::Content,
Expand Down Expand Up @@ -86,13 +84,13 @@ impl OpenApi {
}

#[cfg(feature = "serde_json")]
pub fn to_json(&self) -> Result<String, Error> {
serde_json::to_string(self).map_err(Error::Serde)
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string(self)
}

#[cfg(feature = "serde_json")]
pub fn to_pretty_json(&self) -> Result<String, Error> {
serde_json::to_string_pretty(self).map_err(Error::Serde)
pub fn to_pretty_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(self)
}
}

Expand Down Expand Up @@ -176,22 +174,18 @@ impl Default for Required {
#[cfg(test)]
#[cfg(feature = "serde_json")]
mod tests {

use crate::{error::Error, openapi::licence::License};
use crate::openapi::licence::License;

use super::{path::Operation, response::Response, *};

#[test]
fn serialize_deserialize_openapi_version_success() -> Result<(), Error> {
assert_eq!(
serde_json::to_value(&OpenApiVersion::Version3).map_err(Error::Serde)?,
"3.0.3"
);
fn serialize_deserialize_openapi_version_success() -> Result<(), serde_json::Error> {
assert_eq!(serde_json::to_value(&OpenApiVersion::Version3)?, "3.0.3");
Ok(())
}

#[test]
fn serialize_openapi_json_minimal_success() -> Result<(), Error> {
fn serialize_openapi_json_minimal_success() -> Result<(), serde_json::Error> {
let raw_json = include_str!("testdata/expected_openapi_minimal.json");
let openapi = OpenApi::new(
Info::new("My api", "1.0.0")
Expand All @@ -210,7 +204,7 @@ mod tests {
}

#[test]
fn serialize_openapi_json_with_paths_success() -> Result<(), Error> {
fn serialize_openapi_json_with_paths_success() -> Result<(), serde_json::Error> {
let openapi = OpenApi::new(
Info::new("My big api", "1.1.0"),
Paths::new()
Expand Down
Loading

0 comments on commit f456ade

Please sign in to comment.