Skip to content

The Sword Application ​

The central piece of a Sword application is the Application struct. It represents your application instance and provides methods to build, configure, and run it.

Application Construction ​

Sword uses a builder pattern to create applications. It is implemented in the ApplicationBuilder struct, which lets you configure the application before building the Application instance.

The flow starts with Application::builder() and chains the configuration methods:

rust
let app = Application::builder()?
    .with_module::<SomeModule>()
    .build()?;

Internally, the builder() method:

  • Initializes the shared application state.
  • Loads the configuration from the TOML file.

API Reference: Methods and attributes of the 'ApplicationBuilder' struct

Accessing the application configuration ​

rust
pub config: Config

A public attribute that gives access to the application configuration loaded from the configuration file. For more details, see the Configuration section.

Registering modules ​

Registers a module that implements the Module trait. Modules group related controllers, components, and providers. Learn more

rust
pub fn with_module<M: Module>(self) -> Self

Parameters

  • M: a type that implements the Module trait.

Registering plugins ​

Registers a plugin that implements the Plugin trait. A plugin groups the providers and components of a reusable integration. Learn more

rust
pub fn with_plugin<P: Plugin>(self) -> Self

Parameters

  • P: a type that implements the Plugin trait.

Building the application ​

Finishes the ApplicationBuilder and returns an Application instance ready to run.

rust
pub fn build(mut self) -> Result<Application, Error>

Application Instance ​

Once you build an Application instance with build(), you can run it with run():

rust
#[sword::main]
async fn main() -> Result<(), Error> {
    let app = Application::builder()?
        .with_module::<SomeModule>()
        .build()?;

    app.run().await
}

API Reference: Methods and attributes of the 'Application' struct

Building from a custom configuration path ​

Loads the application configuration from a .toml file at a custom path.

rust
pub fn from_config_path<P: AsRef<Path>>(path: P)
    -> Result<ApplicationBuilder, Error>

Building from a 'Config' instance ​

Loads the application configuration from a manually created Config instance.

rust
pub fn from_config(config: Config) -> Result<ApplicationBuilder, Error>

Starting the application ​

Starts the core of the selected application type and begins listening for requests.

rust
pub async fn run(self) -> Result<(), Error>

The run method initializes the execution of the application and the associated engines. How each engine runs depends on the application type (Web, Socket.IO, Events, gRPC). If an error occurs during execution, a Result is returned with the corresponding error.

If an engine fails, the application and all associated engines stop.

The application also stops when it receives a termination signal:

  • SIGINT: generated by pressing Ctrl+C in the terminal. The process exits with code 0.

  • SIGTERM: normally sent by Docker, systemd or Kubernetes. The process exits with code 0.


Accessing the internal router ​

Available for Web and Socket.IO applications, it returns the internal router with the application state attached.

rust
pub fn router(&self) -> axum::Router

Use it to embed the application in another server or to build a test server.

Example

rust
let app = Application::builder()?
    .with_module::<SomeModule>()
    .build()?;

let router = app.router();

Adding layers to the router ​

Receives the router before the state is attached and returns the modified router. Use it to add Tower layers, services, or fallbacks.

rust
pub fn with_router<F>(mut self, f: F) -> Self
where
    F: FnOnce(axum::Router<State>) -> axum::Router<State>

Example

rust
use tower_http::cors::*;

let cors_layer = CorsLayer::new()
    .allow_origin(Any)
    .allow_methods(vec!["GET", "POST"]);

let app = Application::builder()?
    .with_module::<SomeModule>()
    .build()?
    .with_router(|router| router.layer(cors_layer));

These layers wrap everything the framework applies, so they run first on requests and last on responses. Learn more

The 'main' function ​

In Rust, program execution begins at the main function. In asynchronous frameworks, that function must be marked with a special attribute.

Sword provides the #[sword::main] macro, which initializes the application's internal tokio runtime and runs the main function asynchronously:

rust
use sword::prelude::*;

#[sword::main]
async fn main() -> Result<(), Error> {
    let app = Application::builder()?
        .with_module::<SomeModule>()
        .build()?;

    app.run().await
}

With this approach, you do not need to add tokio as a dependency unless you need it for other features.