Creating Azure Functions
This guide will walk you through the process of creating your first Azure Function. Azure Functions provide a serverless compute experience, allowing you to run small pieces of code, or "functions," without provisioning or managing infrastructure.
Prerequisites
Before you begin, ensure you have the following installed:
- Azure CLI
- Azure Functions Core Tools
- A code editor (e.g., Visual Studio Code with the Azure Functions extension)
- Node.js (for JavaScript/TypeScript functions)
- .NET SDK (for C# functions)
- Python (for Python functions)
Steps to Create a Function
1. Initialize a New Function Project
Open your terminal or command prompt and navigate to the directory where you want to create your project. Then, run the following command to create a new Azure Functions project:
func init MyFunctionApp --worker-runtime
Replace MyFunctionApp with your desired project name and <runtime> with your chosen language runtime (e.g., node, dotnet, python).
2. Create a New Function
Once the project is initialized, you can add a new function to it. Navigate into your project directory and run:
cd MyFunctionApp
func new --name MyHttpTrigger --template "HTTP trigger"
This command creates a new HTTP-triggered function named MyHttpTrigger. You can choose from various templates like Queue trigger, Blob trigger, etc.
--authlevel parameter can be used with HTTP triggers to control access (e.g., anonymous, function, admin).
3. Develop Your Function Logic
Open the newly created function folder (e.g., MyHttpTrigger) in your code editor. You'll find files like index.js (or __init__.py, MyHttpTrigger.cs) and function.json.
Example (JavaScript - index.js):
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
const name = (req.query.name || (req.body && req.body.name));
const responseMessage = name
? 'Hello, ' + name + '!'
: 'This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.';
context.res = {
status: 200,
body: responseMessage
};
};
Example (C# - MyHttpTrigger.cs):
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
public static class MyHttpTrigger
{
[FunctionName("MyHttpTrigger")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (IActionResult)new OkObjectResult($"Hello, {name}!")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
}
4. Run Your Function Locally
From your project's root directory, start the Azure Functions host:
func start
The output will show the local endpoint for your HTTP-triggered function. You can then test it using a web browser or tools like Postman.
function.json file defines the function's trigger, inputs, and outputs. You can edit this file to customize its behavior.
5. Deploy to Azure
Once you're satisfied with your function, you can deploy it to Azure. Ensure you have logged in to your Azure account using the Azure CLI:
az login
Then, you can deploy your function app:
func azure functionapp publish <YourFunctionAppName>
Replace <YourFunctionAppName> with the name of your Azure Function App.