Search code examples
jsonscalamarshallingakka-httpargonaut

Sending an http response with Json content using marshallers in Akka Http


I want to send a Http error response with a message in JSON format in the body. I am having trouble using the PredefinedToResponseMarshallers.

I saw an implementation in the Akka docs but I tried a similar thing and it throws a compilation error.

import argonaut._, Argonaut._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.marshalling.{ Marshaller, ToResponseMarshaller } 

trait Sample extends Marshallers with Directives { 
     def login(user: Login): CRIX[HttpResponse] = {
        for {
          verification ← verify(user)
          resp = if (verification) {
            HttpResponse(NoContent, headers = Seq(
              .........
            ))
          }//below is my http Error response
          else Marshal(401 → "It is an Unauthorized Request".asJson).to[HttpResponse]
        } yield resp
      }
    }

It gives this compilation error :

Sample.scala:164: type mismatch;
[error]  found   : Object
[error]  required: akka.http.scaladsl.model.HttpResponse
[error]     } yield resp
[error]             ^
[error] one error found
[error] (http/compile:compileIncremental) Compilation failed

I have just started Akka Http so forgive me if it is trivially easy.

TL;DR: I want(examples) to learn how to use ToResponseMarshallers in Akka Http.


Solution

  • Method to[HttpResponse] of negative condition takes on Future[HttpResponse]. At the same time positive condition returns HttpResponse.

    Try something like (I assume verify takes on Future[T]):

    for {
      verification <- verify(user)
      resp <- if (verification) 
               Future.successful(HttpResponse(NoContent, headers = Seq(.........)) )
             else 
               Marshal(401 → "It is an Unauthorized Request".asJson).to[HttpResponse]
    } yield resp