Integrate Azure Functions with Astra DB Serverless

Azure Functions is Microsoft Azure’s function-as-a-service offering that provides a serverless execution environment for your code. You can use Azure Functions for actions such as the following:

  • Extend Astra DB Serverless with additional data processing capabilities, such as aggregating, summarizing, and validating data periodically.

  • Connect Astra DB Serverless with other cloud services into data pipelines that move, process, and analyze data.

Prerequisites

Create a local Azure Functions project

Create a local project, based on the Azure Functions Python quickstart, to develop and test your Azure Functions before you deploy them to the cloud.

  1. Install the Azure CLI.

  2. Install the Azure functions core tools package version 4.0 or later.

  3. Create and activate a new Python virtual environment:

    python -m venv .venv
    source .venv/bin/activate
  4. Initialize a new Azure Functions project with the Python runtime:

    func init --python

    This command initializes a project directory with a function_app.py file, a requirements.txt file, and other necessary Python files.

  5. Use func new to add a function to your project:

    func new --name HttpExample --template "HTTP trigger" --authlevel "ANONYMOUS"

    The --name argument is the unique name of your function, and the --template argument specifies the function’s trigger.

    In this example, func new adds an HTTP trigger endpoint named HttpExample to the function_app.py file, which is accessible without authentication. For more information, see the Azure functionapp CLI reference.

  6. Replace the contents of function_app.py with the following code:

    import azure.functions as func
    import datetime
    import json
    import logging
    
    app = func.FunctionApp()
    
    @app.route(route="HttpExample", auth_level=func.AuthLevel.ANONYMOUS)
    def HttpExample(req: func.HttpRequest) -> func.HttpResponse:
        logging.info('Python HTTP trigger function processed a request.')
    
        name = req.params.get('name')
        if not name:
            try:
                req_body = req.get_json()
            except ValueError:
                pass
            else:
                name = req_body.get('name')
    
        if name:
            return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
        else:
            return func.HttpResponse(
                 "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
                 status_code=200
            )
  7. Run the function locally:

    func start

    From the output, use the HttpExample invoke URL to trigger the function. The expected output is the contents of func.HttpResponse from the function_app.py script.

    Azure Functions Core Tools
    Core Tools Version:       4.0.5907 Commit hash: N/A +807e89766a92b14fd07b9f0bc2bea1d8777ab209 (64-bit)
    Function Runtime Version: 4.834.3.22875
    
    [2024-07-25T14:48:34.922Z] Worker process started and initialized.
    
    Functions:
    
            HttpExample:  http://localhost:7071/api/HttpExample

    If you get a No job functions found error, open your project’s local.settings.json file, and then make sure UseDevelopmentStorage is set to true:

    {
      "IsEncrypted": false,
      "Values": {
        "FUNCTIONS_WORKER_RUNTIME": "python",
        "AzureWebJobsFeatureFlags": "EnableWorkerIndexing",
        "AzureWebJobsStorage": "UseDevelopmentStorage=true"
      }
    }

Deploy the function to the cloud

  1. Sign into your Azure account:

    az login
  2. Create a resource group, specifying the group name and region code.

    For this example, the group is named AzureFunctionsQuickstart and the location is eastus2:

    az group create --name AzureFunctionsQuickstart --location eastus2

    To get region codes, run the az account list-locations command. In the next steps, you will deploy the function to the same region.

  3. Create a general-purpose storage account (--sku Standard_LRS) using the resource group and region from the previous step.

    For this example, the storage account is named astraquickstartstorage:

    az storage account create --name astraquickstartstorage --location eastus2 --resource-group AzureFunctionsQuickstart --sku Standard_LRS

    For more information, see Storage considerations for Azure Functions.

  4. Create the function app in Azure with az functionapp create and the resource group, region, and storage account from the previous steps:

    az functionapp create --resource-group AzureFunctionsQuickstart --consumption-plan-location eastus2 --runtime python --runtime-version 3.10 --functions-version 4 --name uniqueapplication --os-type linux --storage-account astraquickstartstorage

    For this example, --os-type linux is required because Python functions only run on Linux.

  5. Publish the application in Azure to make it publicly available and get the application’s endpoint:

    func azure functionapp publish uniqueapplication
  6. To test the deployed application, send a request to the application’s endpoint:

    curl "https://uniqueapplication.azurewebsites.net/api/HttpExample?name=datastax"

    The output uses the value of the name query parameter:

    Hello, datastax. This HTTP triggered function executed successfully.

    You can also view, test, and debug the function in the Azure portal.

