What are the core components of Akka HTTP?

Core Components of Akka HTTP :

Akka HTTP is designed around a set of modular components that work together to provide flexible, reactive, and high-performance HTTP functionalities. Here are its core components:

1. HTTP Model
  • Description: A set of immutable classes and objects representing HTTP requests, responses, headers, and entities.
  • Purpose: Provides a type-safe and consistent way to work with HTTP messages.
  • Key Elements:
    • HttpRequest: Represents an HTTP request.
    • HttpResponse: Represents an HTTP response.
    • HttpEntity: Encapsulates the body of a request or response.
    • Headers: Standard and custom headers like Authorization, Content-Type, etc.

Example :
val request = HttpRequest(uri = "/api/data")
val response = HttpResponse(entity = "Hello, Akka HTTP!")?

 

2. Routing DSL :
  • Description: A high-level declarative API for defining HTTP endpoints and handling requests.
  • Purpose: Simplifies creating RESTful APIs by abstracting HTTP handling logic.
  • Key Features:
    • Match HTTP methods (e.g., GET, POST).
    • Match paths or query parameters.
    • Process requests and send responses.

Example :
val route =
  path("hello") {
    get {
      complete("Hello, World!")
    }
  }?

 

3. Directives :
  • Description: Building blocks for routing logic, encapsulating common operations like path matching, header extraction, and request processing.
  • Purpose: Provide composable components for building routes.
  • Types of Directives:
    • Path Directives: Match specific paths (path, pathPrefix).
    • Method Directives: Match HTTP methods (get, post).
    • Header Directives: Extract headers (optionalHeaderValueByName).
    • Entity Directives: Extract and process request bodies (entity).
Example :
val route =
  path("user" / IntNumber) { userId =>
    get {
      complete(s"Fetching user with ID: $userId")
    }
  }?
4. Marshalling and Unmarshalling :
  • Description: Converting objects into HTTP entities (marshalling) and vice versa (unmarshalling).
  • Purpose: Enables serialization and deserialization of data (e.g., JSON, XML).
  • Common Libraries:
    • Akka HTTP integrates well with libraries like Spray JSON or Jackson.

Example :
import spray.json._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._

case class User(name: String, age: Int)
object UserJsonProtocol extends DefaultJsonProtocol {
  implicit val userFormat = jsonFormat2(User)
}

import UserJsonProtocol._

val route =
  path("createUser") {
    post {
      entity(as[User]) { user =>
        complete(s"Received user: ${user.name}")
      }
    }
  }?

 

5. Akka Streams :
  • Description: A reactive streams-based toolkit used for processing data streams asynchronously and non-blockingly.
  • Purpose: Enables streaming data handling in Akka HTTP, such as processing large files or continuous data streams.
  • Key Features:
    • Backpressure handling.
    • Easy integration with HTTP entities.

Example :
import akka.stream.scaladsl.Source
val numbers = Source(1 to 100)
val route =
  path("stream") {
    get {
      complete(numbers.map(_.toString))
    }
  }?
6. Connection Layer :
  • Description: The lower-level layer responsible for handling HTTP connections, requests, and responses.
  • Purpose: Provides direct control over the HTTP connection lifecycle.
  • Key Features:
    • Start an HTTP server.
    • Create HTTP clients for external API interactions.
  • Example: Starting a server.
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._

val responseFuture = Http().singleRequest(HttpRequest(uri = "https://api.example.com/data"))?

 

7. Client-Side API :
  • Description: A high-level API for making HTTP requests to external services.
  • Purpose: Allows interaction with RESTful APIs or HTTP servers from Akka-based applications.
  • Key Features:
    • Send requests and receive responses.
    • Streaming and non-blocking support.

Example :
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._

val responseFuture = Http().singleRequest(HttpRequest(uri = "https://api.example.com/data"))?
8. TestKit :
  • Description: Tools and utilities for testing Akka HTTP routes and applications.
  • Purpose: Simplifies writing unit tests for routes and APIs.
  • Key Features:
    • Simulate HTTP requests.
    • Validate responses and statuses.
Example :
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class MyRouteTest extends AnyWordSpec with Matchers with ScalatestRouteTest {
  val route =
    path("test") {
      get {
        complete("Test successful")
      }
    }

  "The service" should {
    "return a successful response for GET /test" in {
      Get("/test") ~> route ~> check {
        responseAs[String] shouldEqual "Test successful"
      }
    }
  }
}?