Azure

Create the API Function in Azure Functions using Python code
Azure
Azure Functions is a serverless compute service that lets you run event-triggered code without having to provision or manage infrastructure. In this case, we want to use an HTTP trigger which allows our function to be called from a web app. In order to connect Azure Functions with Cosmos DB, we need to use Azure SDK for Python.

Prerequisites

You’ll need the following tools and resources installed on your workstation:

  • Microsoft Visual Studio Code
  • Azure Functions Core Tools
  • Python
  • Azure CLI
  • Azure SDK for Python.

Step 1: Create an Azure Function

Create an HTTP Trigger Azure Function.

  1. Open a terminal and create a new folder for your function app. Navigate to it:

    mkdir my-function-app
    cd my-function-app
    
  2. Run the following command to create a new function:

    func init --worker-runtime python
    
  3. To create an HTTP Trigger function, use the following command:

    func new --template "HTTP trigger" --name UpdateVisitorCount
    

This will create a new function called UpdateVisitorCount with an HTTP trigger. The code for the function will be in a file named __init__.py.

Step 2: Add Azure SDK for Python to your project

Azure SDK for Python will allow us to interact with Cosmos DB from our Azure Function.

  1. Locate a file in your function app directory named requirements.txt.

  2. Add the following line to requirements.txt:

    azure-cosmos==4.2.0
    

The Azure Functions Core Tools will automatically install packages listed in requirements.txt when you run your function.

Step 3: Update your function code

Now you can update __init__.py with code to connect to Cosmos DB and update the visitor count.

  1. Open __init__.py.
  2. Replace the existing code with the following:
import logging
import os
from azure.cosmos import CosmosClient, PartitionKey
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    cosmos_db_endpoint = os.getenv('COSMOS_DB_ENDPOINT')
    cosmos_db_key = os.getenv('COSMOS_DB_KEY')
    database_name = 'VisitorCounter'
    container_name = 'count'

    client = CosmosClient(cosmos_db_endpoint, cosmos_db_key)
    database = client.get_database_client(database_name)
    container = database.get_container_client(container_name)

    # assuming your items have a 'visits' field
    for item in container.query_items(
            query='SELECT * FROM c WHERE c.id = "visitorCount"',
            enable_cross_partition_query=True):
        item['visits'] += 1
        container.upsert_item(item)

    return func.HttpResponse("Visitor count updated.", status_code=200)

Step 4: Set Cosmos DB connection information

You will need to store your Cosmos DB connection information as environment variables in your function app settings.

  1. Open the Azure portal and navigate to your function app.
  2. Select Configuration under the Settings section.
  3. Add new application settings for your Cosmos DB endpoint and key, with the names COSMOS_DB_ENDPOINT and COSMOS_DB_KEY, respectively.

Step 5: Run and test your function

You can now run your function with the func start command from the function app directory.

The HTTP endpoint for your function will be displayed in the command line once the function is running. You can use this endpoint to trigger your function from your web app. Each time the function is triggered, it will increment the visitor count in your Cosmos DB.

Please let me know if you need help with any of the steps.

Last modified July 21, 2024: update (e2ae86c)