CRad
CRad

Reputation: 3

Akka-http: How do I map response to object

Not sure if I'm getting this whole routing DSL thing right but here's the question. I want to do a post to external service such as:

val post = pathPrefix("somePath") {
  post {     
    //get the response mapped to my Output object
  }
}

Then I want the response (which is a Json) to be mapped to an object matching the fields for example Output (assuming I have my JsonProtocol set up). How is this done?

Upvotes: 0

Views: 1868

Answers (2)

Markon
Markon

Reputation: 4600

You are using HTTP server directives to "retrieve" something "externally". This is what typically an HTTP client does.

For this sort of things, you can use akka http client api.

For example:

val response = Http().singleRequest(HttpRequest(uri = "http://akka.io"))
response onComplete { 
  case Success(res) =>
    val entity = Unmarshal(res.entity).to[YourDomainObject]
    // use entity here
  case Failure(ex) =>  // do something here 
}

However, this requires some Unmarshaller (to deserialize the received json). Take also a look at Json Support, as it helps you define marshallers easily:

case class YourDomainObject(id: String, name: String)
implicit val YourDomainObjectFormat = jsonFormat2(YourDomainObject)

Upvotes: 3

Shivansh
Shivansh

Reputation: 3544

I think what you are trying to ask is how to get the body i.e in JSOn format to the Case class that you have

Here is a quick example:

    path("createBot" / Segment) { tag: String =>
            post {
              decodeRequest {
                entity(as[CaseClassName]) { caseclassInstance: CaseClassName =>
                   val updatedAnswer = doSomeStuff(caseclassInstance)
                  complete {
                    "Done"
                  }
                }
          }

You can find more detailed example from here : https://github.com/InternityFoundation/Stackoverflowbots/blob/master/src/main/scala/in/internity/http/RestService.scala#L56

I hope it answers your question.

Upvotes: 0

Related Questions