page_type languages products urlFragment name description
sample
azdeveloper
java
bicep
azure
azure-spring-apps
azure-postgresql
azure-key-vault
azure-pipelines
ms-build-openjdk
todo-java-postgresql-asa
REST API and PostgreSQL - Flexible Server on Azure Spring Apps
A REST API ToDo app on Azure Spring Apps with Azure Database for PostgreSQL flexible server for storage, . Uses Azure Developer CLI (azd) to build, deploy, and run

REST API and PostgreSQL - Flexible Server on Azure Spring Apps

A blueprint for getting a REST API app with a Java API and a PostgreSQL - Flexible Server on Azure, the REST APIs are protected by Azure Active Directory (Azure AD). The blueprint includes sample application code (a ToDo web api app) which can be removed and replaced with your own application code. Add your own source code and leverage the Infrastructure as Code assets (written in Bicep) to get up and running quickly. This architecture is for running containerized apps or microservices on a serverless platform.

Let's jump in and get this up and running in Azure. When you are finished, you will have a REST API web app deployed to the cloud. In later steps, you'll see how to setup a pipeline and run the application.

Prerequisites

The following prerequisites are required to use this application. Please ensure that you have them all installed locally.

Quickstart

Expose REST APIs

This section provides the steps to expose your REST APIs in Azure AD.

  1. Sign in to the Azure portal.

  2. If you have access to multiple tenants, use the Directory + subscription filter "Switch tenant" to select the tenant in which you want to register an application.

  3. Search for and Select Azure Active Directory.

  4. Under Manage, select App registrations > New registration.

  5. Enter a name for your application in the Name field, for example SimpleToDoApi. Users of your app might see this name, and you can change it later.

  6. For Supported account types, select Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts.

  7. Select Register to create the application.

  8. On the app Overview page, look for the Application (client) ID value, and then record it for later use. You need it to configure the YAML configuration file for this project.

  9. Under Manage, select Expose an API, find the Application ID URI at the beginning of the page, select Add.

  10. On the Edit application ID URI page, accept the proposed Application ID URI (api://{client ID}) or use a meaningful name instead of the client ID, such as api://simple-todo, and select Save.

  11. Under Manage, select Expose an API > Add a scope, and then enter the following information:

    • For Scope name, enter SimpleToDo.User.
    • For Who can consent, select Admins and users.
    • For Admin consent display name, enter Access the Simple ToDo service as an administrator.
    • For Admin consent description, enter Allows authenticated admin users to access resources of Simple ToDo..
    • For User consent display name, enter Access the Simple ToDo service as a user.
    • For User consent description, enter Allows authenticated users to access the resources of Simple ToDo..
    • For State, keep Enabled.
    • Select Add scope.
  12. Repeat the previous step to add another scope. When you select Add a scope, enter the following information:

    • For Scope name, enter SimpleToDo.Admin.
    • For Who can consent, select Admins only.
    • For Admin consent display name, enter Access the Simple ToDo service as an administrator.
    • For Admin consent description, enter Allows authenticated admin users to access resources of Simple ToDo..
    • For State, keep Enabled.
    • Select Add scope.

"Screenshot of Expose an API of a REST API"

Update the application configuration

This section provides the steps to update the YAML file to use your Azure AD registered application information to establish a relationship with the REST API application.

Update the configuration of spring.cloud.azure.active-directory in the configuration file. Be sure to replace the placeholders with your own values you created in the previous step.

spring:
  cloud:
    azure:
      active-directory:
        credential:
          client-id: <your-application-ID-of-SimpleToDoApi>
        app-id-uri: <your-application-ID-URI-of-SimpleToDoApi>

Note

In v1.0 tokens, the configuration requires the client ID of the API, while in v2.0 tokens, you can use the client ID or the application ID URI in the request. You can configure both to properly complete the audience validation.

Use the following command to rebuild the sample project:

./mvnw clean package

To learn how to get started with any template, follow the steps in this quickstart with this template(Azure-Samples/ASA-Samples-Web-Api-Application).

Deploy to Azure Spring Apps

This quickstart will show you how to authenticate on Azure, initialize using a template, provision infrastructure and deploy code on Azure via the following commands:

# Log in to azd. Only required once per-install.
azd auth login

# Enable Azure Spring Apps feature for AZD. Only required once per-install.
azd config set alpha.springapp on

# First-time project setup. Initialize a project in the current directory, using this template. 
azd init --template Azure-Samples/ASA-Samples-Web-Api-Application

# Provision and deploy to Azure
azd up

Request an access token

The REST APIs acts as a resource server, which is protected by Azure AD. Before acquiring an access token, it's required to register another application in Azure AD and grant permissions to the client application, which is named SimpleToDoWebApp.

Register the client application

This section provides the steps to register an application in Azure AD, which is used to add the permissions of app SimpleToDoApi.

  1. Sign in to the Azure portal.

  2. If you have access to multiple tenants, use the Directory + subscription filter "Switch tenant" to select the tenant in which you want to register an application.

  3. Search for and Select Azure Active Directory.

  4. Under Manage, select App registrations > New registration.

  5. Enter a name for your application in the Name field, for example SimpleToDoWebApp. Users of your app might see this name, and you can change it later.

  6. For Supported account types, use the default Accounts in this organizational directory only.

  7. Select Register to create the application.

  8. On the app Overview page, look for the Application (client) ID value, and then record it for later use. You need it to acquire access token.

  9. Select API permissions > Add a permission > My APIs. Select the SimpleToDoApi application that you registered earlier, then select the Permissions SimpleToDo.User or SimpleToDo.Admin, and select Add permissions.

  10. Select Grant admin consent for {your-tenant-name} to grant admin consent for the permissions you added.

"Screenshot of API permissions of a web application"

  1. Navigate to Certificates & secrets and select the New client secret. On the Add a client secret page, enter a description for the secret, select an expiration date, and select Add.

  2. Look for the Value of the secret, and then record it for later use. You need it to acquire access token.

Add user to access the REST APIs

This section provides the steps to create a member user in your Azure AD, then the user can manage the data of ToDo application through REST APIs.

  1. Under Manage, select Users > New user -> Create new user.

  2. On the Create new user page, enter the following information:

    • User principal name: Enter a name for the user.
    • Display name: Enter a display name for the user.
    • Password: Copy the autogenerated password provided in the Password box.

    [!NOTE]

    1. New users must complete the first login authentication and update their passwords, otherwise, you will receive an AADSTS50055: The password is expired error when you get the access token.
    2. When a new user logs in, they will receive an Action Required prompt, you may choose to Ask later to skip the validation.
  3. Select Review + create to review your selections. Select Create to create the user.

Obtain the access token

This section provides the steps to use OAuth 2.0 Resource Owner Password Credentials method to obtain an access token in Azure AD, then access the REST APIs of the app SimpleToDoApi.

  1. Request an access token using the following command. Be sure to replace the placeholders with your own values you created in the previous step.

    export CLIENT_ID=<client-ID-of-your-app-SimpleToDoWebApp>
    export CLIENT_SECRET=<client-secret-of-your-app-SimpleToDoWebApp>
    export USERNAME=<user-principal-name>
    export PASSWORD='<user-password>'
    export TENANT_ID=<tenant-ID-of-your-Azure-AD>
    curl -H "Content-Type: application/x-www-form-urlencoded" \
      -d "grant_type=password&client_id=$CLIENT_ID&scope=api://simple-todo/SimpleToDo.Admin&client_secret=$CLIENT_SECRET&username=$USERNAME&password=$PASSWORD" \
      "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/token"
  2. Look for the access_token value, and then record it for later use. You need it to access REST APIs.

Access the REST APIs

This section provides the steps to access the REST APIs of the app SimpleToDoApi.

  1. Define the following variables for HTTP requests:

    export SPRING_APPS_NAME=<Azure-Spring-Apps-instance-name>
    export BEARER_TOKEN=<access-token-from-previous-step>
  2. Ordinary users create a ToDo list:

    curl -X POST https://${SPRING_APPS_NAME}-simple-todo-api.azuremicroservices.io/api/simple-todo/lists \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer ${BEARER_TOKEN}" \
     -d '{"name":"My List"}'

    After the addition is successful, the ToDo list information will be returned.

    {"id":"<ID-of-the-ToDo-list>","name":"My List","description":null}
  3. Ordinary users create a ToDo item within a list:

    export LIST_ID=<ID-of-the-ToDo-list>
    curl -X POST https://${SPRING_APPS_NAME}-simple-todo-api.azuremicroservices.io/api/simple-todo/lists/${LIST_ID}/items \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer ${BEARER_TOKEN}" \
     -d "{\"name\":\"My first ToDo item\",\"listId\":\"${LIST_ID}\",\"state\":\"todo\"}"

    After the addition is successful, the ToDo list information will be returned.

    {"id":"<ID-of-the-ToDo-item>","listId":<ID-of-the-ToDo-list>,"name":"My first ToDo item","description":null,"state":"todo","dueDate":"2023-07-11T13:59:24.9033069+08:00","completedDate":null}
  4. Anonymous users query ToDo list:

    curl -X GET https://${SPRING_APPS_NAME}-simple-todo-api.azuremicroservices.io/api/simple-todo/lists

    Return ToDo list:

    [{"id":<ID-of-the-ToDo-list>,"name":"My List","description":null}]
  5. Anonymous users query Todo items within the specified list:

    curl -X GET https://${SPRING_APPS_NAME}-simple-todo-api.azuremicroservices.io/api/simple-todo/lists/${LIST_ID}/items

    Return ToDo item:

    [{"id":"<ID-of-the-ToDo-item>","listId":<ID-of-the-ToDo-list>,"name":"My first ToDo item","description":null,"state":"todo","dueDate":"2023-07-11T13:59:24.903307+08:00","completedDate":null}]
  6. Ordinary users modify a ToDo item within a list:

    export ITEM_ID=<ID-of-the-ToDo-item>
    curl -X PUT https://${SPRING_APPS_NAME}-simple-todo-api.azuremicroservices.io/api/simple-todo/lists/${LIST_ID}/items/${ITEM_ID} \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer ${BEARER_TOKEN}" \
     -d "{\"id\":\"${ITEM_ID}\",\"listId\":\"${LIST_ID}\",\"name\":\"My first ToDo item\",\"description\":\"Updated description.\",\"dueDate\":\"2023-07-11T13:59:24.903307+08:00\",\"state\":\"inprogress\"}"

    After the modification is successful, the latest ToDo item information will be returned.

    {"id":"<ID-of-the-ToDo-item>","listId": <ID-of-the-ToDo-list>,"name":"My first ToDo item","description":"Updated description.","state":"inprogress","dueDate":"2023-07-11T05:59:24.903307Z","completedDate":null}
  7. Admin users delete a ToDo item within a list:

    curl -i -X DELETE https://${SPRING_APPS_NAME}-simple-todo-api.azuremicroservices.io/api/simple-todo/lists/${LIST_ID}/items/${ITEM_ID} \
     -H "Authorization: Bearer ${BEARER_TOKEN}"

    You should see an output like the following snippet:

    HTTP/1.1 204
    ...
    ...
    

Application Architecture

This application utilizes the following Azure resources:

Here's a high level architecture diagram that illustrates these components. Notice that these are all contained within a single resource group, that will be created for you when you create the resources.

"Application architecture diagram"

This template provisions resources to an Azure subscription that you will select upon provisioning them. Please refer to the Pricing calculator for Microsoft Azure and, if needed, update the included Azure resource definitions found in infra/main.bicep to suit your needs.

Application Code

This template is structured to follow the Azure Developer CLI. You can learn more about azd architecture in the official documentation.

Next Steps

At this point, you have a complete application deployed on Azure. But there is much more that the Azure Developer CLI can do. These next steps will introduce you to additional commands that will make creating applications on Azure much easier. Using the Azure Developer CLI, you can delete the resources easily.

  • azd down - to delete all the Azure resources created with this template

Additional azd commands

The Azure Developer CLI includes many other commands to help with your Azure development experience. You can view these commands at the terminal by running azd help. You can also view the full list of commands on our Azure Developer CLI command page.

Reporting Issues and Feedback

If you have any feature requests, issues, or areas for improvement, please file an issue. To keep up-to-date, ask questions, or share suggestions, join our GitHub Discussions. You may also contact us via AzDevTeam@microsoft.com.