KScript docs
EN

Routes and APIs

Route parameters

A part of the path in braces is a route parameter. Its value reaches the controller as the variable of the same name, so {id} becomes $id:

<!-- routes.kscript -->
<KScript.Routes>
  <import path="controllers/people.kscript" as="people" />

  <Get path="/people/{id}" to="people.page" />
  <Get path="/archive/{year?}" to="people.index" />
  <Get path="/files/{path*}" to="people.index" />
</KScript.Routes>
// routes.kscript
import KScript.Http
import "controllers/people.kscript" as people

Routes {
  Get(path: /people/{id}, to: @people.page)
  Get(path: /archive/{year?}, to: @people.index)
  Get(path: /files/{path*}, to: @people.index)
}

{year?} is optional, and {path*} takes the rest of the path. A path is a slash path, so it needs no quotes: path: /people/{id} and path: "/people/{id}" are the same. Either way, {id} is a route parameter and is never filled in from a variable.

Rules for parameters

where: gives a parameter a rule. A request that breaks the rule doesn't match the route, so the next route gets a try:

<!-- routes.kscript -->
<KScript.Routes>
  <import path="controllers/people.kscript" as="people" />

  <Get path="/people/{id}" to="people.page" where="{ id: int }" />
  <Get path="/posts/{slug}" to="people.index" where="{ slug: slug }" />
</KScript.Routes>
// routes.kscript
import KScript.Http
import "controllers/people.kscript" as people

Routes {
  Get(path: /people/{id}, to: @people.page, where: { id: int })
  Get(path: /posts/{slug}, to: @people.index, where: { slug: slug })
}

The rules are number, int, alpha, alnum, slug, uuid, or a regular expression in quotes. In XML the same rules are written where="id: int, slug: slug".

Edit this page on GitHub