Why Use Azure Functions for APIs?
- Auto-scale on demand (hello, unpredictable traffic).
- Pay only for what you use (per millisecond).
- Quick deployment (ideal for MVPs and microservices).
- Built-in bindings to Azure services (like Blob Storage, Cosmos DB, Queues).
But be warned, this is for lightweight services. If you're building a full-blown enterprise app with complex orchestration, consider Azure App Services or AKS.
Setting Up Azure Functions for REST
Step 1: Install Prerequisites
Step 2: Create a Function Project
`func init MyFunctionApp --worker-runtime dotnet --target-framework net8.0 cd MyFunctionApp
func new --name GetProducts --template "HTTP trigger" --authlevel "anonymous"`
This creates a basic HTTP-triggered function.
Step 3: Write Your REST Endpoint
Update GetProducts.cs:
`public static class GetProducts {
[FunctionName("GetProducts")] public static IActionResult Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "products")] HttpRequest req,
ILogger log)
{ var products = new[]
{ new { Id = 1, Name = "Laptop", Price = 1000 }, new { Id = 2, Name = "Mouse", Price = 25 }
}; return new OkObjectResult(products);
}
}`
You've now got a RESTful GET endpoint at:
https://<your-function-app>.azurewebsites.net/api/products
Step 4: Add More REST Endpoints
Want to handle POST/PUT/DELETE? Create separate functions or reuse one with multiple verbs.
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "products/{id?}")] HttpRequest req
Use req.Method to branch logic inside the function - or better, separate functions per verb for clean separation.
Step 5: Local Testing
Run the azure function locally:
`func start`
Your API will be available at:
http://localhost:7071/api/products