Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

Connect Azure Functions to Azure Cosmos DB using Visual Studio Code

  • 2024-04-26
Feedback

In this article

Azure Functions lets you connect Azure services and other resources to functions without having to write your own integration code. Thesebindings, which represent both input and output, are declared within the function definition. Data from bindings is provided to the function as parameters. Atrigger is a special type of input binding. Although a function has only one trigger, it can have multiple input and output bindings. To learn more, seeAzure Functions triggers and bindings concepts.

This article shows you how to use Visual Studio Code to connectAzure Cosmos DB to the function you created in the previous quickstart article. The output binding that you add to this function writes data from the HTTP request to a JSON document stored in an Azure Cosmos DB container.

Before you begin, you must complete thequickstart: Create a C# function in Azure using Visual Studio Code. If you already cleaned up resources at the end of that article, go through the steps again to recreate the function app and related resources in Azure.

Before you begin, you must complete thequickstart: Create a JavaScript function in Azure using Visual Studio Code. If you already cleaned up resources at the end of that article, go through the steps again to recreate the function app and related resources in Azure.

Note

This article currently only supportsNode.js v3 for Functions.

Before you begin, you must complete thequickstart: Create a Python function in Azure using Visual Studio Code. If you already cleaned up resources at the end of that article, go through the steps again to recreate the function app and related resources in Azure.

Configure your environment

Before you get started, make sure to install theAzure Databases extension for Visual Studio Code.

Create your Azure Cosmos DB account

Now, you create an Azure Cosmos DB account as aserverless account type. This consumption-based mode makes Azure Cosmos DB a strong option for serverless workloads.

  1. In Visual Studio Code, selectView >Command Palette... then in the command palette search forAzure Databases: Create Server...

  2. Provide the following information at the prompts:

    PromptSelection
    Select an Azure Database ServerChooseCore (NoSQL) to create a document database that you can query by using a SQL syntax or a Query Copilot (Preview) converting natural language prompts to queries.Learn more about the Azure Cosmos DB.
    Account nameEnter a unique name to identify your Azure Cosmos DB account. The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
    Select a capacity modelSelectServerless to create an account inserverless mode.
    Select a resource group for new resourcesChoose the resource group where you created your function app in theprevious article.
    Select a location for new resourcesSelect a geographic location to host your Azure Cosmos DB account. Use the location that's closest to you or your users to get the fastest access to your data.

    After your new account is provisioned, a message is displayed in notification area.

Create an Azure Cosmos DB database and container

  1. Select the Azure icon in the Activity bar, expandResources >Azure Cosmos DB, right-click (Ctrl+select on macOS) your account, and selectCreate database....

  2. Provide the following information at the prompts:

    PromptSelection
    Database nameTypemy-database.
    Enter and ID for your collectionTypemy-container.
    Enter the partition key for the collectionType/id as thepartition key.
  3. SelectOK to create the container and database.

Update your function app settings

In theprevious quickstart article, you created a function app in Azure. In this article, you update your app to write JSON documents to the Azure Cosmos DB container you've created. To connect to your Azure Cosmos DB account, you must add its connection string to your app settings. You then download the new setting to your local.settings.json file so you can connect to your Azure Cosmos DB account when running locally.

  1. In Visual Studio Code, right-click (Ctrl+select on macOS) on your new Azure Cosmos DB account, and selectCopy Connection String.

    Copying the Azure Cosmos DB connection string

  2. PressF1 to open the command palette, then search for and run the commandAzure Functions: Add New Setting....

  3. Choose the function app you created in the previous article. Provide the following information at the prompts:

    PromptSelection
    Enter new app setting nameTypeCosmosDbConnectionString.
    Enter value for "CosmosDbConnectionString"Paste the connection string of your Azure Cosmos DB account you copied. You can also configureMicrosoft Entra identity as an alternative.

    This creates an application setting named connectionCosmosDbConnectionString in your function app in Azure. Now, you can download this setting to your local.settings.json file.

  4. PressF1 again to open the command palette, then search for and run the commandAzure Functions: Download Remote Settings....

  5. Choose the function app you created in the previous article. SelectYes to all to overwrite the existing local settings.

This downloads all of the setting from Azure to your local project, including the new connection string setting. Most of the downloaded settings aren't used when running locally.

Register binding extensions

Because you're using an Azure Cosmos DB output binding, you must have the corresponding bindings extension installed before you run the project.

Except for HTTP and timer triggers, bindings are implemented as extension packages. Run the followingdotnet add package command in the Terminal window to add the Azure Cosmos DB extension package to your project.

dotnet add package Microsoft.Azure.Functions.Worker.Extensions.CosmosDB

Your project has been configured to useextension bundles, which automatically installs a predefined set of extension packages.

Extension bundles usage is enabled in thehost.json file at the root of the project, which appears as follows:

