Akka-http Common Operations: Reference + Examples

Last updated:

WIP Alert This is a work in progress. Current information is correct but more content will probably be added in the future.

Unless otherwise noted, all examples have been run on Akka version 2.4.x (will probably work on later versions too)

Extract Query String Parameters as a Map

def myRoute1: Route = {
  extract(ctx => ctx.request.uri.query()) { queryStringParams =>
  val params = queryStringParams.toMap
  // use them

Extract body contents

def myRoute2: Route = {
  extract(ctx => ctx.request) { request =>

    // toStrict retruns a future because the body contents may be very large
    request.entity.toStrict(TimeHelper.defaultStreamTimeout).map { materializedStream =>
    val data = materializedStream.data.utf8String

    //use data

Map a request context through an arbitrary function

A generic function that you can use to modify the request context before you start processing it.

For example, I use this to remove authorization parameters from the query string, because I don't need them anymore once the request has been authorized.

// note the function signature: this function returns a 
// function of type (RequestContext => RequestContext)
def dropParam(paramName: String): (RequestContext => RequestContext) = { ctx =>

    // ctx is short for context
    val queryStringParams = ctx.request.uri.query()

    // parameter that matches the name provided is removed
    // (if it exists)
    val parameterRemoved = query.toMap.filterKeys(key => key != paramName)

    // build the new query
    val newQuery = Query(parameterRemoved)

    // but we need a Uri which is something that wraps the Query
    val newUri = ctx.request.uri.withQuery(newQuery)

    // return the modified context

After creating the function, as above, you can use it when declaring routes, using mapRequestContext, which takes a mapper function as parameter:

// say you have a param called AUTH that you want to drop form the query string:
                // handle the request here. parameter "AUTH" will not be here

See also

Dialogue & Discussion