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:
| Sent | Answer |
|---|---|
JSON that is a T and passes | handler runs |
| not JSON | 400 with where: Invalid JSON: expected `:` at line 1, column 9 |
JSON not a T, or failing a check | 422, every problem by field |
non-JSON Content-Type | 415 |
no body, body: Option<T> | None |
FromJson
#[derive(FromJson)] reads a struct from an object.
Optioncan be absent ornull. An absentboolis 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 (
300is not au8),bool,Option,Vec,Box, string-key maps andwisp::Value(any JSON:body.get("title")). wisp::from_json::<T>(bytes)reads JSON anywhere.wisp::json::parsegives aValue:get as_str as_bool as_i64 as_f64 as_number as_array as_object(andas_array_mut as_object_mut into_array into_objectto change or take it), ormatch v.kind()onwisp::json::Kind. Make one withValue::from(..),Value::number("1e3")orValue::NULL.
Checks
| Rule | Checks | On |
|---|---|---|
len = 1..=200 | length or item count | strings, lists |
min = 0 max = 100 | bounds | numbers |
min_len = 1 max_len = 200 | length or items | strings, lists |
email | what <input type="email"> takes, 254 bytes at most | strings |
Nonepasses. 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
| Returns | Client gets |
|---|---|
a Json value (#[derive(Json)], Vec, numbers, strings, maps) | 200 + JSON |
nothing, Result<()> | 204 |
a Response with status 205 | bodiless |
Response | it |
Option<Response> | it, or 404 |
Option<T> | JSON, 204 for Some(()), 404 for None |
any of these in a Result | same, 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"}}
errorsonly 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").erroris your message, else the status name.accept: application/problem+json, orWISP_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), orcx.header_or("x-api-version", 1).(group)folders do not change URLs.[id=int]answers/api/notes/abcwith 404 before any code runs. cx.cors("*")?inbefore(a preflight is theErrit returns), orconst CORS: &str = "*";, where the route answers its own preflight with 204 before itsMIDDLEWAREor rate limit. Errors keep the CORS headers, so the page can read them. A request with noorigingetsvary: originfrom a list (oraccess-control-allow-origin: *from*), so a shared cache never hands it to another site's request. On aCACHEroute, the kept answer holds each header that the handler set, also those beforecx.cors. Withcx.cors("*"), a request with anyorigingets a hit. Whenaccess-control-allow-originechoes an origin, the kept answer holds one origin at a time. A request with the sameorigingets 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 acorsrule 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 ascx.corsto every reply of those paths and answers their preflight with a 204 whatever the route says (a 405, a 404, anallowlist), so no route needsconst CORS. A site not listed getsvary: originand no allowance. A static export (wisp build --static) writes no CORS headers: that is for the server. A route's owncx.corsorconst CORSwins: a reply that already hasaccess-control-allow-originorvary: originis 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'sconst CORS. On the edge, each request for a path with acorsrule goes to the app. The bridge keeps no answer of it for the next request. An app with nocorsrule 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?