Search code examples
javaakkaakka-http

Connecting Akka HTTP directly to an Akka Stream Flow


I've looked through the examples at https://doc.akka.io/docs/akka-http/current/introduction.html for Akka HTTP routing and strangely for something built on top of Akka Streams none of the examples connect to a stream.

Can somebody show a simple example of creating a Java DSL flow (not Scala please), and then connecting a Route directly to that flow?

Or am I missing the point and it's not possible but requires some CompletionStage code within the Route to wait for a result of glue code that calls a Flow?

Edit: to clarify the flow can do something like append a string to a posted request body.


Solution

  • Edit: to clarify the flow can do something like append a string to a posted request body.

    Michał's answer contains good links, so please give them a read. Akka HTTP is by default and always streaming with its data -- e.g. the entities. So for example to do a streaming "echo" which at the same time adds a suffix, you could do something like this:

    path("test", () ->
      // extract the request entity, it contains the streamed entity as `getDataBytes`
      extractRequestEntity(requestEntity -> {
    
      // prepare what to add as suffix to the incoming entity stream:
      Source<ByteString, NotUsed> suffixSource = 
        Source.single(ByteString.fromString("\n\nADDS THIS AFTER INCOMING ENTITY"))
    
      // concat the suffix stream to the incoming entity stream
      Source<ByteString, Object> replySource = requestEntity.getDataBytes()
        .concat(suffixSource);
    
        // prepare and return the entity:
        HttpEntity.Chunked replyEntity = HttpEntities.create(ContentTypes.TEXT_PLAIN_UTF8, replySource);
        return complete(StatusCodes.OK, replyEntity);
      })
    );
    

    Having that said, there is numerous ways to make use of the streaming capabilities, including framed JSON Streaming and more. You should also give the docs page about implications of streaming a read.