Create the Azure function with the Cassandra Python driver

Now that you have a working template application, locally modify the application to connect to Astra DB with the Cassandra Python driver, and the republish the application:

  1. Set the following environment variables:

    export APP_NAME =                  # Function app name
    export RESOURCE_GROUP_NAME =       # Azure resource group name
    export ASTRA_DB_CLIENT_ID = token  # The literal string 'token'
    export ASTRA_DB_CLIENT_SECRET =    # Astra application token (AstraCS:...)
  2. Use the Azure CLI or Azure Portal to add ASTRA_DB_CLIENT_ID and ASTRA_DB_CLIENT_SECRET to the application settings:

    az functionapp config appsettings set \
      --name ${APP_NAME} \
      --resource-group ${RESOURCE_GROUP_NAME} \
      --settings "ASTRA_DB_CLIENT_ID=${ASTRA_DB_CLIENT_ID}"
    
    az functionapp config appsettings set \
      --name ${APP_NAME} \
      --resource-group ${RESOURCE_GROUP_NAME} \
      --settings "ASTRA_DB_CLIENT_SECRET=${ASTRA_DB_CLIENT_SECRET}"
  3. In your Python project, add the Python driver (cassandra-driver) to the requirements.txt file:

    echo "cassandra-driver" | cat >> requirements.txt
    cat requirements.txt
  4. Replace the function_app.py content with the following code, and then replace secure-connect-bundle-for-your-database.zip with the file name for your database’s SCB.

    For this example, the SCB is stored at the root of the Python project directory. In production, treat the SCB as a secret. For example, use an Azure Key Vault reference in your app settings.

    This function connects to your database using the Python driver and retrieves the supported CQL version from the system.local table. The output is formatted as VERSION Success, such as 3.4.5 Success.

    import azure.functions as func
    from azure.functions import AuthLevel
    import datetime
    import json
    import logging
    import os
    from cassandra.cluster import Cluster
    from cassandra.auth import PlainTextAuthProvider
    
    ASTRA_DB_CLIENT_ID = os.environ.get('ASTRA_DB_CLIENT_ID')
    ASTRA_DB_CLIENT_SECRET = os.environ.get('ASTRA_DB_CLIENT_SECRET')
    
    if not ASTRA_DB_CLIENT_ID or not ASTRA_DB_CLIENT_SECRET:
        raise ValueError("Environment variables ASTRA_DB_CLIENT_ID and ASTRA_DB_CLIENT_SECRET must be set")
    
    cloud_config = {
        'secure_connect_bundle': 'secure-connect-bundle-for-your-database.zip',
        'use_default_tempdir': True
    }
    auth_provider = PlainTextAuthProvider(ASTRA_DB_CLIENT_ID, ASTRA_DB_CLIENT_SECRET)
    cluster = Cluster(
        cloud=cloud_config,
        auth_provider=auth_provider,
        protocol_version=4
    )
    
    app = func.FunctionApp()
    
    @app.route(route="HttpExample", auth_level=func.AuthLevel.ANONYMOUS)
    def HttpExample(req: func.HttpRequest) -> func.HttpResponse:
        session = cluster.connect()
        session.default_timeout = 60
        row = session.execute("SELECT cql_version FROM system.local WHERE key = 'local';").one()
        cql_version = row[0]
        logging.info(f"{cql_version} Success")
        return func.HttpResponse(f"{cql_version} Success")
  5. Test the function locally:

    1. Start the Azure Functions runtime:

      func start
    2. Use the returned HttpExample invoke URL to trigger the function:

      Azure Functions Core Tools
      Core Tools Version:       4.0.5907 Commit hash: N/A +807e89766a92b14fd07b9f0bc2bea1d8777ab209 (64-bit)
      Function Runtime Version: 4.834.3.22875
      
      [2024-07-25T14:48:34.922Z] Worker process started and initialized.
      
      Functions:
      
              HttpExample:  http://localhost:7071/api/HttpExample

      For this example, a successful response is VERSION Success, such as 3.4.5 Success.

  6. Deploy the updated function to Azure:

    func azure functionapp publish uniqueapplication

    A successful build returns Remote build succeeded and an invoke URL for your application.

  7. To test your application, send a GET request to your application’s invoke URL:

    curl "https://uniqueapplication.azurewebsites.net/api/HttpExample"

    This Azure function integrates with Astra DB Serverless through the Cassandra Python driver. Try extending or modifying the function to run queries against your database. For more information, see the Python driver documentation.

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | Privacy policy | Terms of use |  Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: Contact IBM