SwiftStack is an opinionated and easy way to build REST APIs, websockets APIs, and RabbitMQ interfaces, taking inspiration from the elegant model shown in FastAPI in Python. Built on Watson webserver.
$ dotnet add package SwiftStackSwiftStack is an opinionated and easy way to build distributed systems — RESTful, message queue–oriented, or WebSocket–based — inspired by the elegant model shown in FastAPI (Python) but designed for C# developers who value clarity and speed.
MIT Licensed • No ceremony • Just build.
using SwiftStack;
class Program
{
static async Task Main(string[] args)
{
SwiftStackApp app = new SwiftStackApp("My test application");
app.Rest.Route("GET", "/", async (req) => "Hello world");
app.Rest.Route("POST", "/loopback", async (req) => req.Data);
app.Rest.Get("/search", async (req) =>
{
string query = req.Query["q"];
if (string.IsNullOrEmpty(query)) query = "no query provided";
int page = int.TryParse(req.Query["page"] as string, out int p) ? p : 1;
return new
{
Query = query,
Page = page,
Message = $"Searching for '{query}' on page {page}"
};
});
await app.Rest.Run();
}
}
</details>
<details>
<summary>Click to expand</summary>
</details>
<details>
<summary>Click to expand</summary>
</details>
<details>
<summary>Click to expand</summary>
</details>
<details>
<summary>Click to expand</summary>
</details>
<details>
<summary>Click to expand</summary>
</details>
using SwiftStack;
class Program
{
static async Task Main(string[] args)
{
SwiftStackApp app = new SwiftStackApp("My secure app");
app.Rest.AuthenticationRoute = AuthenticationRoute;
app.Rest.Route("GET", "/authenticated", async (req) => "Hello, authenticated user", true);
await app.Rest.Run();
}
static async Task<AuthResult> AuthenticationRoute(HttpContextBase ctx)
{
if (ctx.Request.Authorization?.Username == "user" &&
ctx.Request.Authorization?.Password == "password")
{
ctx.Metadata = new { Authorized = true };
return new AuthResult
{
AuthenticationResult = AuthenticationResultEnum.Success,
AuthorizationResult = AuthorizationResultEnum.Permitted
};
}
else
{
return new AuthResult
{
AuthenticationResult = AuthenticationResultEnum.NotFound,
AuthorizationResult = AuthorizationResultEnum.DeniedImplicit
};
}
}
}You can set a custom default route to handle requests that don't match any registered routes. This is useful for:
using SwiftStack;
using WatsonWebserver.Core;
class Program
{
static async Task Main(string[] args)
{
SwiftStackApp app = new SwiftStackApp("My app with catch-all");
// Register your specific routes
app.Rest.Get("/api/users", async (req) => new[] { "Alice", "Bob" });
app.Rest.Get("/api/health", async (req) => new { Status = "OK" });
// Set a custom default route for unmatched requests
app.Rest.DefaultRoute = async (HttpContextBase ctx) =>
{
// Example: Return a custom 404 response
ctx.Response.StatusCode = 404;
ctx.Response.ContentType = "application/json";
await ctx.Response.Send("{\"error\": \"Not Found\", \"message\": \"The requested endpoint does not exist.\"}");
};
await app.Rest.Run();
}
}For single-page applications, you typically want to serve the index page for any route that doesn't match an API endpoint:
app.Rest.DefaultRoute = async (HttpContextBase ctx) =>
{
// Skip API routes - let them 404 normally
if (ctx.Request.Url.RawWithoutQuery.StartsWith("/api/"))
{
ctx.Response.StatusCode = 404;
await ctx.Response.Send("{\"error\": \"API endpoint not found\"}");
return;
}
// Serve index.html for all other routes (SPA fallback)
ctx.Response.ContentType = "text/html";
string indexContent = File.ReadAllText("./wwwroot/index.html");
await ctx.Response.Send(indexContent);
};When DefaultRoute is not set, the built-in handler returns a 400 Bad Request response for unmatched requests.
SwiftStack includes built-in OpenAPI 3.0 documentation and Swagger UI for your REST APIs.
using SwiftStack;
using SwiftStack.Rest.OpenApi;
SwiftStackApp app = new SwiftStackApp("My API");
// Enable OpenAPI with configuration
app.Rest.UseOpenApi(openApi =>
{
openApi.Info.Title = "My API";
openApi.Info.Version = "1.0.0";
openApi.Info.Description = "A sample API built with SwiftStack";
openApi.Info.Contact = new OpenApiContact("Support", "support@example.com");
// Define tags for grouping endpoints
openApi.Tags.Add(new OpenApiTag("Users", "User management endpoints"));
openApi.Tags.Add(new OpenApiTag("Products", "Product catalog endpoints"));
// Define security schemes
openApi.SecuritySchemes["Bearer"] = OpenApiSecurityScheme.Bearer(
"JWT",
"Enter your JWT token");
openApi.SecuritySchemes["Basic"] = OpenApiSecurityScheme.Basic(
"Use username:password");
});
await app.Rest.Run();This automatically creates:
/openapi.json/swaggerUse the fluent API to add metadata to your routes:
// Simple route with documentation
app.Rest.Get("/", async (req) => "Hello, World!",
api => api
.WithTag("General")
.WithSummary("Root endpoint")
.WithDescription("Returns a simple greeting message"));
// Route with path parameters
app.Rest.Get("/users/{id}", async (req) =>
{
string id = req.Parameters["id"];
return new { Id = id, Name = "John Doe" };
},
api => api
.WithTag("Users")
.WithSummary("Get user by ID")
.WithParameter(OpenApiParameterMetadata.Path("id", "The user ID"))
.WithResponse(200, OpenApiResponseMetadata.Json<User>("User details"))
.WithResponse(404, OpenApiResponseMetadata.NotFound()));
// Route with query parameters
app.Rest.Get("/search", async (req) =>
{
string query = req.Query["q"];
int page = int.TryParse(req.Query["page"] as string, out int p) ? p : 1;
return new { Query = query, Page = page };
},
api => api
.WithTag("General")
.WithSummary("Search endpoint")
.WithParameter(OpenApiParameterMetadata.Query("q", "Search query", true))
.WithParameter(OpenApiParameterMetadata.Query("page", "Page number", false,
OpenApiSchemaMetadata.Integer())));
// Route with request body (type is inferred from generic parameter)
app.Rest.Post<User>("/users", async (req) =>
{
User user = req.GetData<User>();
return new { Id = Guid.NewGuid(), user.Email };
},
api => api
.WithTag("Users")
.WithSummary("Create a new user")
.WithRequestBody(OpenApiRequestBodyMetadata.Json<User>("User to create", true))
.WithResponse(201, OpenApiResponseMetadata.Json<User>("Created user")));
// Authenticated route
app.Rest.Get("/profile", async (req) => new { Email = "user@example.com" },
api => api
.WithTag("Users")
.WithSummary("Get current user profile")
.WithSecurity("Bearer")
.WithResponse(200, OpenApiResponseMetadata.Json<User>("User profile"))
.WithResponse(401, OpenApiResponseMetadata.Unauthorized()),
requireAuthentication: true);Schemas are automatically generated from your C# types:
public class User
{
public string Id { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public DateTime CreatedAt { get; set; }
}
// Use in responses - schema is auto-generated via reflection
.WithResponse(200, OpenApiResponseMetadata.Json<User>("User data"))
// Or create schemas manually
OpenApiSchemaMetadata.String() // string
OpenApiSchemaMetadata.Integer() // int32
OpenApiSchemaMetadata.Long() // int64
OpenApiSchemaMetadata.Number() // double
OpenApiSchemaMetadata.Boolean() // boolean
OpenApiSchemaMetadata.Array(OpenApiSchemaMetadata.String()) // string[]
OpenApiSchemaMetadata.FromType<MyClass>() // complex objectOpenApiResponseMetadata.Json<T>(description) // 200 with JSON body
OpenApiResponseMetadata.Text(description) // 200 with text body
OpenApiResponseMetadata.NoContent() // 204 No Content
OpenApiResponseMetadata.BadRequest() // 400 Bad Request
OpenApiResponseMetadata.Unauthorized() // 401 Unauthorized
OpenApiResponseMetadata.NotFound() // 404 Not Found
OpenApiResponseMetadata.Conflict() // 409 Conflict
OpenApiResponseMetadata.InternalServerError() // 500 Internal Server ErrorYou can control whether OpenAPI and Swagger UI endpoints are exposed:
// Both OpenAPI and Swagger UI enabled (default)
app.Rest.UseOpenApi();
// Disable Swagger UI but keep OpenAPI JSON endpoint
app.Rest.UseOpenApi(openApi =>
{
openApi.EnableSwaggerUi = false;
});
// Disable both OpenAPI and Swagger UI entirely
app.Rest.UseOpenApi(openApi =>
{
openApi.EnableOpenApi = false;
});| Setting | Default | Effect |
|---|---|---|
EnableOpenApi | true | When false, disables /openapi.json endpoint and Swagger UI |
EnableSwaggerUi | true | When false, disables /swagger endpoint only |
Note: Swagger UI depends on the OpenAPI document, so setting
EnableOpenApi = falsewill disable Swagger UI regardless of theEnableSwaggerUisetting.
app.Rest.UseOpenApi(openApi =>
{
// Enable/disable endpoints (defaults shown)
openApi.EnableOpenApi = true; // Set to false to disable OpenAPI entirely
openApi.EnableSwaggerUi = true; // Set to false to disable Swagger UI only
// Customize paths (defaults shown)
openApi.DocumentPath = "/openapi.json";
openApi.SwaggerUiPath = "/swagger";
// API info
openApi.Info.Title = "My API";
openApi.Info.Version = "1.0.0";
openApi.Info.Description = "API description";
openApi.Info.TermsOfService = "https://example.com/terms";
openApi.Info.Contact = new OpenApiContact("Name", "email@example.com");
openApi.Info.License = new OpenApiLicense("MIT", "https://opensource.org/licenses/MIT");
// External docs
openApi.ExternalDocs = new OpenApiExternalDocs(
"https://docs.example.com",
"Full documentation");
// Server configuration
openApi.Servers.Add(new OpenApiServer("https://api.example.com", "Production"));
openApi.Servers.Add(new OpenApiServer("https://staging-api.example.com", "Staging"));
});SwiftStack includes first-class RabbitMQ support, including resilient producer/consumer and broadcaster/receiver patterns.
Resilient modes use on-disk index files to recover state across process restarts.
using SwiftStack;
using SwiftStack.RabbitMq;
// Initialize app and RabbitMQ integration
SwiftStackApp app = new SwiftStackApp("RabbitMQ Example");
RabbitMqApp rabbit = new RabbitMqApp(app);
// Define queue settings
QueueProperties queueProps = new QueueProperties
{
Hostname = "localhost",
Name = "demo-queue",
AutoDelete = true
};
// Create producer and consumer
var producer = new RabbitMqProducer<string>(app.Logging, queueProps, 1024 * 1024);
var consumer = new RabbitMqConsumer<string>(app.Logging, queueProps, true);
consumer.MessageReceived += (sender, e) =>
{
Console.WriteLine($"[Consumer] {e.Data}");
};
// Initialize and send
await producer.InitializeAsync();
await consumer.InitializeAsync();
for (int i = 1; i <= 5; i++)
{
await producer.SendMessage($"Message {i}", Guid.NewGuid().ToString());
await Task.Delay(500);
}Resilient versions are identical except you use:
var producer = new ResilientRabbitMqProducer<string>(app.Logging, queueProps, "./producer.idx", 1024 * 1024);
var consumer = new ResilientRabbitMqConsumer<string>(app.Logging, queueProps, "./consumer.idx", 4, true);and the same for broadcaster/receiver via:
var broadcaster = new RabbitMqBroadcaster<MyType>(...);
var receiver = new RabbitMqBroadcastReceiver<MyType>(...);SwiftStack makes it trivial to stand up WebSocket servers with routing, default handlers, and direct server→client messaging.
using SwiftStack;
using SwiftStack.Websockets;
SwiftStackApp app = new SwiftStackApp("WebSockets Demo");
WebsocketsApp wsApp = new WebsocketsApp(app);
// Route for "echo"
wsApp.AddRoute("echo", async (msg, token) =>
{
await msg.RespondAsync($"Echo: {msg.DataAsString}");
});
// Default route
wsApp.DefaultRoute = async (msg, token) =>
{
await msg.RespondAsync("No route matched, sorry!");
};
// Start server
app.LoggingSettings.EnableConsole = true;
Task serverTask = wsApp.Run("127.0.0.1", 9006, CancellationToken.None);
// Example: sending server→client message after connect
wsApp.ClientConnected += async (sender, client) =>
{
await wsApp.WebsocketServer.SendAsync(client.Guid, "Welcome to the server!");
};
await serverTask;Client (any WebSocket library works — here’s with System.Net.WebSockets):
using var ws = new ClientWebSocket();
await ws.ConnectAsync(new Uri("ws://127.0.0.1:9006/echo"), CancellationToken.None);
await ws.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken.None);dotnet add package SwiftStackSee CHANGELOG.md for details.
If you’d like to financially support development: see DONATIONS.md.
Thanks to pngall.com for the lightning icon.