Error while calling an API using akka in scala

227 Views Asked by At

TO start with I am very new to Scala and also I don't have any Java experience also. I am trying to call an API using simple Scala code and running into the errors. Code looks like:

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer

import scala.concurrent.Future
import scala.util.{ Failure, Success }

object Client {
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()
    // needed for the future flatMap/onComplete in the end
    implicit val executionContext = system.dispatcher

    val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = "https://akka.io"))

    responseFuture
      .onComplete {
        case Success(res) => println(res)
        case Failure(_)   => sys.error("something wrong")
      }
  }
}

Basically, I have just copied the code from Akka documentation and trying to run it.

I get the following errors:

not found: value ActorSystem implicit val system = ActorSystem()

not found: value ActorMaterializer implicit val materializer = ActorMaterializer()

Cannot find an implicit ExecutionContext. You might pass an (implicit ec: ExecutionContext) parameter to your method.

Also 'ActorMaterializer()' now seems to be deprecated. Is this the reason for errors?

Thanks in advance :)

2

There are 2 best solutions below

0
On

You may need to add akka-streams as a dependency in your build tool.

ActorMaterializer.apply should just be a warning, unrelated to your other error. Might be worth opening an issue on github asking for updated docs for this snippet though.

0
On

This should get you going. In your build.sbt

scalaVersion := "2.13.8"

val akkaVersion = "2.6.19"
val akkaHTTPVersion = "10.2.9"

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-stream" % akkaVersion,
  "com.typesafe.akka" %% "akka-actor" % akkaVersion,
  "com.typesafe.akka" %% "akka-http" % akkaHTTPVersion
)

The code below is from the latest Doc, with the added line to consume the response entity as described in the Doc.

object HttpClientSingleRequest extends App {
  implicit val system: ActorSystem = ActorSystem()

  import system.dispatcher

  val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = "https://akka.io"))
  responseFuture
    .onComplete {
      case Success(res) =>
        // Even if we don’t care about the response entity, we must consume it 
        res.entity.discardBytes()
        println(s"Success: ${res.status}")
      case Failure(ex) => sys.error(s"Something wrong: ${ex.getMessage}")
    }
}