Module openapi

Source
Expand description

Automatic openapi spec generator.

§Usage

Enable cargo feature by

[dependencies]
rweb = { version = "0.6", features = ["openapi"] }
serde = "1"
tokio = "1"

and wrap your handlers like

use rweb::*;
use serde::Serialize;

#[get("/")]
fn index() -> String {
    String::from("content type will be 'text/plain' as you return String")
}

#[derive(Debug, Serialize, Schema)]
struct Product {
    id: String,
    price: usize,
}

#[get("/products")]
fn products() -> Json<Vec<Product>> {
    unimplemented!("content type will be 'application/json', and type of openapi schema will be array")
}

#[get("/product/{id}")]
fn product(id: String) -> Json<Product> {
    // See Component section below if you want to give a name to type.
    unimplemented!("content type will be 'application/json', and type of openapi schema will be object")
}

#[tokio::main]
async fn main() {
    let (_spec, filter) = openapi::spec().build(||{
           index().or(products()).or(product())
    });

    serve(filter);
    // Use the code below to run server.
    //
    // serve(filter).run(([127, 0, 0, 1], 3030)).await;
}

Note: Currently using path filter from warp is not supported by rweb. If you use path filter from warp, generated document will point to different path.

§Annotations

This is applicable to #[get], #[post], ..etc

§#[openapi(id = "foo")]

use rweb::*;

#[get("/sum/{a}/{b}")]
#[openapi(id = "math.sum")]
fn sum(a: usize, b: usize) -> String {
    (a + b).to_string()
}

§#[openapi(description = "foo")]

use rweb::*;

/// By default, doc comments on the function will become description of the operation.
#[get("/sum/{a}/{b}")]
#[openapi(description = "But what if implementation details is written on it?")]
fn sum(a: usize, b: usize) -> String {
    (a + b).to_string()
}

§#[openapi(summary = "foo")]

use rweb::*;

#[get("/sum/{a}/{b}")]
#[openapi(summary = "summary of operation")]
fn sum(a: usize, b: usize) -> String {
    (a + b).to_string()
}

§#[openapi(tags("foo", "bar"))]

use rweb::*;

#[get("/sum/{a}/{b}")]
#[openapi(tags("sum"))]
fn sum(a: usize, b: usize) -> String {
    (a + b).to_string()
}

#[get("/mul/{a}/{b}")]
#[openapi(tags("mul"))]
fn mul(a: usize, b: usize) -> String {
    (a * b).to_string()
}

// This is also applicable to #[router]
#[router("/math", services(sum, mul))]
#[openapi(tags("math"))]
fn math() {}

§Parameters

use rweb::*;
use serde::Deserialize;

#[derive(Debug, Deserialize, Schema)]
struct Opt {
    query: String,
    limit: usize,
    page_token: String,
}

/// Look at the generated api document, and surprise :)
///
/// Fields of [Opt] are documented as query parameters.
#[get("/")]
pub fn search(_q: Query<Opt>) -> String {
    String::new()
}

/// Path parameter is documented. (as there's enough information to document it)
#[get("/{id}")]
pub fn get(id: String) -> String {
    String::new()
}

/// Fields of [Opt] are documented as request body parameters.
pub fn store(_: Json<Opt>) -> String{
    String::new()
}

§Response body

use rweb::*;
use serde::Serialize;

#[derive(Debug, Default, Serialize, Schema)]
struct Output {
    data: String,
}

/// Json<T> implements rweb::openapi::ResponseEntity if T implements Entity.
#[get("/")]
pub fn get() -> Json<Output> {
    Output::default().into()
}

§Entity

See Entity for details and examples.

§Custom error

use rweb::*;
use indexmap::IndexMap;
use std::borrow::Cow;

#[derive(Debug, Schema)]
enum Error {
    NotFound,
}

impl openapi::ResponseEntity for Error {
    fn describe_responses(_: &mut openapi::ComponentDescriptor) -> openapi::Responses {
        let mut map = IndexMap::new();

        map.insert(
            Cow::Borrowed("404"),
            openapi::Response {
                description: Cow::Borrowed("Item not found"),
                ..Default::default()
            },
        );

        map
    }
}

Structs§

AuthorizationCodeFlow
Configuration details for a authorization code OAuth Flow See [link] [link](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oauth-flow-object
Builder
Builder for openapi v3 specification.
Callback
A map of possible out-of band callbacks related to the parent operation. Each value in the map is a Path Item Object that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.
ClientCredentialsFlow
Configuration details for a client credentials OAuth Flow See [link] [link](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oauth-flow-object
Collector
ComponentDescriptor
Components
Holds a set of reusable objects for different aspects of the OAS.
Contact
Contact information for the exposed API.
Encoding
A single encoding definition applied to a single schema property.
Example
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#exampleObject.
ExternalDoc
Allows referencing an external resource for extended documentation.
Flows
Allows configuration of the supported OAuth Flows. See [link] [link][https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oauth-flows-object]
Header
The Header Object follows the structure of the Parameter Object with the following changes:
ImplicitFlow
Configuration details for a implicit OAuth Flow See [link] link
Info
General information about the API.
License
License information for the exposed API.
Link
The Link object represents a possible design-time link for a response.
MediaType
Each Media Type Object provides schema and examples for the media type identified by its key.
Operation
Describes a single API operation on a path.
Parameter
Describes a single operation parameter. A unique parameter is defined by a combination of a name and location.
PasswordFlow
Configuration details for a password OAuth Flow See [link] [link](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oauth-flow-object
PathItem
Describes the operations available on a single path.
RequestBody
Describes a single request body.
Response
Describes a single response from an API Operation, including design-time, static links to operations based on the response.
Schema
The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is an extended subset of the JSON Schema Specification Wright Draft 00. For more information about the properties, see JSON Schema Core and JSON Schema Validation. Unless stated otherwise, the property definitions follow the JSON Schema.
Server
An object representing a Server.
ServerVariable
An object representing a Server Variable for server URL template substitution.
Spec
top level document
Tag
Adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.

Enums§

ComponentOrInlineSchema
Either a reference to a component schema or an [inline] schema itself.
ExampleValue
Embedded literal example or a URL that points to the literal example.
LinkOperation
The name of an existing resolvable OAS operation, or a relative or absolute reference to an OAS operation.
Location
MediaTypeExample
ObjectOrReference
ParameterExamples
Example(s) of the parameter’s potential value
ParameterRepresentation
The schema defining the type used for the parameter or a map containing the representations for the parameter.
ParameterStyle
RuntimeExpressionOrValue
Runtime expression or literal value. Used for Link parameters and request_body.
SecurityScheme
Defines a security scheme that can be used by the operations. Supported schemes are HTTP authentication, an API key (either as a header or as a query parameter), OAuth2’s common flows (implicit, password, application and access code) as defined in RFC6749, and OpenID Connect Discovery.
Type

Traits§

Entity
This can be derived by #[derive(Schema)].
ResponseEntity
This should be implemented only for types that know how it should be encoded.

Functions§

spec
Crates a new specification builder

Type Aliases§

Responses
SecurityRequirement
Security Requirement Object