Number Classification API: Fully Automated Deployment on Azure App Services with ARM Integration.
Technology Stack
Programming Languag: C# with ASP.NET Core
Cloud Provider: Azure
Infrastructure as Code: ARM Template
Azure Services: App Services
Prerequisites
Ensure you have the following before starting:
An Azure Account
Azure CLI Installed
.NET SDK Installed
Git Installed
Introduction
An API (Application Programming Interface) is a set of rules and protocols that allow different software applications to communicate with each other. It defines how requests and responses should be structured, enabling applications to share data and functionality without exposing their internal code. APIs can be RESTful, SOAP-based, or use other architectures, and they are commonly used for web services, integrating third-party applications, and automating workflows.
The Number Classification API is a cloud-based service deployed on Azure App Services with ARM template automation, designed to analyze and classify numbers based on mathematical properties. It determines whether a number is prime, perfect, Armstrong, or odd/even, while also computing its digit sum. Additionally, it fetches fun facts about numbers from an external API, enhancing its functionality. Built using C# and ASP.NET Core, the API ensures efficient, scalable, and reproducible deployment through Infrastructure as Code (IaC). With structured JSON responses and robust error handling, it provides a seamless and reliable experience for users.
Step 1: Set Up Your Development Environment
1. Install .NET SDK
Download and install the latest .NET SDK (Ensure at least .NET 6 or later).
Verify installation by running:
dotnet --version
2. Create a New ASP.NET Core Web API Project
dotnet new webapi -n NumberClassificationAPI
This will create a new ASP.NET Core Web API project in a folder named NumberClassificationAPI
.
3. Navigate into the project directory
cd NumberClassificationAPI
Step 2: Install Required Dependencies
1. Install Newtonsoft.Json for JSON serialization
dotnet add package Newtonsoft.Json
2. Install Cors for Cross-Origin Resource Sharing
dotnet add package Microsoft.AspNetCore.Cors
Step 3: Implement the API Logic
1. Open the Project in a Code Editor
If using Visual Studio Code, run:
code .
If using Visual Studio, open the
NumberClassificationAPI.sln
file.
2. Modify Program.cs
to Enable CORS
Open Program.cs
and update it with the following code to include CORS support:
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.WriteIndented = true; // Enables pretty-printing
});
builder.Services.AddCors();
var app = builder.Build();
app.UseCors(policy =>
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
3. Create the API Controller
Locate the Controllers
folder. If there is none, manually create a new folder inside your project root and name it Controllers
. Then create a new file named NumberController.cs
inside the Controllers folder and add the code below:
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
[ApiController]
[Route("api")]
public class ClassifyNumberController : ControllerBase
{
[HttpGet("classify-number")]
public async Task<IActionResult> ClassifyNumber([FromQuery] string number)
{
// Try parsing the number as a double to handle both integers and floating-point numbers
if (!double.TryParse(number, out double num))
{
return BadRequest(new { number, error = true });
}
// Use the absolute value for classification and calculations
num = Math.Abs(num);
var properties = GetNumberProperties(num);
int digitSum = num.ToString().Sum(c => c - '0'); // Sum of absolute digit values
string funFact = await GetFunFact(num);
return Ok(new
{
number = num,
is_prime = IsPrime(num),
is_perfect = IsPerfect(num),
properties,
digit_sum = digitSum,
fun_fact = funFact
});
}
private bool IsPrime(double n)
{
if (n < 2) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
private bool IsPerfect(double n)
{
if (n < 1) return false;
int sum = 1;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) sum += i + (i * i == n ? 0 : (int)(n / i));
return sum == n;
}
private string[] GetNumberProperties(double n)
{
var properties = new System.Collections.Generic.List<string>();
if (IsArmstrong(n)) properties.Add("armstrong");
properties.Add(n % 2 == 0 ? "even" : "odd");
return properties.ToArray();
}
private bool IsArmstrong(double n)
{
int sum = 0, temp = (int)Math.Abs(n), digits = temp.ToString().Length;
while (temp > 0)
{
int digit = temp % 10;
sum += (int)Math.Pow(digit, digits);
temp /= 10;
}
return sum == Math.Abs(n);
}
private async Task<string> GetFunFact(double n)
{
using var httpClient = new HttpClient();
string apiUrl = $"http://numbersapi.com/{(int)n}/math"; // Use the integer part for the fun fact
try
{
return await httpClient.GetStringAsync(apiUrl);
}
catch
{
return "No fun fact available";
}
}
}
Step 4: Test the API Locally
Save your changes
Build and Run the API
dotnet build dotnet run
Test in Browser or Postman
Open:
http://localhost:5062/api/classify-number?number=371
Response:
Try
number=
3xyzExpected Response:
Step 6: Create a Repository
Create a public repository in GitHub
Push Code to GitHub repo
git init git add . git commit -m "Initial commit" git branch -M main git remote add origin <your-github-repo-url> git push -u origin main
Step 5: Deploy to a Public Endpoint
Deploy on Azure App Services
Prerequisites
Ensure you have before starting:
An Azure Account
Azure CLI Installed
.NET SDK Installed
GitHub Repository with your API code
Git Installed (Download)
- Login to Azure
az login --tenant <tenantID>
replace <tenantID> with your Azure tenant ID
This opens a browser for authentication. Select your Azure account.
- Create an Azure Resource Group
az group create --name webappRG --location westus
Replace webappRG
and westus
with your preferred name and location.
- Create an Azure App Service Plan
az appservice plan create --name myAPIServicePlan --resource-group webappRG --sku F1 --is-linux
F1 is a Free (F1) tier (good for testing).
Use --is-linux if you're deploying a Linux-based app.
- Create an Azure Web App
az webapp create --name numberClassificationAPI-763 --resource-group webappRG --plan myAPIServicePlan --runtime "DOTNETCORE:8.0"
Replace numberClassificationAPI-763 with a unique app name.
Your live URL will be: https://numberClassificationAPI-763.azurewebsites.net
- Configure Deployment from GitHub : link your repository:
az webapp deployment source config --name numberClassificationAPI-763 --resource-group webappRG --repo-url https://github.com/celestinaodili/NumberClassificationAPI.git --branch main --manual-integration
Replace GitHub url with yours. Replace numberClassificationAPI-763
with your web app name.
- Enable Continuous Deployment (CI/CD)
Set up GitHub Actions to deploy automatically when you push changes.
Go to GitHub Repository
Navigate to Settings → Secrets and variables → Actions
Click New Repository Secret
add the following:
Name: AZURE_WEBAPP_PUBLISH_PROFILE
Secret: Get it by running the following command
az webapp deployment list-publishing-profiles --name numberClassificationAPI-763 --resource-group webappRG --xml
Replace
numberClassificationAPI-763
with your webapp nameCopy and paste the entire XML output into GitHub.
- Add GitHub Actions Workflow
Create a .github/workflows/deploy.yml file in your repo and add:
name: Deploy API to Azure
on:
push:
branches:
- main
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Setup .NET Core
uses: actions/setup-dotnet@v3
with:
dotnet-version: '8.0'
- name: Build and Publish API
run: |
dotnet publish -c Release -o release
- name: Deploy to Azure
uses: azure/webapps-deploy@v2
with:
app-name: "numberClassificationAPI-763"
slot-name: "production"
publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }}
package: release
replace numberClassificationAPI-763
with your webapp name
- Retrieve Endpoint:
Retrieve base url, run
az webapp show --resource-group webappRG --name numberClassificationAPI-763 --query "defaultHostName" --output tsv
returned url:
numberClassificationAPI-763.azurewebsites.net
Endpoint (Full API URL): Append the API path (
/api/classify-number
) to the returned url. Add a query parameter (?number=371
) to test the endpoint. Hence the API endpoint ishttps://numberClassificationAPI-763.azurewebsites.net/api/classify-number
- Test Endpoint:
To test the end point, you need to append the query parameter.
Open
https://numberClassificationAPI-763.azurewebsites.net/api/classify-number?number=371
in a browser