Interacting With Objects
All methods described here support additional optional headers that can be included in the request. Please refer to the S3 Documentation for more information on what headers can be applied to different methods.
To list all objects in a bucket, we can use the listObjectsV2
method. This makes use of the V2 version of the action in S3.
//Print an objects name (key) and ETag.
def printObject(s3Object: S3Object): IO[Unit] = IO {
println(s"S3Object Name: ${s3Object.key}, S3Object ETag: ${s3Object.eTag}")
}
s3.listObjectsV2("hello-world-bucket-example").flatMap { response =>
response.contents.traverse(printObject _)
}
// res0: IO[Vector[Unit]] = IO$2298746
To upload a file into a bucket as an object, use the putObject
method. This method requires an EntityEncoder[F, T]
for what you intend to upload.
import org.http4s.EntityEncoder
implicit val encoder: EntityEncoder[IO, String] = EntityEncoder.stringEncoder
// encoder: EntityEncoder[IO, String] = org.http4s.EntityEncoder$$anon$3@71111609
val body = "testing-file-body"
// body: String = testing-file-body
s3.putObject("hello-world-bucket-example", "example-file.txt", body)
// res1: IO[UploadFileResponse] = IO$12901229
To download an object from a bucket, use the getObject
method. In order to decode the contents of the file, an EntityDecoder[F, T]
must be provided.
import org.http4s.EntityDecoder
implicit val decoder: EntityDecoder[IO, String] = EntityDecoder.text
// decoder: EntityDecoder[IO, String] = org.http4s.EntityDecoder$$anon$7@7f57e55f
//Download the object then print it's decoded contents.
s3.getObject("hello-world-bucket-example", "example-file.txt").flatMap { response =>
IO { println(response.body) }
}
// res2: IO[Unit] = IO$1735889164
An object can be deleted using the deleteObject
method.
s3.deleteObject("hello-world-bucket-example", "example-file.txt")
// res3: IO[org.http4s.Headers] = IO$514814645
An object can be copied using copyObject
.
s3.copyObject("hello-world-bucket-example", "new-example-file.txt","example-file.txt")
// res4: IO[CopyObjectResponse] = IO$949407166
To obtain the metadata of an object in the form of headers, headObject
can be used.
//Print the object's ETag
s3.headObject("hello-world-bucket-example", "example-file.txt").flatMap { response =>
IO { println(response.eTag) }
}
// res5: IO[Unit] = IO$2016131822