Skip to content

Getting Started with Sword ​

You can start from an empty crate or run the examples in the GitHub repository. Each example is designed to show a specific part of the framework and help you understand how it works.

The sword-cli command line tool is still in development, so it is not recommended for starting a project right now.

Create a project ​

Sword is published on crates.io, so you can start from an empty crate without cloning the repository. The framework needs a configuration file: Application::builder() looks for config/config.toml and fails if it is missing.

bash
cargo new hello-sword
cd hello-sword
cargo add sword --features web

Create config/config.toml:

toml
[application]
name = "Hello Sword"

[web]
port = 3000

Replace src/main.rs with:

rust
use sword::prelude::*;
use sword::web::*;

#[controller(kind = Controller::Web, path = "/hello")]
struct HelloController;

impl HelloController {
    #[get("/")]
    async fn hello(&self) -> WebResult {
        Ok(JsonResponse::Ok().message("Hello from Sword"))
    }
}

struct AppModule;

impl Module for AppModule {
    fn register_controllers(controllers: &ControllerRegistry) {
        controllers.register::<HelloController>();
    }
}

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

    app.run().await
}

Run it and query the endpoint:

bash
cargo run
curl http://localhost:3000/hello
json
{ "code": 200, "success": true, "message": "Hello from Sword" }

Run the web example ​

The web example is the most complete one. It needs nothing but a Rust toolchain: the data lives in an in-memory SQLite database that is created on startup.

bash
git clone https://github.com/sword-web/sword.git
cd sword/examples/web
cargo run

The API is served under the /api prefix:

bash
curl http://localhost:8081/api/users

The same example ships a small browser client at http://localhost:8081/api/static/, which exercises the CRUD endpoints and the SSE stream without extra setup.

Examples ​

You can find the examples in the repository on GitHub.

Web Application Example ​

This is the most direct example for understanding the base flow of a REST API built with Sword on top of axum.

View on GitHub

Socket.IO Application Example ​

This example focuses on Socket.IO integration with Sword, using the socketioxide crate.

View on GitHub

gRPC Application Example ​

This example focuses on gRPC integration with Sword, using the tonic crate.

View on GitHub

Events Application Example ​

This example publishes and consumes events through two transports at once: in-memory for events that stay in the process, and NATS for events that leave it. It needs a NATS broker to run.

View on GitHub

Jobs Application Example ​

This example shows the three kinds of schedule: a cron expression, a fixed interval, and a one-shot task that runs after a delay.

View on GitHub