Search code examples
azureazure-blob-storageazure-synapse

Use a Linked Service for configuring a BlobServiceClient


I have been successfully using BlobServiceClient.from_connection_string() to obtain an instance of BlobServiceClient. Our infrastructure also needs to be able to connect via a linked service. I did not see that capacity in the BlobServiceClient API . How can that be done?

Linked services: Microsoft Learn for Linked Services


Solution

  • To get the connection from synapse linked service, use the below code in your synapse notebook.

    # Get the connection string
    import json
    print(json.loads(mssparkutils.credentials.getPropertiesAll("Blob_LS"))['AuthKey'])
    
    #Create instance from 
    from azure.storage.blob import BlobServiceClient
    service = BlobServiceClient(account_url="https://<storage_account_name>.blob.core.windows.net", credential=json.loads(mssparkutils.credentials.getPropertiesAll("<linked_service_name>"))['AuthKey'])
    print("Instance created")
    
    
    containers = service.list_containers(include_metadata=True)
    for i in containers:
        print(i['name'])
    

    Output:

    enter image description here

    You can also get the connection string in normal python using the below REST API.

    GET {endpoint}/linkedservices/{linkedServiceName}?api-version=2020-12-01
    

    Use the above REST API in python get request and get the required connection string from the JSON response. Check the documentation example for more information about it.