Rust Macros to automate the addition of Paths/Schemas to Utoipa crate, simulating Reflection during the compilation phase

Overview

utoipa_auto_discovery

Rust Macros to automate the addition of Paths/Schemas to Utoipa crate, simulating Reflection during the compilation phase

MSRV

Crate presentation

Utoipa is a great crate for generating documentation (openapi/swagger) via source code.

But since Rust is a static programming language, we don't have the possibility of automatically discovering paths and dto in runtime and adding them to the documentation,

for APIs with just a few endpoints, it's not that much trouble to add controller functions one by one, and DTOs one by one.

if you have hundreds or even thousands of endpoints, the code becomes very verbose and difficult to maintain.

ex :

...

#[derive(OpenApi)]
#[openapi(
    paths(
        // <================================ all functions  1 to N
        test_controller::service::func_get_1,
        test_controller::service::func_get_2,
        test_controller::service::func_get_3,
        test_controller::service::func_get_4,
       ....
       ....
       ....
        test_controller::service::func_get_N,

    ),
    components(
        // <====================== All DTO one by one
        schemas(TestDTO_1,  TestDTO_2, ........ , TestDTO_N)
    ),
    tags(
        (name = "todo", description = "Todo management endpoints.")
    ),
    modifiers(&SecurityAddon)
)]
pub struct ApiDoc;

...

The aim of crate utoipa_auto_discovery is to propose a macro that automates the detection of methods carrying Utoipa macros (#[utoipa::path(...]), and adds them automatically. (it also detects sub-modules.)

how to use it

simply add the crate utoipa_auto_discovery to the project

cargo add utoipa_auto_discovery

import macro

use utoipa_auto_discovery::utoipa_auto_discovery;

then add the #[utoipa_auto_discovery] macro just before the #[derive(OpenApi)] and #[openapi] macros.

important !!

Put #[utoipa_auto_discovery] before #[derive(OpenApi)] and #[openapi] macros.

#[utoipa_auto_discovery(paths = "( MODULE_TREE::MODULE_NAME => MODULE_SRC_FILE_PATH ) ; ( MODULE_TREE::MODULE_NAME => MODULE_SRC_FILE_PATH ) ; ... ;")]

the paths receives a String which must respect this structure :

" ( MODULE_TREE_PATH => MODULE_SRC_FILE_PATH ) ;"

you can add several pairs (Module Path => Src Path ) by separating them with a semicolon ";".

Here's an example of how to add all the methods contained in the test_controller and test2_controller modules. you can also combine automatic and manual addition, as here we've added a method manually to the documentation "other_controller::get_users".

...

use utoipa_auto_discovery::utoipa_auto_discovery;

...
#[utoipa_auto_discovery(
  paths = "( crate::rest::test_controller => ./src/rest/test_controller.rs ) ; ( crate::rest::test2_controller => ./src/rest/test2_controller.rs )"
  )]
#[derive(OpenApi)]
#[openapi(
    paths(

        crate::rest::other_controller::get_users,
    ),
    components(
        schemas(TestDTO)
    ),
    tags(
        (name = "todo", description = "Todo management endpoints.")
    ),
    modifiers(&SecurityAddon)
)]

pub struct ApiDoc;

...

exclude a method of automatic scanning

you can exclude a function from the Doc Path list by adding the following macro #[utoipa_ignore] .

ex:

    /// Get all pets from database
    ///
    #[utoipa_ignore]  //<============== this Macro
    #[utoipa::path(
        responses(
            (status = 200, description = "List all Pets", body = [ListPetsDTO])
        )
    )]
    #[get("/pets")]
    async fn get_all_pets(req: HttpRequest, store: web::Data<AppState>) -> impl Responder {
        // your CODE
    }

note

sub-modules within a module containing methods tagged with utoipa::path are also automatically detected.

Features

  • automatic path detection
  • automatic schema detection (in progress)
You might also like...
A Rust library to extract useful data from HTML documents, suitable for web scraping.

select.rs A library to extract useful data from HTML documents, suitable for web scraping. NOTE: The following example only works in the upcoming rele

