Wisp is in pre-release, self-hosted since GitHub suspended us. Install it, or see the changelog.

Wisp

Input, Output and Errors

Input

Each param but cx is read by name: route param, then form field or JSON object member, then query. fn put(id: u64, title: String, done: bool) takes a form post and {"title":"Tea","done":true} alike. A missing param or wrong type is an error naming it.

body: T is the whole JSON body:

SentAnswer
JSON that is a T and passeshandler runs
not JSON400 with where: Invalid JSON: expected `:` at line 1, column 9
JSON not a T, or failing a check422, every problem by field
non-JSON Content-Type415
no body, body: Option<T>None

FromJson

#[derive(FromJson)] reads a struct from an object.

  • Option can be absent or null. An absent bool is false. Extra members are ignored.
  • A one-field tuple struct reads as that field. A fieldless enum reads from its variant name ("Low").
  • Also implemented for strings, numbers (300 is not a u8), bool, Option, Vec, Box, string-key maps and wisp::Value (any JSON: body.get("title")).
  • wisp::from_json::<T>(bytes) reads JSON anywhere. wisp::json::parse gives a Value: get as_str as_bool as_i64 as_f64 as_number as_array as_object (and as_array_mut as_object_mut into_array into_object to change or take it), or match v.kind() on wisp::json::Kind. Make one with Value::from(..), Value::number("1e3") or Value::NULL.

Checks

RuleChecksOn
len = 1..=200length or item countstrings, lists
min = 0 max = 100boundsnumbers
min_len = 1 max_len = 200length or itemsstrings, lists
emailwhat <input type="email"> takes, 254 bytes at moststrings
  • None passes. Further rules (url slug uuid alnum phone not_blank ascii lowercase no_html date min_date max_date step one_of pattern with): Data, files and jobs.
  • An unknown rule is a build error listing the valid ones.
  • Own checks: return invalid("email", "is already taken") (422). Error::invalid(..).and(..) names several fields.

Output

ReturnsClient gets
a Json value (#[derive(Json)], Vec, numbers, strings, maps)200 + JSON
nothing, Result<()>204
a Response with status 205bodiless
Responseit
Option<Response>it, or 404
Option<T>JSON, 204 for Some(()), 404 for None
any of these in a Resultsame, or the error

Response::created(&v) is 201. Response::json_of(&v).with_status(202) sets 202. .with_header(name, value) adds a header (also on Error, and cx.set_header in a page). Its value is a String or a &'static str. A &'static str is not copied. A borrowed &str that is not 'static needs .to_string(). A single-valued header (content-type, cache-control, location, etag) replaces the earlier value. content-length and transfer-encoding belong to the server. Response::text and its kin take a String or &str (the IntoText trait). Response::text sends content-type: text/plain;charset=UTF-8 on every target. At load, the edge bridge checks if new Response(string) has this type (Deno does, Bun does not). Where it does, the bridge sends a plain text 200 with no headers object. In a page, cx.set_status(404) sets the status; one outside 200 to 599 is logged and ignored.

Query: cx.query("q"), cx.query_or("page", 1) (parsed, else the default), cx.query_string() (raw, no ?). cx.request_id() is sent back as x-request-id.

Errors Are JSON

An error is JSON (else the app's +error.wisp, else Wisp's default page) when the request targets a +server.rs, is under /api, sent JSON or prefers JSON by Accept, or has no Accept and is not a browser navigating. An app with no pages always answers JSON.

{"status": 422, "code": "invalid", "error": "title: must have at least 1 character",
 "errors": {"title": "must have at least 1 character"}}
  • errors only for invalid input.
  • code: the status's (bad_request unauthorized forbidden not_found method_not_allowed conflict precondition_failed too_large unsupported_media_type invalid rate_limited internal unavailable) or your own: Error::new(409, "That email is taken").with_code("email_taken").
  • error is your message, else the status name.
  • accept: application/problem+json, or WISP_PROBLEM_JSON=on, gives RFC 9457 (type, title, status, code, detail, errors).
  • This covers 404, 405, error(403, "…") and panics (500, details in dev only).

Webhooks

// src/routes/hooks/github/+server.rs
fn post(cx: &mut Cx, body: Value) -> Result {
    cx.need_signature("GITHUB_SECRET", "x-hub-signature-256")?; // 401 unless it matches
    Ok(())
}
  • HMAC-SHA256 of the body with the secret in that variable, hex (with or without sha256=) or base64 (Shopify).
  • Stripe's stripe-signature (t=…,v1=…) signs the time too, and is refused after five minutes.
  • Other schemes: wisp::hex(&wisp::hmac_sha256(secret, message)), wisp::secure_eq.

Big Lists

fn get() -> Response {
    Response::ndjson(|out| async move {
        for page in 0.. {
            let rows = db::page(page).await;
            if rows.is_empty() {
                break;
            }
            // stops once the client left
            for row in rows {
                out.line(&row).await?;
            }
        }
        Ok(())
    })
}

Versions, CORS

  • Versions are folders (api/v1/notes), or cx.header_or("x-api-version", 1). (group) folders do not change URLs. [id=int] answers /api/notes/abc with 404 before any code runs.
  • cx.cors("*")? in before (a preflight is the Err it returns), or const CORS: &str = "*";, where the route answers its own preflight with 204 before its MIDDLEWARE or rate limit. Errors keep the CORS headers, so the page can read them. A request with no origin gets vary: origin from a list (or access-control-allow-origin: * from *), so a shared cache never hands it to another site's request. On a CACHE route, the kept answer holds each header that the handler set, also those before cx.cors. With cx.cors("*"), a request with any origin gets a hit. When access-control-allow-origin echoes an origin, the kept answer holds one origin at a time. A request with the same origin gets a hit, and alternating origins run the handler again.
  • Allowed sites: "https://app.example.com https://example.com" (these can then send cookies). Others get no CORS headers.
  • Some paths only: if cx.path().starts_with("/api/") { cx.cors("*")?; }, or a cors rule in [package.metadata.wisp]: cors = ["/api/[...p] https://app.example.com https://x.com", "/pub/[...p] *"] (pattern origins, the first rule that fits the path wins). It adds the same headers as cx.cors to every reply of those paths and answers their preflight with a 204 whatever the route says (a 405, a 404, an allow list), so no route needs const CORS. A site not listed gets vary: origin and no allowance. A static export (wisp build --static) writes no CORS headers: that is for the server. A route's own cx.cors or const CORS wins: a reply that already has access-control-allow-origin or vary: origin is left as the route made it. Rules cover reads and preflights. The origin check of a credentialed write (CSRF) does not change, so for those use the route's const CORS. On the edge, each request for a path with a cors rule goes to the app. The bridge keeps no answer of it for the next request. An app with no cors rule pays nothing for it.
  • cx.route() is the pattern (/api/posts/[id]), a label for metrics that does not grow with every id.

Is This Page Useful?

View This Page's Source

Type to search every docs page and heading.