AWS Elixir SDK Example
The following example shows how AWS Elixir SDK can be used to interact with Telnyx Cloud Storage. This example requires the following dependencies be added to your mix.exs file
{:aws, "~> 1.0.0"},
{:hackney, "~> 1.18"}
telnyx_storage_client =
AWS.Client.create(
System.fetch_env!("TELNYX_V2_API_KEY"),
# secret access key can be left blank for Telnyx Storage
"",
System.get_env("TELNYX_STORAGE_REGION", "us-east-1")
)
|> AWS.Client.put_endpoint(fn options -> "#{options.region}.telnyxstorage.com" end)
# create a bucket
bucket_name = System.get_env("TELNYX_STORAGE_BUCKET_NAME", "my-test-bucket-#{Enum.random(1..1_000_000)}")
{:ok, _, _} = AWS.S3.create_bucket(telnyx_storage_client, bucket_name, %{})
# write a couple of objects to the bucket
for i <- 1..2 do
object_key = "object-#{i}.bin"
# create a blob of random bytes
upload_request = %{
"Body" => :rand.bytes(42),
"ContentType" => "application/octet-stream"
}
{:ok, _, _} = AWS.S3.put_object(telnyx_storage_client, bucket_name, object_key, upload_request)
end
# list contents of a bucket
{:ok, %{"ListBucketResult" => bucket_details}, _} = AWS.S3.list_objects(telnyx_storage_client, bucket_name)
# print the object keys
Enum.each(bucket_details["Contents"], fn content ->
IO.puts("Object key: #{content["Key"]}")
end)
# download the first object
object_key = List.first(bucket_details["Contents"])["Key"]
{:ok, %{"Body" => object_data}, _} = AWS.S3.get_object(telnyx_storage_client, bucket_name, object_key)
IO.puts("Downloaded object data: #{inspect(object_data)}")
For generating presigned URLs, the below example requires the following additional libraries added to your mix.exs file
{:req, "~> 0.5"},
{:jason, "~> 1.4"}
url = "https://api.telnyx.com/v2/storage/buckets/#{bucket_name}/#{object_key}/presigned_url"
api_key = System.fetch_env!("TELNYX_V2_API_KEY")
headers = %{
"authorization" => "Bearer #{api_key}",
"content_type" => "application/json",
"accept" => "application/json"
}
body = %{
"ttl" => 30
}
{:ok, %{body: %{"data" => %{"presigned_url" => presigned_url}}}} = Req.post(url, headers: headers, json: body)
# download the object using the presigned url
{:ok, %{body: object_data}} = Req.get(presigned_url)
IO.puts("Downloaded object data using presigned URL: #{inspect(object_data)}")