Search code examples
javascalaakkaakka-http

Passing data with request using Akka http


I am new to Scala/Akka and I have a service that I want to call using Akka Scaladsl. Using curl, I can call the service like this:

curl -v -d "STRING_DATA" -X GET http://localhost:3838/query?format=json

I know I can call the service like this using Scaladsl:

Http().singleRequest(HttpRequest(uri = "http://localhost:3838/query?format=json"))
responseFuture onComplete {
    case Success(response) => {
        // Do something with the response here..
    }
}

I am not sure how I can pass the "data" ("STRING_DATA") along with the request through HttpRequest. Thoughts?


Solution

  • curl -v -d "STRING_DATA" -X GET http://localhost:3838/query?format=json
    

    The above command makes a GET request with the application/x-www-form-urlencoded content type (if you left out the -X GET, the command would be a POST because of the -d parameter). Using FormData is one way to model application/x-www-form-urlencoded data in Akka HTTP:

    val ent = FormData(Map("format" -> "json", "data" -> "STRING_DATA")).toEntity
    

    To send a POST request with that data:

    Http().singleRequest(HttpRequest(method = HttpMethods.POST,
        uri = "http://localhost:3838/query", entity = ent))
    

    To send a GET request:

    Http().singleRequest(HttpRequest(uri = "http://localhost:3838/query", entity = ent))