Kest

Search

Search the documentation

FAQ

Raw body

Read the exact bytes of a request.

The question: My handler receives parsed JSON. How do I get the original bytes (for example to verify a signature)?

Parsing and re-encoding JSON can change it (spacing, key order, escaping). A signature is computed over the exact bytes that were sent, so you must check it against the unparsed body. Take the request object: request.body is the raw ByteArray.

@Post("/hooks/payments")
fun hook(@Request req: HttpRequest): String {
    verifier.verify({ req.header(it) }, req.body)            // the bytes as received, before any parsing
    val event = Json.parseObject(String(req.body))           // now parse them yourself
    ...
    return "ok"
}

Use a @Request req: HttpRequest parameter instead of @Body: if you also declare a @Body, the framework parses it as well (harmless, but wasteful and it will answer 400 for a non-JSON body).

For incoming webhooks use the ready-made WebhookGuard, which does exactly this (Webhooks).

Limits

The body is limited by maxBodyBytes (10 MB by default); a larger one is refused with 413 before your code runs. Raise it on the engine when you accept large uploads: NettyHttpAdapter(8080, maxBodyBytes = 50 shl 20). For files, see File upload and streaming.

Text, form and binary bodies

The same req.body works for any content type: plain text, application/x-www-form-urlencoded, binary data. Check req.header("content-type") and decode as needed.

Read more