Get URL for container or blob with TypeScript

You can get a container or blob URL by using the url property of the client object:

  • ContainerClient.url
  • BlobClient.url
  • BlockBlobClient.url

Note

The examples in this article assume that you've created a BlobServiceClient object by using the guidance in the Get started with Azure Blob Storage and TypeScript article.

Get URL for container and blob

The following example gets a container URL and a blob URL by accessing the client's url property:

async function getUrls(blobServiceClient: BlobServiceClient): Promise<void> {
  // create container
  const containerName = `con1-${Date.now()}`;
  const {
    containerClient,
    containerCreateResponse
  }: {
    containerClient: ContainerClient;
    containerCreateResponse: ContainerCreateResponse;
  } = await blobServiceClient.createContainer(containerName, {
    access: 'container'
  });

  if (containerCreateResponse.errorCode)
    throw Error(containerCreateResponse.errorCode);

  // Display container name and its URL
  console.log(
    `created container:\n\tname=${containerClient.containerName}\n\turl=${containerClient.url}`
  );

  // create blob from string
  const blobName = `${containerName}-from-string.txt`;
  const blobContent = `Hello from a string`;
  const blockBlobClient = await containerClient.getBlockBlobClient(blobName);
  const blockBlobUploadResponse: BlockBlobUploadResponse =
    await blockBlobClient.upload(blobContent, blobContent.length);

  if (blockBlobUploadResponse.errorCode)
    throw Error(blockBlobUploadResponse.errorCode);

  // Display Blob name and its URL
  console.log(
    `created blob:\n\tname=${blobName}\n\turl=${blockBlobClient.url}`
  );

  // In loops, blob is BlobItem
  // Use BlobItem.name to get BlobClient or BlockBlobClient
  // The get `url` property
  for await (const blob of containerClient.listBlobsFlat({
    includeMetadata: true,
    includeSnapshots: false,
    includeTags: true,
    includeVersions: false,
    prefix: ''
  })) {
    // blob
    console.log('\t', blob.name);

    // Get Blob Client from name, to get the URL
    const tempBlockBlobClient: BlockBlobClient =
      containerClient.getBlockBlobClient(blob.name);

    // Display blob name and URL
    console.log(`\t${blob.name}:\n\t\t${tempBlockBlobClient.url}`);
  }
}

Tip

For loops, you must use the object's name property to create a client then get the URL with the client. Iterators don't return client objects, they return item objects.

Code samples

View code samples from this article (GitHub):

See also