{  "version": "2.0",  "logging": {    "applicationInsights": {      "samplingSettings": {        "isEnabled": true,        "excludedTypes": "Request"      }    }  },  "extensionBundle": {    "id": "Microsoft.Azure.Functions.ExtensionBundle",    "version": "[4.*, 5.0.0)"  },  "concurrency": {    "dynamicConcurrencyEnabled": true,    "snapshotPersistenceEnabled": true  },  "extensions": {    "cosmosDB": {      "connectionMode": "Gateway"    }  }}

Your project has been configured to useextension bundles, which automatically installs a predefined set of extension packages.

Extension bundles usage is enabled in thehost.json file at the root of the project, which appears as follows:

{  "version": "2.0",  "extensionBundle": {    "id": "Microsoft.Azure.Functions.ExtensionBundle",    "version": "[3.*, 4.0.0)"  } }

Now, you can add the Azure Cosmos DB output binding to your project.

Add an output binding

In a C# class library project, the bindings are defined as binding attributes on the function method.

Open theHttpExample.cs project file and add the following classes:

public class MultiResponse{    [CosmosDBOutput("my-database", "my-container",        Connection = "CosmosDbConnectionSetting", CreateIfNotExists = true)]    public MyDocument Document { get; set; }    public HttpResponseData HttpResponse { get; set; }}public class MyDocument {    public string id { get; set; }    public string message { get; set; }}

TheMyDocument class defines an object that gets written to the database. The connection string for the Storage account is set by theConnection property. In this case, you could omitConnection because you're already using the default storage account.

TheMultiResponse class allows you to both write to the specified collection in the Azure Cosmos DB and return an HTTP success message. Because you need to return aMultiResponse object, you need to also update the method signature.

Specific attributes specify the name of the container and the name of its parent database. The connection string for your Azure Cosmos DB account is set by theCosmosDbConnectionString.

Binding attributes are defined directly in your function code. TheAzure Cosmos DB output configuration describes the fields required for an Azure Cosmos DB output binding.

For thisMultiResponse scenario, you need to add anextraOutputs output binding to the function.

