DocsCustom Routes

Custom Routes

Extend Postrust with custom Rust handlers for webhooks, background jobs, and custom business logic.

Overview

Custom routes allow you to add your own endpoints alongside the auto-generated REST and GraphQL APIs. This is useful for:

  • Webhook handlers (Stripe, GitHub, etc.)
  • Custom authentication flows
  • Background job triggers
  • Custom business logic

Basic Example

Edit crates/postrust-server/src/custom.rs:

Rust
use axum::{Router, Json, routing::post};
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct WebhookPayload {
    event: String,
    data: serde_json::Value,
}

#[derive(Serialize)]
struct WebhookResponse {
    received: bool,
}

async fn handle_webhook(
    Json(payload): Json<WebhookPayload>,
) -> Json<WebhookResponse> {
    println!("Received webhook: {}", payload.event);

    // Process the webhook...

    Json(WebhookResponse { received: true })
}

pub fn custom_routes() -> Router {
    Router::new()
        .route("/webhooks/stripe", post(handle_webhook))
}

Accessing the Database

Rust
use axum::{Router, Json, Extension, routing::get};
use sqlx::PgPool;

async fn get_stats(
    Extension(pool): Extension<PgPool>,
) -> Json<serde_json::Value> {
    let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
        .fetch_one(&pool)
        .await
        .unwrap();

    Json(serde_json::json!({
        "user_count": count.0
    }))
}

pub fn custom_routes() -> Router {
    Router::new()
        .route("/stats", get(get_stats))
}

Building with Custom Routes

# Build with your custom routes
cargo build --release -p postrust-server

# Build with admin UI
cargo build --release -p postrust-server --features admin-ui

# Run
./target/release/postrust