Apistos

repository·main·Indexed 42 days ago

https://github.com/netwo-io/apistos

An OpenAPI v3.0.3 documentation generator for Rust that provides an actix-web wrapper to automatically generate documentation from code. It includes a modular ecosystem with crates for models, macro utilities, and plugins for HTML-based UIs such as Swagger UI, Redoc, RapiDoc, and Scalar.

Tokens
25.9K
Snippets
72
Records
98
Agent score
52%

What's inside Apistos

  1. Extend Apistos using plugins

    main

    The apistos-plugins crate provides traits that allow you to extend the core functionality of Apistos. Currently, its primary use case is to expose generated OpenAPI specifications through various HTML-based User Interfaces (UIs).

    To use these plugins, you must enable one of the following features in your Cargo.toml:

    • rapidoc
    • redoc
    • swagger-ui
  2. Use apistos-gen to generate OpenAPI v3.0.3 documentation

    main

    The apistos-gen crate provides a set of macro utilities designed to generate OpenAPI v3.0.3 documentation directly from Rust models.

    Important Note: This crate is not intended to be used as a standalone dependency. Instead, you should use the main apistos crate, which provides the complete functionality and integrates these utilities.

  3. Apistos Ecosystem Components

    main

    Apistos is a modular ecosystem of crates designed to work with actix-web and OpenAPI v3.0.3:

    • apistos: The main actix-web wrapper for generating OpenAPI documentation.
    • apistos-core: Traits and common models for OpenAPI v3.0.3.
    • apistos-gen: Macros for generating documentation from Rust models.
    • apistos-models: OpenAPI v3.0.3 models based on schemars.
    • apistos-plugins: Traits and utilities for extending Apistos.
    • apistos-rapidoc: Bridge to RapiDoc for actix.
    • apistos-redoc: Bridge to Redoc for actix.
    • apistos-scalar: Bridge to Scalar for actix.
    • apistos-shuttle: Support for running documented actix-web servers on Shuttle.
    • apistos-swagger-ui: Bridge to Swagger UI for actix.
  4. Use Apistos to document an actix-web API

    main

    Apistos allows you to generate OpenAPI v3.0.3 documentation by wrapping your actix-web application. You can use macros like #[derive(ApiComponent)] and #[derive(ApiErrorComponent)] to mark your data models and error types, and #[api_operation] to add metadata to your route handlers.

    To expose the documentation, use .document(spec) to attach an OpenAPI Spec to your App, and .build("/openapi.json") to define the endpoint where the JSON specification will be served.

    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> {
        let spec = Spec {
          info: Info {
            title: "An API".to_string(),
            version: "1.0.0".to_string(),
            ..Default::default()
          },
          ..Default::default()
        };
    
        HttpServer::new(move || {
            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
    }
  5. Install apistos-models

    main

    To use apistos-models, add it to your Cargo.toml. Note that because of a requirement to fix multiple flatten issues for enums, you must use the apistos-schemars fork instead of the standard schemars crate.

    [dependencies]
    # Use the apistos fork of schemars to fix multiple flatten for enums
    schemars = { package = "apistos-schemars", version = "0.8" }
    apistos-models = "0.5"
  6. Install Apistos Swagger UI for Actix

    main

    To use the Swagger UI bridge for Actix, you must enable the swagger-ui feature in the main apistos crate. Additionally, because of a known issue with multiple flatten for enums in the standard schemars crate, you must use the apistos-schemars fork instead of the official schemars package.

    Add the following to your Cargo.toml:

    1. Use apistos with the swagger-ui feature enabled.
    2. Use apistos-schemars (version 0.8) instead of the standard schemars crate.
    [dependencies]
    # Use the apistos-provided fork of schemars to fix enum flattening issues
    schemars = { package = "apistos-schemars", version = "0.8" }
    
    # Enable the swagger-ui feature in apistos
    apistos = { version = "0.5", feature = ["swagger-ui"] }
  7. Install Apistos

    main

    To use Apistos, add it and its required fork of schemars to your Cargo.toml. Apistos currently relies on the apistos-schemars package to fix issues with multiple flatten attributes for enums.

    [dependencies]
    schemars = { package = "apistos-schemars", version = "0.8" }
    apistos = "0.6"
    [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"
  8. Install apistos-shuttle

    main

    To run an actix-web server documented with Apistos on Shuttle, add apistos-shuttle to your dependencies. Note that you must use the apistos-schemars fork instead of the standard schemars to resolve issues with multiple flatten attributes for enums.

    Ensure you use compatible versions of apistos and apistos-shuttle.

    [dependencies]
    # Use the apistos fork of schemars to fix multiple flatten for enums
    schemars = { package = "apistos-schemars", version = "0.8" }
    apistos = { version = "0.5" }
    apistos-shuttle = { version = "0.5" }
  9. Use apistos instead of apistos-core

    main

    The apistos-core crate provides a set of traits and common models centered around the [OpenAPI v3.0.3][OASv3.md] specification.

    Important: This crate is not intended to be used as a standalone dependency. If you are looking to use the Apistos ecosystem, you should use the main apistos crate instead.

  10. Install Apistos Redoc

    main

    To use the Redoc bridge for Actix within Apistos, you must enable the redoc feature in your apistos dependency. Additionally, because of a known issue with multiple flatten for enums in the standard schemars crate, you must use the apistos-schemars fork instead of the standard schemars package.

    Add the following to your Cargo.toml:

    [dependencies]
    schemars = { package = "apistos-schemars", version = "0.8" }
    apistos = { version = "0.5", feature = ["redoc"] }
  11. Install Apistos RapiDoc via the `rapidoc` feature

    main

    To use the RapiDoc bridge for Actix, you must enable the rapidoc feature in your apistos dependency. Additionally, because of a known issue with schemars regarding multiple flatten attributes for enums, you must use the apistos-schemars fork instead of the standard schemars crate.

    Add the following to your Cargo.toml:

    [dependencies]
    # Use the apistos fork of schemars to fix enum flatten issues
    schemars = { package = "apistos-schemars", version = "0.8" }
    
    # Enable the `rapidoc` feature
    apistos = { version = "0.5", features = ["rapidoc"] }
    [dependencies]
    schemars = { package = "apistos-schemars", version = "0.8" }
    apistos = { version = "0.5", feature = ["rapidoc"] }