Kitura Logo

Writing Custom Paths

When hooking up middleware and handlers to your Kitura server, you can customize your paths using Kitura’s path syntax. This guide assumes familiarity with the concepts of Kitura app and route handler.

Static Paths

The most basic of paths, static paths, are supported. Simply specify the path as it is when mounting your middleware or handler, like so:

// handler example
app.get("/test") { req, res, next in
    try res.send("Hello world").end()
}

In this case, the path /test will be matched for /test only.

Paths with Parameter(s)

Kitura supports parameters in the path for use cases such as performing CRUD operations against an object. Simply tag the parameter using :, like so:

app.get("/:id") { req, res, next in
    let id = req.parameters["id"] ?? ""
    try res.send("Hello world to user \(id)").end()
}

In this case, the path /:id will be for /123 as well as /abc. You can then access the id parameter’s value via req.parameters["id"].

Parameter Modifiers

Zero or One

You can specify that a parameter is optional by using the ? operator, like so:

app.get("/:id?") { req, res, next in
    let id = req.parameters["id"] ?? ""
    try res.send("Hello world to user \(id)").end()
}

In this case, the path /:id? will be matched for both / and /123.

Zero or Many

You can specify that a parameter should be matched zero times, or as many times as possible, by using the * operator, like so:

app.get("/:id*") { req, res, next in
    let id = req.parameters["id"] ?? ""
    try res.send("Hello world to user \(id)").end()
}

In this case, the path /:id* will be matched for /, /123, and /abc/def/ghi.

One or Many

You can specify that a parameter should be matched one or more times by using the + operator, like so:

app.get("/:id+") { req, res, next in
    let id = req.parameters["id"] ?? ""
    try res.send("Hello world to user \(id)").end()
}

In this case, the path /:id+ will be matched for /123 and /abc/def/ghi, but not /.

Custom Matching

In addition to modifying parameters, you can also use regular expressions to specify what kinds of URLs can be matched and captured as parameters. Simply enclose your regex in () and append it to the parameter name, like so:

app.get("/:id(\\d+)") { req, res, next in
    let id = req.parameters["id"] ?? ""
    try res.send("Hello world to user \(id)").end()
}

In this case, the path /:id(\\d+) specifies that only digits should be matched; this path will be matched for /123, but not / or /abc.

Unnamed Parameters

You can use custom matching without naming a parameter, like so:

app.get("/(\\d+)") { req, res, next in
    let id = req.parameters["0"] ?? ""
    try res.send("Hello world to user \(id)").end()
}

In this case, the path /(\\d+) will be matched for /123, but not / or /abc. The matched parameter can then be referenced via its index; in this case, since this is the first unnamed parameter, its index is 0.

Slack icon

NEED HELP?

MESSAGE US ON SLACK.