openapi schema serialization for rust

open api Rust crate for serializing and deserializing open api documents Documentation install add the following to your Cargo.toml file [dependencies

📮 An elegant Telegram bots framework for Rust
📮 An elegant Telegram bots framework for Rust

teloxide A full-featured framework that empowers you to easily build Telegram bots using the async/.await syntax in Rust. It handles all the difficult

Sōzu HTTP reverse proxy, configurable at runtime, fast and safe, built in Rust. It is awesome! Ping us on gitter to know more

Sōzu · Sōzu is a lightweight, fast, always-up reverse proxy server. Why use Sōzu? Hot configurable: Sozu can receive configuration changes at runtime

A Rust application which funnels external webhook event data to an Urbit chat.
A Rust application which funnels external webhook event data to an Urbit chat.

Urbit Webhook Funnel This is a simple Rust application which funnels external webhook event data to an Urbit chat. This application is intended to be

A html document syntax and operation library written in Rust, use APIs similar to jQuery.

Visdom A server-side html document syntax and operation library written in Rust, it uses apis similar to jQuery, left off the parts thoes only worked

Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.

Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.

Starlight is a JS engine in Rust which focuses on performance rather than ensuring 100% safety of JS runtime.

starlight Starlight is a JS engine in Rust which focuses on performance rather than ensuring 100% safety of JS runtime. Features Bytecode interpreter

A rust web framework with safety and speed in mind.

darpi A web api framework with speed and safety in mind. One of the big goals is to catch all errors at compile time, if possible. The framework uses

Releases(v0.3.0)
Owner
null
Simple example of axum, sqlx with sqlite and utoipa (swagger) - without auth

axum_crud_api Simple example to learn creating CRUD rest apis in Rust with axum, sqlx with sqlite and utoipa (swagger) - without auth Also shows how t

null 2 Nov 12, 2022
A Rust crate for managing authentication and authorization with support for multi-tenant / B2B products, powered by PropelAuth

PropelAuth Add authentication and authorization to your application. This library is meant to be used with a PropelAuth account. You can sign up and g

PropelAuth 3 Dec 10, 2022
A WebGPU implementation based on the excellent wgpu crate.

A WebGPU implementation based on the excellent wgpu crate.

Ben Noordhuis 3 Jul 30, 2022
A crate built on top of `axum-sessions`, implementing the CSRF Synchronizer Token Pattern

Axum Synchronizer Token Pattern CSRF prevention This crate provides a Cross-Site Request Forgery protection layer and middleware for use with the axum

null 3 Dec 15, 2022
Download .crate files of all versions of all crates from crates.io

get-all-crates Download .crate files of all versions of all crates from crates.io. Useful for things like noisy-clippy which need to analyze the sourc

David Tolnay 18 Jan 3, 2023
Rate Limiting middleware for Tower/Axum/Tonic/Hyper utilizing the governor crate

A Tower service and layer that provides a rate-limiting backend by governor. Based heavily on the work done for actix-governor. Works with Axum, Hyper

Ben Wishovich 31 Feb 15, 2023
Rust I18n is use Rust codegen for load YAML file storage translations on compile time, and give you a t! macro for simply get translation texts.

Rust I18n Rust I18n is use Rust codegen for load YAML file storage translations on compile time, and give you a t! macro for simply get translation te

Longbridge 73 Dec 27, 2022
lispr is a Rust macro that tries to implement a small subset of LISPs syntax in Rust

lispr lispr is a Rust macro that tries to implement a small subset of LISPs syntax in Rust. It is neither especially beautiful or efficient since it i

Jan Vaorin 0 Feb 4, 2022
Rust/Axum server implementation with PCR(Prisma Client Rust)

Realworld Rust Axum Prisma This project utilizes Rust with the Axum v0.7 framework along with the Prisma Client Rust to build a realworld application.

Neo 3 Dec 9, 2023
A Rust web framework

cargonauts - a Rust web framework Documentation cargonauts is a Rust web framework intended for building maintainable, well-factored web apps. This pr

null 179 Dec 25, 2022