Crate apistos

Source
Expand description

An OpenAPI documentation tool exposing OAS 3.0 models as well as an actix-web wrapper similar to paperclip.

§What does Apistos means

Apistos (pronounced /a.p.i.stos/) is a word play between Héphaïstos (Ἥφαιστος, grec god of blacksmiths, carpenters, craftsmen, metallurgy … which can also be considered by some as the god of technology) and API (pronounced /a.p.i/ in French).

§Installation

[dependencies]
#schemars = "0.8"
# sadly we currently rely on a fork to fix multiple flatten for enums, related PR can be found here: https://github.com/GREsau/schemars/pull/264
schemars = { package = "apistos-schemars", version = "0.8" }
apistos = "0.6"

§Usage example

Wrap your regular actix-web app using apistos types.

Most of these types are drop-in types for actix-web one’s.

use std::fmt::Display;
use actix_web::{App, HttpServer, ResponseError};
use actix_web::http::StatusCode;
use actix_web::middleware::Logger;
use actix_web::web::Json;
use apistos::actix::CreatedJson;
use apistos::api_operation;
use apistos::ApiComponent;
use apistos::ApiErrorComponent;
use apistos::app::OpenApiWrapper;
use apistos::spec::Spec;
use apistos::web::{post, resource, scope};
use apistos_models::info::Info;
use core::fmt::Formatter;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::net::Ipv4Addr;

#[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, ApiComponent)]
pub struct Test {
  pub test: String
}

#[derive(Serialize, Deserialize, Debug, Clone, ApiErrorComponent)]
#[openapi_error(
  status(code = 403),
  status(code = 404),
  status(code = 405, description = "Invalid input"),
  status(code = 409)
)]
pub enum ErrorResponse {
  MethodNotAllowed(String),
  NotFound(String),
  Conflict(String),
  Unauthorized(String),
}

impl Display for ErrorResponse {
  fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
    todo!()
  }
}

impl ResponseError for ErrorResponse {
  fn status_code(&self) -> StatusCode {
    todo!()
  }
}

#[api_operation(
  tag = "pet",
  summary = "Add a new pet to the store",
  description = r###"Add a new pet to the store
    Plop"###,
  error_code = 405
)]
pub(crate) async fn test(
  body: Json<Test>,
) -> Result<CreatedJson<Test>, ErrorResponse> {
  Ok(CreatedJson(body.0))
}

#[actix_web::main]
async fn main() -> Result<(), impl Error> {
  HttpServer::new(move || {
    let spec = Spec {
      info: Info {
        title: "An API".to_string(),
        version: "1.0.0".to_string(),
        ..Default::default()
      },
      ..Default::default()
    };

    App::new()
      .document(spec)
      .wrap(Logger::default())
      .service(scope("/test")
        .service(
          resource("")
            .route(post().to(test))
        )
      )
      .build("/openapi.json")
    })
    .bind((Ipv4Addr::UNSPECIFIED, 8080))?
    .run()
    .await
}

For a complete example, see the sample petstore.

§Feature flags

namedescriptionextra dependencies
query (default)Enables documenting actix_web::web::Query
actix (default)Enables documenting types from actix
lab_queryEnables documenting actix_web_lab::extract::Queryactix-web-lab
gardeEnables input validation through gardegarde
actix-web-grantsEnables support for actix-web-grantsactix-web-grants
qs_queryEnables documenting types from serde_qsserde_qs
rapidocEnables RapiDoc to expose the generated openapi file
redocEnables ReDoc to expose the generated openapi file
swagger-uiEnables Swagger UI to expose the generated openapi file
chronoEnables documenting types from chronochrono
multipartEnables documenting types from actix-multipartactix-multipart
rust_decimalEnables documenting types from rust_decimalrust_decimal
uuidEnables documenting types from uuiduuid
urlEnables documenting types from urlurl
extrasEnables chrono, multipart, rust_decimal, uuid and url featuresAll from previous features

It is possible to completely disable the documentation of actix_web::web::Query. This is useful when you want to enforce the use of serde_qs::actix::QsQuery in your project. To do so disable the default features. (Note: you might need to add actix feature as well)

§What’s next

  • Handle schema for errors using ApiErrorComponent[ derive macro

§Alternatives

CrateKey differences
paperclipPaperclip is similar to this project but generate Swagger v2 documentation. Paperclip also provide a tool to generate rust code from a Swagger v2 document.
utoipaUtoipa-actix integration rely on actix web macros for routing definition. At first, we planned on relying on utoipa for OAS types and schema derivation but for now utoipa doesn’t support generic struct the way we intended to.
okapiPretty similar, based on schemars as well (and maintained by the founder of schemars) but not integrated with actix.

Modules§

actix
app
components
info
paths
reference_or
security
server
spec
tag
web

Structs§

ArrayValidation
Properties of a SchemaObject which define validation assertions for arrays.
IndexMap
A hash table where the iteration order of the key-value pairs is independent of the hash values of the keys.
Metadata
Properties which annotate a SchemaObject which typically have no effect when an object is being validated against the schema.
NumberValidation
Properties of a SchemaObject which define validation assertions for numbers.
ObjectValidation
Properties of a SchemaObject which define validation assertions for objects.
OpenApi
This is the root document object of the OpenAPI document.
RootSchema
The root object of a JSON Schema document.
SchemaObject
A JSON Schema object.
StringValidation
Properties of a SchemaObject which define validation assertions for strings.
SubschemaValidation
Properties of a SchemaObject which define validation assertions in terms of other schemas.

Enums§

InstanceType
The possible types of values in JSON Schema documents.
OpenApiVersion
Schema
A JSON Schema.
SingleOrVec
A type which can be serialized as a single item, or multiple items.

Traits§

ApiComponent
ApiErrorComponent
ApiHeader
FutureExt
An extension trait for Futures that provides a variety of convenient adapters.
PathItemDefinition
TypedSchema

Attribute Macros§

api_operation
Operation attribute macro implementing PathItemDefinition for the decorated handler function.

Derive Macros§

ApiComponent
Generates a reusable OpenAPI schema.
ApiCookie
Generates a reusable OpenAPI parameter schema in cookie.
ApiErrorComponent
Generates a reusable OpenAPI error schema.
ApiHeader
Generates a reusable OpenAPI header schema.
ApiSecurity
Generates a reusable OpenAPI security scheme.
ApiType
Generates a custom OpenAPI type.