🔄Backup and Restore of Azure SQL Using C# and REST API
Managing backups and performing restores in Azure SQL Database is an essential skill for developers and DevOps engineers. While the Azure Portal provides a user-friendly interface, sometimes we need to automate these operations in our applications or CI/CD pipelines.
In this article, we’ll explore how to work with Azure SQL backup and restore using C# and the Azure REST API — and why this approach can be so useful. 🚀
📌 Understanding Backups in Azure SQL
Azure SQL automatically creates backups for you:
These backups are stored in RA-GRS (geo-redundant storage) by default.
But what if you need to restore a database to a previous point in time in an automated way? 🤔 That’s where the REST API comes in handy.
🛠️ Prerequisites
Before we start coding in C#, make sure you have:
🔑 Step 1: Authenticate with Azure REST API
We’ll first authenticate against Azure AD to obtain a Bearer Token that we’ll use for API calls.
csharp
using System.Net.Http.Headers;
using System.Text.Json;
public class AzureAuth
{
private static readonly HttpClient client = new HttpClient();
public static async Task<string> GetAccessToken(string tenantId, string clientId, string clientSecret)
{
var url = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token";
var body = new Dictionary<string, string>
{
{"client_id", clientId},
{"scope", "https://management.azure.com/.default"},
{"client_secret", clientSecret},
{"grant_type", "client_credentials"}
};
var response = await client.PostAsync(url, new FormUrlEncodedContent(body));
var content = await response.Content.ReadAsStringAsync();
var json = JsonDocument.Parse(content);
return json.RootElement.GetProperty("access_token").GetString();
}
}
✅ Now we can use this token for all our REST API calls.
💾 Step 2: Restore a Database from Backup
To restore a database, we call the Azure Management REST API:
PUT
https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{newDatabaseName}?api-version=2021-02-01-preview
Here’s the C# code to perform the restore:
Recommended by LinkedIn
csharp
public class AzureSqlRestore
{
private static readonly HttpClient client = new HttpClient();
public static async Task RestoreDatabase(
string accessToken,
string subscriptionId,
string resourceGroup,
string serverName,
string sourceDatabaseName,
string newDatabaseName,
DateTime restorePoint)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var url = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}" +
$"/providers/Microsoft.Sql/servers/{serverName}/databases/{newDatabaseName}?api-version=2021-02-01-preview";
var body = new
{
location = "eastus", // Change to your server region
properties = new
{
createMode = "PointInTimeRestore",
sourceDatabaseId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{sourceDatabaseName}",
restorePointInTime = restorePoint.ToString("o") // ISO 8601 format
}
};
var json = JsonSerializer.Serialize(body);
var response = await client.PutAsync(url, new StringContent(json, System.Text.Encoding.UTF8, "application/json"));
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}
⚡ Usage Example
csharp
class Program
{
static async Task Main()
{
string tenantId = "<YOUR_TENANT_ID>";
string clientId = "<YOUR_CLIENT_ID>";
string clientSecret = "<YOUR_CLIENT_SECRET>";
string subscriptionId = "<YOUR_SUBSCRIPTION_ID>";
string resourceGroup = "<YOUR_RESOURCE_GROUP>";
string serverName = "<YOUR_SERVER_NAME>";
string sourceDb = "MyDatabase";
string newDb = "MyDatabase_Restored";
string token = await AzureAuth.GetAccessToken(tenantId, clientId, clientSecret);
await AzureSqlRestore.RestoreDatabase(
token,
subscriptionId,
resourceGroup,
serverName,
sourceDb,
newDb,
DateTime.UtcNow.AddHours(-1) // Restore to 1 hour ago ⏳
);
}
}
💡 Why Is REST API Restore Useful?
At first glance, you might think: “Why would I restore a database via an API if I can just do it in the portal?” 🤷 Well, here are some powerful scenarios:
1. CI/CD Automation 🚀
Automate restores as part of a pipeline. For example:
2. Disaster Recovery (DR) ⚡
Create a runbook or script that automatically restores a database to a safe point if corruption or data loss happens. Faster than doing it manually in the portal.
3. Test Environments Always Fresh 🔄
QA teams often need updated data. With the API, you can set up a scheduled restore (daily/weekly) to refresh test databases with production data (after sanitization).
4. Compliance and Recovery Drills ✅
Some industries require proof of recoverability. You can schedule monthly automated restores and verify the database is functional.
5. Self-Service for Teams 🙌
Build an internal tool where QA or developers can click a button → API is called → a new database copy is restored. This reduces dependency on DBAs and increases agility.
🎯 Conclusion
By using C# with the Azure REST API, we can go beyond manual restores and unlock real automation for Azure SQL Databases.
Key benefits include:
With just a few lines of code, you can integrate backups and restores into your DevOps pipelines and internal tools. 🚀
Thanks for sharing
Thanks for sharing... 🚀
Great breakdown 👏 Automating database restores through REST APIs is something I’ve found really useful in backend workflows—especially when setting up test environments quickly. It not only saves time but also reduces human error in CI/CD pipelines. Curious: in your experience, how reliable is Azure SQL restore automation under heavy load or large-scale databases?