---
id: streaming
title: "Streaming Examples"
sidebar_label: "Streaming"
---

## Streaming Request

```scala title="zio-http-example/src/main/scala/example/RequestStreaming.scala" 
package example

import zio._

import zio.http._

object RequestStreaming extends ZIOAppDefault {

  // Create HTTP route which echos back the request body
  val app = Routes(Method.POST / "echo" -> handler { (req: Request) =>
    // Returns a stream of bytes from the request
    // The stream supports back-pressure
    val stream = req.body.asStream

    // Creating HttpData from the stream
    // This works for file of any size
    val data = Body.fromStreamChunked(stream)

    Response(body = data)
  })

  // Run it like any simple app
  val run: UIO[ExitCode] =
    Server.serve(app).provide(Server.default).exitCode
}
```

## Streaming Response

```scala title="zio-http-example/src/main/scala/example/StreamingResponse.scala" 
package example

import zio.{http, _}

import zio.stream.ZStream

import zio.http._

/**
 * Example to encode content using a ZStream
 */
object StreamingResponse extends ZIOAppDefault {
  // Starting the server (for more advanced startup configuration checkout `HelloWorldAdvanced`)
  def run = Server.serve(routes).provide(Server.default)

  // Create a message as a Chunk[Byte]
  def message = Chunk.fromArray("Hello world !\r\n".getBytes(Charsets.Http))

  def routes: Routes[Any, Response] = Routes(
    // Simple (non-stream) based route
    Method.GET / "health" -> handler(Response.ok),

    // ZStream powered response
    Method.GET / "stream" ->
      handler(
        http.Response(
          status = Status.Ok,
          body = Body.fromStream(ZStream.fromChunk(message), message.length.toLong), // Encoding content using a ZStream
        ),
      ),
  )
}
```

## Streaming File

```scala title="zio-http-example/src/main/scala/example/FileStreaming.scala" 
package example

import java.io.File
import java.nio.file.Paths

import zio._

import zio.stream.ZStream

import zio.http._

object FileStreaming extends ZIOAppDefault {

  // Create HTTP route
  val app = Routes(
    Method.GET / "health" -> Handler.ok,

    // Read the file as ZStream
    // Uses the blocking version of ZStream.fromFile
    Method.GET / "blocking" -> Handler.fromStreamChunked(ZStream.fromPath(Paths.get("README.md"))),

    // Uses netty's capability to write file content to the Channel
    // Content-type response headers are automatically identified and added
    // Adds content-length header and does not use Chunked transfer encoding
    Method.GET / "video" -> Handler.fromFile(new File("src/main/resources/TestVideoFile.mp4")),
    Method.GET / "text"  -> Handler.fromFile(new File("src/main/resources/TestFile.txt")),
  ).sandbox

  // Run it like any simple app
  val run =
    Server.serve(app).provide(Server.default)
}
```
