Quickstart: Create your first Azure Function
Learn how to create a serverless function in Azure that responds to HTTP requests.
Published: | Last updated:This quickstart guides you through creating a serverless HTTP-triggered function using Azure Functions. Azure Functions is a serverless compute service that lets you run code on-demand without explicitly provisioning or managing infrastructure.
Prerequisites
Before you begin, ensure you have the following:
- An Azure subscription. If you don't have one, create a free account before you begin.
- Azure Functions Core Tools installed.
- Node.js (LTS version recommended).
- A code editor like Visual Studio Code.
Step 1: Create a new Function App project
Open your terminal or command prompt and run the following command to create a new directory and navigate into it:
mkdir MyFunctionApp
cd MyFunctionApp
Initialize a new Functions project using the Core Tools:
func init --worker-runtime node
This command creates a new Azure Functions project with Node.js as the runtime.
Step 2: Create an HTTP-triggered function
Now, create a new function within your project. Use the following command to create an HTTP-triggered function named 'HttpExample':
func new --name HttpExample --template "HTTP trigger"
When prompted for an authorization level, choose 'Anonymous'. This allows anyone to call your function endpoint without requiring a key.
Step 3: Run your function locally
Start the Azure Functions host to run your function locally:
func start
The output will show the local URL of your HTTP-triggered function. It will look something like this:
HttpExample: [GET,POST] http://localhost:7071/api/HttpExample
You can now access this URL in your web browser or use a tool like `curl` to test your function.
Step 4: Test your function
Open your web browser and navigate to the URL displayed in the previous step. You should see a message indicating that the function executed successfully.
You can also send a POST request with a JSON body:
curl -X POST "http://localhost:7071/api/HttpExample?name=Azure" -H "Content-Type: application/json" -d '{"message": "Hello from curl!"}'
The function will return a response including the name you provided and any data from the request body.
Step 5: Deploy your function to Azure
To deploy your function, you'll need an Azure account. You can deploy using the Azure Functions Core Tools CLI. First, log in to your Azure account:
az login
Then, create a Function App resource in Azure. Replace `MyFunctionApp-UniqueName` with a unique name for your Function App and choose your desired region:
az functionapp create --resource-group MyResourceGroup --consumption-plan-location westeurope --runtime node --runtime-version 18 --functions-version 4 --name MyFunctionApp-UniqueName
Finally, deploy your project:
func azure functionapp publish MyFunctionApp-UniqueName
Next Steps
Congratulations! You've created and deployed your first Azure Function. Here are some resources to help you learn more: