能否通过REST API一次性列出Azure账户下所有数据库?
Great question! Let me break down how this works in Azure:
Unfortunately, there isn't a single REST API endpoint that can list all databases across every Azure database service (MySQL, PostgreSQL, SQL Database, etc.) in one go. Here's why, plus the best workarounds to get the data you need:
Why No Unified Endpoint?
Each Azure database service is managed by a separate resource provider (e.g., Microsoft.Sql for SQL Databases, Microsoft.DBforMySQL for Azure Database for MySQL, Microsoft.DBforPostgreSQL for Azure Database for PostgreSQL). These providers operate independently with their own API structures, so there’s no universal endpoint to pull all database types at once.
Your Best Options
1. Use Azure Resource Graph (Recommended for Bulk Listing)
Azure Resource Graph is built exactly for cross-resource queries like this. You can write a Kusto-style query to fetch all databases across your subscriptions/resource groups in a single request, regardless of their service type.
Example query to retrieve key database details:
Resources | where type in ( 'microsoft.sql/servers/databases', 'microsoft.dbformysql/servers/databases', 'microsoft.dbforpostgresql/servers/databases', 'microsoft.azurecosmosdb/databaseAccounts/sqlDatabases' // Add other database types if needed ) | project DatabaseName = name, ServiceType = type, ResourceGroup = resourceGroup, SubscriptionId = subscriptionId
You can run this query via:
- Azure Portal’s Resource Graph Explorer
- REST API (
POST /subscriptions/{subscriptionId}/providers/Microsoft.ResourceGraph/resources?api-version=2021-03-01) - Azure CLI:
az graph query -q "<your-query-here>" - Azure PowerShell:
Search-AzGraph -Query "<your-query-here>"
2. Call Individual Service APIs
If you only need databases from specific services, you can directly use their dedicated REST endpoints. For example:
- Azure SQL Databases:
GET /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases?api-version=2021-11-01 - Azure Database for MySQL:
GET /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases?api-version=2021-05-01 - Azure Database for PostgreSQL:
GET /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases?api-version=2021-06-01
Note: You’ll need to iterate over each server in the target service to collect all its databases.
Final Recommendation
If you want a full overview of all databases in your Azure account, Azure Resource Graph is the most efficient approach. It eliminates the need to write multiple API calls and handle pagination across different services.
内容的提问来源于stack exchange,提问作者Roman Alekseiev

