Create your first Azure Functions HTTP-triggered function
This article guides you through creating your first Azure Functions HTTP-triggered function. Azure Functions is a serverless compute service that enables you to run code on-demand without explicitly provisioning or managing infrastructure.
Prerequisites
- An Azure subscription. If you don't have one, create a free account before you begin.
- The Azure Functions Core Tools installed.
- A code editor.
Step 1: Create a new Functions project
Open your terminal or command prompt, and navigate to a directory where you want to create your project. Then, run the following command to create a new Functions project:
func init MyFunctionProj --worker-runtime node --docker
Replace MyFunctionProj
with the name of your project. The --worker-runtime
specifies the language of your Functions, and --docker
generates a Dockerfile for containerization.
Step 2: Create a new HTTP-triggered function
Navigate into your project directory:
cd MyFunctionProj
Then, create a new HTTP-triggered function:
func new --name HttpTriggerFunction --template "HTTP trigger" --authlevel "anonymous"
This command creates a new function named HttpTriggerFunction
with an HTTP trigger template. --authlevel "anonymous"
means the function can be called without an API key.
Step 3: Understand the function code
Open the HttpTriggerFunction
folder in your code editor. You'll find a few files, including index.js
(or your language's equivalent) and function.json
.
function.json
This file defines the function's bindings, including the HTTP trigger:
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
index.js
This file contains the actual code for your function:
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
};
};
Note: The code above is for Node.js. The structure and specifics will vary slightly for other languages like C#, Python, or Java.
Step 4: Run your function locally
In your terminal, within your project directory, run the following command to start the Functions host:
func start
The output will show the local URL for your HTTP-triggered function. It typically looks like http://localhost:7071/api/HttpTriggerFunction
.
Step 5: Test your function
Open your web browser and navigate to the local URL. You can also append a name query parameter:
http://localhost:7071/api/HttpTriggerFunction?name=AzureFunctionsUser
You should see a personalized greeting. If you navigate without a name, you'll see the default message.