Skip to content

Instantly share code, notes, and snippets.

@kubukoz
Last active April 18, 2021 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kubukoz/c9c7d990c4f07447b68dcdb8cb09b9a3 to your computer and use it in GitHub Desktop.
Save kubukoz/c9c7d990c4f07447b68dcdb8cb09b9a3 to your computer and use it in GitHub Desktop.
Download file from dropbox with http4s
import cats.effect.IO
import cats.effect.IOApp
import io.circe.Printer
import io.circe.literal._
import org.http4s.AuthScheme
import org.http4s.Credentials
import org.http4s.Header
import org.http4s.Request
import org.http4s.client.blaze.BlazeClientBuilder
import org.http4s.client.dsl.io._
import org.http4s.dsl.io._
import org.http4s.headers.Authorization
import org.http4s.implicits._
import org.typelevel.ci.CIString
//requires:
//circe-literal 0.14.0-M5
//http4s 1.0.0-M21: blaze-client, dsl, circe
object JsonHeaderDropbox extends IOApp.Simple {
def downloadFile(filePath: String): Request[IO] =
POST(uri"https://content.dropboxapi.com/2/files/download")
.putHeaders(
Header.Raw(
name = CIString("Dropbox-API-Arg"),
// the important part - if you have non-ascii chars in your paths (e.g. you're a normal Polish person),
// you need to escape them, thankfully circe makes it relatively easy
value = json"""{"path": $filePath }""".printWith(Printer.noSpaces.copy(escapeNonAscii = true)),
),
Authorization(
Credentials.Token(
AuthScheme.Bearer,
//use ciris instead of reading env variables like this please
System.getenv("DROPBOX_TOKEN"),
)
),
)
def run: IO[Unit] =
BlazeClientBuilder[IO](runtime.compute)
.stream
.flatMap(_.stream(downloadFile("/foo.txt")))
.flatMap(_.bodyText)
.debug()
.compile
.drain
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment