Access data with Azure Cosmos DB NoSQL API

This article demonstrates adding the Spring Cloud Azure Starter for Spring Data for Azure Cosmos DB to a custom application to store data in and retrieve data from your Azure Cosmos DB database by using Spring Data and Azure Cosmos DB for NoSQL. The article starts by showing you how to create an Azure Cosmos DB via the Azure portal, then shows you how to use Spring Initializr to create a custom Spring Boot application that you can use with the Spring Boot Starter.

Azure Cosmos DB is a globally distributed database service that allows developers to work with data using various standard APIs, such as SQL, MongoDB, Graph, and Table APIs. Microsoft's Spring Boot Starter enables developers to use Spring Boot applications that easily integrate with Azure Cosmos DB for NoSQL.


Create an Azure Cosmos DB by using the Azure portal

  1. Browse to the Azure portal at and select Create a resource.

  2. Select Databases, and then select Azure Cosmos DB.

    Azure portal screenshot showing 'Create a resource' page with search box highlighted and containing text 'Azure Cosmos DB'.

  3. On the Select API option screen, select Core (SQL).

    Azure portal screenshot showing 'Select API option' page with 'Core S Q L' option highlighted.

  4. On the Azure Cosmos DB page, enter the following information:

    • Choose the Subscription you want to use for your database.
    • Specify whether to create a new Resource group for your database, or choose an existing resource group.
    • Enter a unique Account Name, which you'll use as the URI for your database. For example: contosoaccounttest.
    • Choose Core (SQL) for the API.
    • Specify the Location for your database.

    When you've specified these options, select Review + create, review your specifications, and select Create.

    Azure portal screenshot showing the 'Create Azure Cosmos DB Account - Core S Q L' page.

  5. When your database has been created, it's listed on your Azure Dashboard, and under the All Resources and Azure Cosmos DB pages. To create a database and a container for a newly created Azure Cosmos DB, see the Add a database and a container section of Quickstart: Create an Azure Cosmos DB account, database, container, and items from the Azure portal. You can select your database for any of those locations to open the properties page for your cache.

  6. When the properties page for your database is displayed, select Keys and copy your URI and access keys for your database; you'll use these values in your Spring Boot application.

    Azure portal screenshot of an Azure Cosmos DB account with the Keys page showing.


In your newly created Azure Cosmos DB, assign the Owner role to the Azure account you're currently using. For more information, see Assign Azure roles using the Azure portal, .

Create a Spring Boot application with the Spring Initializr

Use the following steps to create a new Spring Boot application project with Azure support. As an alternative, you can use the spring-cloud-azure-data-cosmos-sample sample in the azure-spring-boot-samples repo. Then, you can skip directly to Build and test your app.

  1. Browse to

  2. Specify the following options:

    • Generate a Maven project with Java.
    • Specify your Spring Boot version to 2.7.9.
    • Specify the Group and Artifact names for your application.
    • Select 17 for the Java version.
    • Add Azure Support in the dependencies.


    1. The Spring Initializr uses the Group and Artifact names to create the package name; for example: com.example.wingtiptoysdata.
    2. The version of Spring Boot may be higher than the version supported by Azure Support. After the project is automatically generated, you can manually change the Spring Boot version to the highest version supported by Azure, which you can find in Spring-Versions-Mapping.
  3. When you've specified the options listed above, select GENERATE.

  4. When prompted, download the project to a path on your local computer and extract the files.

Your simple Spring Boot application is now ready for editing.

Configure your Spring Boot application to use the Azure Spring Boot Starter

  1. Locate the pom.xml file in the directory of your app; for example:




  2. Open the pom.xml file in a text editor, and add the following to the <dependencies> element:



    For more information about how to manage Spring Cloud Azure library versions by using a bill of materials (BOM), see the Getting started section of the Spring Cloud Azure developer guide.

  3. Save and close the pom.xml file.

Configure your Spring Boot application to use your Azure Cosmos DB

  1. Locate the file in the resources directory of your app; for example:




  2. Open the file in a text editor, and add the following lines to the file, and replace the sample values with the appropriate properties for your database:

    # Specify the DNS URI of your Azure Cosmos DB.
    # Specify the name of your database.
  3. Save and close the file.

Add sample code to implement basic database functionality

In this section you create two Java classes for storing user data, and then you modify your main application class to create an instance of the User class and save it to your database.

Define a base class for storing user data

  1. Create a new file named in the same directory as your main application Java file.

  2. Open the file in a text editor, and add the following lines to the file to define a generic user class that stores and retrieve values in your database:

    package com.example.wingtiptoysdata;
    @Container(containerName = "mycollection")
    public class User {
        private String id;
        private String firstName;
        private String lastName;
        private String address;
        public User() {
        public User(String id, String firstName, String lastName, String address) {
   = id;
            this.firstName = firstName;
            this.lastName = lastName;
            this.address = address;
        public String getId() {
            return id;
        public void setId(String id) {
   = id;
        public String getFirstName() {
            return firstName;
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        public String getLastName() {
            return lastName;
        public void setLastName(String lastName) {
            this.lastName = lastName;
        public String getAddress() {
            return address;
        public void setAddress(String address) {
            this.address = address;
        public String toString() {
            return String.format("%s %s, %s", firstName, lastName, address);
  3. Save and close the file.

Define a data repository interface

  1. Create a new file named in the same directory as your main application Java file.

  2. Open the file in a text editor, and add the following lines to the file to define a user repository interface that extends the default ReactiveCosmosRepository interface:

    package com.example.wingtiptoysdata;
    import org.springframework.stereotype.Repository;
    import reactor.core.publisher.Flux;
    public interface UserRepository extends ReactiveCosmosRepository<User, String> {
        Flux<User> findByFirstName(String firstName);

    The ReactiveCosmosRepository interface replaces the DocumentDbRepository interface from the previous version of the starter. The new interface provides synchronous and reactive APIs for basic save, delete, and find operations.

  3. Save and close the file.

Modify the main application class

  1. Locate the main application Java file in the package directory of your application, for example:




  2. Open the main application Java file in a text editor, and add the following lines to the file:

    package com.example.wingtiptoysdata;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.util.Assert;
    import reactor.core.publisher.Flux;
    import reactor.core.publisher.Mono;
    import java.util.Optional;
    public class WingtiptoysdataApplication implements CommandLineRunner {
        private static final Logger LOGGER = LoggerFactory.getLogger(WingtiptoysdataApplication.class);
        private UserRepository repository;
        public static void main(String[] args) {
  , args);
        public void run(String... var1) {
  "Deleted all data in container.");
            final User testUser = new User("testId", "testFirstName", "testLastName", "test address line one");
            // Save the User class to Azure Cosmos DB database.
            final Mono<User> saveUserMono =;
            final Flux<User> firstNameUserFlux = repository.findByFirstName("testFirstName");
            //  Nothing happens until we subscribe to these Monos.
            //  findById won't return the user as user isn't present.
            final Mono<User> findByIdMono = repository.findById(testUser.getId());
            final User findByIdUser = findByIdMono.block();
            Assert.isNull(findByIdUser, "User must be null");
            final User savedUser = saveUserMono.block();
            Assert.state(savedUser != null, "Saved user must not be null");
            Assert.state(savedUser.getFirstName().equals(testUser.getFirstName()), "Saved user first name doesn't match");
            final Optional<User> optionalUserResult = repository.findById(testUser.getId()).blockOptional();
            Assert.isTrue(optionalUserResult.isPresent(), "Cannot find user.");
            final User result = optionalUserResult.get();
            Assert.state(result.getFirstName().equals(testUser.getFirstName()), "query result firstName doesn't match!");
            Assert.state(result.getLastName().equals(testUser.getLastName()), "query result lastName doesn't match!");
  "findOne in User collection get result: {}", result.toString());
  3. Save and close the main application Java file.

Build and test your app

  1. Open a command prompt and navigate to the folder where your pom.xml file is located; for example:

    cd C:\SpringBoot\wingtiptoysdata


    cd /users/example/home/wingtiptoysdata

  2. Use the following command to build and run your application:

    ./mvnw clean

    This command runs the application automatically as part of the test phase. You can also use:

    ./mvnw spring-boot:run

    After some build and test output, your console window will display a message similar to the following:

    INFO 1365 --- [           main] c.e.w.WingtiptoysdataApplication         : Deleted all data in container.
    ... (omitting connection and diagnostics output) ...
    INFO 1365 --- [           main] c.e.w.WingtiptoysdataApplication         : findOne in User collection get result: testFirstName testLastName, test address line one

    The above output messages indicate that the data was successfully saved to Azure Cosmos DB and then retrieved again.

Clean up resources

If you're not going to continue to use this application, be sure to delete the resource group containing the Azure Cosmos DB you created earlier. You can do this from the Azure portal.

Next steps

To learn more about Spring and Azure, continue to the Spring on Azure documentation center.

More Resources

For more information about using Azure Cosmos DB and Java, see the following articles:

For more information about using Spring Boot applications on Azure, see the following articles:

For more information about using Azure with Java, see the Azure for Java Developers and the Working with Azure DevOps and Java.

The Spring Framework is an open-source solution that helps Java developers create enterprise-level applications. One of the more-popular projects that is built on top of that platform is Spring Boot, which provides a simplified approach for creating stand-alone Java applications. To help developers get started with Spring Boot, several sample Spring Boot packages are available at In addition to choosing from the list of basic Spring Boot projects, the Spring Initializr helps developers get started with creating custom Spring Boot applications.