Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Routing and Requests

Path and Query Parameters

Read path and query parameters in Ktor, convert them to Int and other types safely, handle missing or invalid values with 400 errors, and decode URL escapes.

Most requests carry data in the URL. Path parameters identify a resource (/books/42); query parameters refine a request (/books?author=Ann&limit=10). Ktor exposes both through a Parameters object, which is a multi-map from names to lists of strings. This lesson shows how to read them, how to convert them safely, and how to turn bad input into proper 400 Bad Request answers rather than server errors.

Reading parameters

Kotlin
get("/books/{id}") {
    val id = call.parameters["id"]                         // String? from the path
    val author = call.request.queryParameters["author"]    // String? from ?author=
    val tags = call.request.queryParameters.getAll("tag")  // List<String>? from ?tag=a&tag=b
    call.respondText("id=$id author=$author tags=$tags")
}
  • call.parameters contains path parameters and query parameters merged. Use call.request.queryParameters when you specifically want the query string, so a path parameter cannot be shadowed by ?id=.
  • Values are always strings, and null when absent.
  • getAll(name) returns every value for a repeated name, which is how ?tag=a&tag=b works.
  • call.request.queryString() gives the raw string, and call.request.uri the full path with query.

Path and query values are URL-decoded for you: ?q=hello%20world arrives as hello world, and + becomes a space in query strings.

Converting types safely

Parameters are strings, so converting needs care. toInt() throws NumberFormatException for "abc"; if you let that escape you answer with 500, which wrongly blames the server for a client mistake. Use toIntOrNull() and answer 400:

Kotlin
get("/books/{id}") {
    val id = call.parameters["id"]?.toIntOrNull()
    if (id == null) {
        call.respond(HttpStatusCode.BadRequest, "id must be a number")
        return@get
    }
    call.respondText("Book #$id")
}

Ktor also has getOrFail, which converts and throws a ParameterConversionException (shown as 400 if you install the StatusPages plugin; see Status pages):

Kotlin
import io.ktor.server.util.*

get("/books/{id}") {
    val id = call.parameters.getOrFail<Int>("id")
    call.respondText("Book #$id")
}

getOrFail<T> supports the primitive types, so getOrFail<Long>, getOrFail<Boolean> and getOrFail<Double> work too.

Defaults and ranges

Optional query parameters should have a default and sensible bounds, especially for paging. A client that sends ?limit=1000000 must not make the server fetch a million rows:

Kotlin
get("/books") {
    val page = call.request.queryParameters["page"]?.toIntOrNull() ?: 1
    val limit = (call.request.queryParameters["limit"]?.toIntOrNull() ?: 20).coerceIn(1, 100)
    call.respondText("page=$page limit=$limit")
}

Stand-in: parse, decode and validate a URL

The Ktor Parameters type is a multi-map with decoding. The stand-in below builds the same thing with the JDK so you can see how a query string turns into repeated and decoded values, and how a safe intParam helper reports errors.

Kotlin Stand-in: query parsing and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The important design: invalid input produces a BadRequest (a client error), with a message that names the parameter, and never a stack trace.

Path versus query: when to use which

Use a path parameter for Use a query parameter for
Identifying one resource: /users/7 Filtering: /users?role=admin
Required values Optional values
Hierarchy: /users/7/orders/3 Sorting and paging: ?sort=name&page=2

A good test: if removing the parameter makes the URL point to a different kind of thing (a collection instead of an item), it belongs in the path. If it only narrows or reorders the same collection, it is a query parameter.

Never concatenate a parameter into SQL or HTML. A value such as ' OR '1'='1 or <script> is just a string to Ktor; escaping and parameterised queries are your job. The Exposed chapter shows safe queries.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type does call.parameters["id"] return?

    Parameters are strings and null when absent; convert them yourself.
  2. 2. A client sends /books/abc to a handler that does call.parameters["id"]!!.toInt(). What is the likely result?

    toInt() throws NumberFormatException; use toIntOrNull() and respond 400, or getOrFail with StatusPages.
  3. 3. How do you read all values of ?tag=a&tag=b?

    getAll returns a list of every value for a repeated name.
  4. 4. Why clamp a limit query parameter with something like coerceIn(1, 100)?

    Unbounded paging parameters are an easy way to overload a service.

Summary

  • call.parameters merges path and query parameters; call.request.queryParameters is the query only.
  • Values are String?; use toIntOrNull() or getOrFail<T> and answer 400 for bad input.
  • getAll(name) reads repeated parameters; URL escapes are decoded for you.
  • Give optional parameters defaults and bounds.
  • Path parameters identify; query parameters filter, sort and page.

Next: Requests and Responses