0
0
Azurecloud~30 mins

Functions with Cosmos DB integration in Azure - Mini Project: Build & Apply

Choose your learning style9 modes available
Functions with Cosmos DB integration
📖 Scenario: You are building a simple Azure Function that interacts with Cosmos DB to store and retrieve user data. This is a common pattern in cloud applications where serverless functions handle data operations.
🎯 Goal: Create an Azure Function that connects to a Cosmos DB container, inserts a user document, and queries users by a specific property.
📋 What You'll Learn
Create a Cosmos DB client connection string variable
Define a function to insert a user document into Cosmos DB
Define a function to query users by their city
Configure the Azure Function to use the Cosmos DB client
💡 Why This Matters
🌍 Real World
Serverless functions often need to store and retrieve data from databases like Cosmos DB. This project shows how to connect and perform basic operations.
💼 Career
Understanding how to integrate Azure Functions with Cosmos DB is a key skill for cloud developers working on scalable, event-driven applications.
Progress0 / 4 steps
1
Create Cosmos DB connection string variable
Create a variable called cosmos_connection_string and set it to the exact string "AccountEndpoint=https://mycosmos.documents.azure.com:443/;AccountKey=ABC123==;".
Azure
Need a hint?

Use a simple string assignment to create the connection string variable.

2
Create Cosmos DB client variable
Using the cosmos_connection_string variable, create a Cosmos DB client variable called client by calling CosmosClient(cosmos_connection_string). Assume CosmosClient is already imported.
Azure
Need a hint?

Instantiate the CosmosClient using the connection string variable with from_connection_string method.

3
Define function to insert a user document
Define a function called insert_user that takes parameters database_name, container_name, and user_data. Inside the function, get the container from client using client.get_database_client(database_name).get_container_client(container_name). Then call container.create_item(user_data) to insert the document.
Azure
Need a hint?

Define the function with the exact name and parameters. Use the client to get the container and call create_item.

4
Define function to query users by city
Define a function called query_users_by_city that takes parameters database_name, container_name, and city. Inside the function, get the container from client as before. Then create a SQL query string "SELECT * FROM c WHERE c.city = @city". Use container.query_items with the query and parameters [{"name": "@city", "value": city}], and set enable_cross_partition_query=True. Return the list of results.
Azure
Need a hint?

Define the function with the exact name and parameters. Use a parameterized SQL query and return the results as a list.