app.http('HttpExample', {  methods: ['GET', 'POST'],  extraOutputs: [sendToCosmosDb],  handler: async (request, context) => {

Add the following properties to the binding configuration:

const sendToCosmosDb = output.cosmosDB({  databaseName: 'my-database',  containerName: 'my-container',  createIfNotExists: false,  connection: 'CosmosDBConnectionString',});

Binding attributes are defined directly in thefunction_app.py file. You use thecosmos_db_output decorator to add anAzure Cosmos DB output binding:

@app.cosmos_db_output(arg_name="outputDocument", database_name="my-database",     container_name="my-container", connection="CosmosDbConnectionString")

In this code,arg_name identifies the binding parameter referenced in your code,database_name andcontainer_name are the database and collection names that the binding writes to, andconnection is the name of an application setting that contains the connection string for the Azure Cosmos DB account, which is in theCosmosDbConnectionString setting in thelocal.settings.json file.

Add code that uses the output binding

Replace the existing Run method with the following code:

[Function("HttpExample")]public static MultiResponse Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,    FunctionContext executionContext){    var logger = executionContext.GetLogger("HttpExample");    logger.LogInformation("C# HTTP trigger function processed a request.");    var message = "Welcome to Azure Functions!";    var response = req.CreateResponse(HttpStatusCode.OK);    response.Headers.Add("Content-Type", "text/plain; charset=utf-8");    response.WriteString(message);    // Return a response to both HTTP trigger and Azure Cosmos DB output binding.    return new MultiResponse()    {         Document = new MyDocument        {            id = System.Guid.NewGuid().ToString(),            message = message        },        HttpResponse = response    };}

Add code that uses theextraInputs output binding object oncontext to send a JSON document to the named output binding function,sendToCosmosDb. Add this code before thereturn statement.

context.extraOutputs.set(sendToCosmosDb, {  // create a random ID  id:    new Date().toISOString() + Math.random().toString().substring(2, 10),  name: name,});

At this point, your function should look as follows:

const { app, output } = require('@azure/functions');const sendToCosmosDb = output.cosmosDB({  databaseName: 'my-database',  containerName: 'my-container',  createIfNotExists: false,  connection: 'CosmosDBConnectionString',});app.http('HttpExampleToCosmosDB', {  methods: ['GET', 'POST'],  extraOutputs: [sendToCosmosDb],  handler: async (request, context) => {    try {      context.log(`Http function processed request for url "${request.url}"`);      const name = request.query.get('name') || (await request.text());      if (!name) {        return { status: 404, body: 'Missing required data' };      }      // Output to Database      context.extraOutputs.set(sendToCosmosDb, {        // create a random ID        id:          new Date().toISOString() + Math.random().toString().substring(2, 10),        name: name,      });      const responseMessage = name        ? 'Hello, ' +          name +          '. This HTTP triggered function executed successfully.'        : 'This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.';      // Return to HTTP client      return { body: responseMessage };    } catch (error) {      context.log(`Error: ${error}`);      return { status: 500, body: 'Internal Server Error' };    }  },});

This code now returns aMultiResponse object that contains both a document and an HTTP response.

UpdateHttpExample\function_app.py to match the following code. Add theoutputDocument parameter to the function definition andoutputDocument.set() under theif name: statement:

import azure.functions as funcimport loggingapp = func.FunctionApp()@app.function_name(name="HttpTrigger1")@app.route(route="hello", auth_level=func.AuthLevel.ANONYMOUS)@app.queue_output(arg_name="msg", queue_name="outqueue", connection="AzureWebJobsStorage")@app.cosmos_db_output(arg_name="outputDocument", database_name="my-database", container_name="my-container", connection="CosmosDbConnectionSetting")def test_function(req: func.HttpRequest, msg: func.Out[func.QueueMessage],    outputDocument: func.Out[func.Document]) -> func.HttpResponse:     logging.info('Python HTTP trigger function processed a request.')     logging.info('Python Cosmos DB 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:        outputDocument.set(func.Document.from_dict({"id": name}))        msg.set(name)        return func.HttpResponse(f"Hello {name}!")     else:        return func.HttpResponse(                    "Please pass a name on the query string or in the request body",                    status_code=400                )

The document{"id": "name"} is created in the database collection specified in the binding.

Run the function locally

Visual Studio Code integrates withAzure Functions Core tools to let you run this project on your local development computer before you publish to Azure. If you don't already have Core Tools installed locally, you are prompted to install it the first time you run your project.

  1. To call your function, pressF5 to start the function app project. TheTerminal panel displays the output from Core Tools. Your app starts in theTerminal panel. You can see the URL endpoint of your HTTP-triggered function running locally.

    Screenshot of the Local function Visual Studio Code output.

    If you don't already have Core Tools installed, selectInstall to install Core Tools when prompted to do so.
    If you have trouble running on Windows, make sure that the default terminal for Visual Studio Code isn't set toWSL Bash.

  2. With the Core Tools running, go to theAzure: Functions area. UnderFunctions, expandLocal Project >Functions. Right-click (Windows) orCtrl - click (macOS) theHttpExample function and chooseExecute Function Now....

    Screenshot of execute function now from Visual Studio Code.

  3. In theEnter request body, pressEnter to send a request message to your function.

  4. When the function executes locally and returns a response, a notification is raised in Visual Studio Code. Information about the function execution is shown in theTerminal panel.

  5. PressCtrl + C to stop Core Tools and disconnect the debugger.

Run the function locally

  1. As in the previous article, pressF5 to start the function app project and Core Tools.

  2. With Core Tools running, go to theAzure: Functions area. UnderFunctions, expandLocal Project >Functions. Right-click (Ctrl-click on Mac) theHttpExample function and chooseExecute Function Now....

    Execute function now from Visual Studio Code

  3. InEnter request body you see the request message body value of{ "name": "Azure" }. Press Enter to send this request message to your function.

  4. After a response is returned, pressCtrl + C to stop Core Tools.

Verify that a JSON document has been created

  1. On the Azure portal, go back to your Azure Cosmos DB account and selectData Explorer.

  2. Expand your database and container, and selectItems to list the documents created in your container.

  3. Verify that a new JSON document has been created by the output binding.

    Verifying that a new document has been created in the Azure Cosmos DB container

Redeploy and verify the updated app

  1. In Visual Studio Code, press F1 to open the command palette. In the command palette, search for and selectAzure Functions: Deploy to function app....

  2. Choose the function app that you created in the first article. Because you're redeploying your project to the same app, selectDeploy to dismiss the warning about overwriting files.

  3. After deployment completes, you can again use theExecute Function Now... feature to trigger the function in Azure.

  4. Againcheck the documents created in your Azure Cosmos DB container to verify that the output binding again generates a new JSON document.

Clean up resources

In Azure,resources refer to function apps, functions, storage accounts, and so forth. They're grouped intoresource groups, and you can delete everything in a group by deleting the group.

You created resources to complete these quickstarts. You might be billed for these resources, depending on youraccount status andservice pricing. If you don't need the resources anymore, here's how to delete them:

  1. In Visual Studio Code, pressF1 to open the command palette. In the command palette, search for and selectAzure: Open in portal.

  2. Choose your function app and pressEnter. The function app page opens in the Azure portal.

  3. In theOverview tab, select the named link next toResource group.

    Screenshot of select the resource group to delete from the function app page.

  4. On theResource group page, review the list of included resources, and verify that they're the ones you want to delete.

  5. SelectDelete resource group, and follow the instructions.

    Deletion may take a couple of minutes. When it's done, a notification appears for a few seconds. You can also select the bell icon at the top of the page to view the notification.

Next steps

You've updated your HTTP triggered function to write JSON documents to an Azure Cosmos DB container. Now you can learn more about developing Functions using Visual Studio Code:


Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo