OpenAPI and Tests
OpenAPI and Docs Page
Example: JSON API shows its code and downloads as a project.
The build describes the app as OpenAPI 3.1 at /_wisp/openapi.json. /_wisp/docs lists it with a try-it form. It is on in dev and off in release; WISP_API_DOCS=on|off overrides. The Cloudflare, Pages, Vercel and Netlify builds serve the JSON but 404 on /_wisp/docs. No annotations are needed:
- Every
+server.rsendpoint, and a#[derive(Rest)]type's routes and/[id]: path, query and header parameters,body: T(JSON) or form fields, what it returns (Optionadds a 404,()a 204), anddefault, 400, 401, 422 errors (Error, and RFC 9457Problem). - A resource adds
if-match/if-none-matchheaders,etag,location,x-total-count, a filter parameter per plain field and a 201 for POST. - Every page as a GET of
text/html, and each#[action]of its Rust (the script of+page.wispor+page.rs) as a POST.fn defaultis thepostof/contact. The others answer/contact?/send. OpenAPI path keys hold no query, so each is an operation in thex-wisp-action-sendfield of the/contactpath item. The form body (multipart/form-datawith anImageorUpload),#[validate]checks, and 200/303/422 are described. - Types come from the route file or
src/*.rs.#[validate]limits becomeminLength,maximum,format: email... An enum without fields becomes its variant names. - A type of yours named
ErrororProblemappears asError_orProblem_(ApiError,WispError,Optionsin the client), so Wisp's keep their names. Same-named different types in two files becomeItemandItem_2. - Security:
bearerandsession(the cookie) are declared when used. A route is marked when it has#[rest(key|write|admin = "...")]or its body callscx.need_bearer/cx.bearer()orcx.signed_in/cx.user. Afn beforeinsrc/hooks.rsthat does the same marks every operation (only changes, if it looks atcx.writes()). Wisp reads the code and does not run it, so a check inside a helper is missed. operationIdis the method and path (/api/notes/[id]isget_api_notes_by_id,getApiNotesByIdin the client). Two endpoints that give the same id, or the same client method name (/api/[id]and/api/byIdare bothgetApiById), are a build error. Pages and actions (page_a_b,action_add_a_b) need no unique name for anything: a page whose folder name has a-,.or_gets a short hash of its path at the end of the id, so/a/band/a-bcan both exist.- Each
[[opt]]or[...rest]segment doubles the paths of a route: a route with two of them has four paths. Only the first 8 such segments give paths. Paths differing only by parameter names are one path to OpenAPI.
wisp openapi prints the document (-o openapi.json writes it). Commit that file and run wisp openapi --check in CI: it fails with the command to run when the file is out of date.
TypeScript Client
Typed, no dependencies: /_wisp/client.ts, or wisp client [--out web/api.ts]:
import { client, WispError } from './client';
const api = client({ base: 'https://api.example.com', token: key });
const note = await api.postApiNotes({ title: 'Tea' });
const page = await api.getApiNotes({ sort: '-created_at', limit: 20 });
try { await api.deleteApiNotesById(note.id); }
catch (e) { if (e instanceof WispError && e.code === 'not_found') {} }
Method name = HTTP method + path. PATCH takes a Partial. An [[opt]] or [...rest] segment is an optional last argument (getFilesByPath("a/b") calls /files/a/b). A path parameter keeps its letters and digits, and any other character becomes _. A name that is a JavaScript reserved word, or that the method uses (body, String, encodeURIComponent, arguments, eval), gets a _ at the end. A name that starts with a digit gets a _ at the start. If two parameters give one name, the later one gets _ at the end until it is new. For a POST, PUT, PATCH or DELETE input that is a struct but not body (note: Note), the server reads the request body by its fields. So the document and the client name the fields. A field cannot have the name of body, of a route parameter or of another input. A GET reads no body: a GET with such an input is a build error ("A GET reads no body: take the fields as inputs"). A handler with body: T and such a struct is a build error too ("body: T and note: Note both read the request body: take one"). The client throws on a path piece that is . or ...
Tests
In process, no port, same routing, hooks and errors (more tools: Testing):
#[test]
fn notes() {
let mut app = wisp::test::client::<App>();
app.bearer("dev-key"); // every request from now on
let made = app.post_json("/api/notes", r#"{"title": "Buy tea"}"#);
assert_eq!(made.status, 201);
let note: Note = made.json(); // any FromJson type; Value for any JSON
assert_eq!(app.post_json("/api/notes", r#"{"title": ""}"#).status, 422);
}
- Also
get put_json patch_json delete post_form send_json(method, url, json),send(Request),next_chunk(events as sent). header(name, value)applies to the next request only (if-match).- Tables are in memory.
In a Browser
With feature browser (new apps have it: wisp test --browser) a test drives headless Chrome or Edge over the DevTools protocol. No Node.
#[test]
fn counter() {
let mut b = wisp::browser!(App); // the app on a free port, and a browser
b.goto("/");
b.click("text=Plus One");
assert_eq!(b.text("output"), "1");
}
goto(path) click(sel) hover(sel) fill(sel, text) press(key) text(sel) attr(sel, name) count(sel) wait(sel) eval(js) -> Value url() offline(on) scripts(on) screenshot(path) timeout(d)
- Selectors: CSS, or
text=Plus One(innermost element whose text,aria-labelortitlecontains it, any case). - Actions wait for the element and for the page to settle. A wait over 15 s fails with the address and DOM.
evalreturns the value as JSON.undefinedgivesValue::NULL, and an object (an element too) gives its own fields. A browser may fail to send some values (for examplewindow). Thenevalfails with the browser's error. For such a statement, usevoid (...)or return JSON (el.id).scripts(false)turns JavaScript off in the page, as a visitor with scripts off sees the app.scripts(true)turns it on again. Pages, forms and redirects work as before. An action that starts a navigation waits until the page loads.- Browser:
$WISP_BROWSER, else Chrome, Edge, Chromium or Brave. With none,browser!returns and the test passes, skipped.wisp::test::browser::<App>()is anOption<Browser>.wisp::test::browser_at(url)is the same for a server that already runs (such aswisp dev). --no-sandboxon Linux.
Where It Runs
The binary, Docker, Lambda and tower run all of this. On the edge (--target cloudflare etc.) each request may run in its own instance:
wisp::channelandwisp::everyare not there.RateLimitcounts in the memory of each instance, so for one count for the whole site use the host's rate limiting. WebSockets work on hosts that can hold a socket and answer 501 on Vercel and Netlify (WebSockets).- Jobs (
cron,work) run from the host's cron triggers (Edge and serverless targets). - Tables are per-instance memory.
Dev logs every request, release logs failures. To return a proxy's request id, call cx.set_header("x-request-id", id) in before (WISP_LOG=json: wisp-ref/api.md).
Is This Page Useful?