Watch the recording of this lesson on YouTube 🎥.
The goal of this lesson is to create your first function which can be triggered by doing an HTTP GET or POST to the function endpoint.
This lessons consists of the following exercises:
📝 Tip - If you're stuck at any point you can have a look at the source code in this repository.
📝 Tip - If you have questions or suggestions about this lesson, feel free to create a Lesson Q&A discussion here on GitHub.
Prerequisite | Exercise |
---|---|
An empty local folder / git repo | 1-6 |
Azure Functions Core Tools | 1-6 |
VS Code with Azure Functions extension | 1-6 |
REST Client for VS Code or Postman | 1-6 |
See .NET prerequisites for more details.
In this exercise, you'll be creating a Function App with the default HTTPTrigger and review the generated code.
-
In VSCode, create the Function App by running
AzureFunctions: Create New Project
in the Command Palette (CTRL+SHIFT+P). -
Browse to the location where you want to save the function app (e.g. AzureFunctions.Http).
📝 Tip - Create a folder with a descriptive name since that will be used as the name for the project.
-
Select the language you'll be using to code the function, in this lesson we'll be using
C#
. -
Select
HTTPTrigger
as the template. -
Give the function a name (e.g.
HelloWorldHttpTrigger
). -
Enter a namespace for the function (e.g.
AzureFunctionsUniversity.Demo
).📝 Tip - Namespaces are used to organize pieces of code into a hierarchy. Make sure you don't use the exact same name as the function/class. Namespaces and classes should be named uniquely to prevent compiler and readability issues.
-
Select
Function
for the AccessRights.🔎 Observation - Now a new Azure Functions project is being generated. Once it's done, look at the files in the project. You will see the following:
File Description AzureFunctions.Http.csproj The C# project file which specifies the .NET version, Azure Functions version and package references. HelloWorldHttpTrigger.cs The C# class containing the HTTPTrigger function method. host.json Contains global configuration options for all the functions in a function app. local.settings.json Contains app settings and connectionstrings for local development. ❔ Question - Review the generated HTTPTrigger function. What is it doing?
-
Build the project (CTRL+SHIFT+B).
-
Start the Function App by pressing
F5
.🔎 Observation - Eventually you should see an HTTP endpoint in the output.
-
Now call the function by making a GET request to the above endpoint using a REST client:
GET http://localhost:7071/api/HelloWorldHttpTrigger?name=YourName
❔ Question - What is the result of the function? Is it what you expected?
❔ Question - What happens when you don't supply a value for the name?
Let's change the template to find out what parameters can be changed. Depending on the trigger, arguments can be added/removed and parameter types can be changed. Start with only allowing GET requests.
-
Remove the
"post"
string from theHttpTrigger
attribute. Now the function can only be triggered by a GET request.📝 Tip - Some people don't like to use strings and prefer something that is known as strong typing. Strong typing can prevent you from making certain mistakes such as typos in strings since specific .NET types are used instead. To allow the function to be triggered by a GET request replace the
"get"
string withnameof(HttpMethods.Get)
. Now you're using a strongly typed version of the HTTP GET verb instead of a string reference. -
The
req
parameter type can also be changed. Try changing it fromHttpRequest
toHttpRequestMessage
. This requires a using ofSystem.Net.Http
.🔎 Observation - You'll notice that this change breaks the code inside the function. This is because the
HttpRequestMessage
type has different properties and methods than theHttpRequest
type. -
Remove the content of the function method (but keep the method definition). We'll be writing a new implementation.
-
Remove the
async Task
part of the method definition since the method is not asynchronous anymore. The method should look like this now:public static IActionResult Run(...)
-
To get the name from the query string you can do the following:
var collection = req.RequestUri.ParseQueryString(); string name = collection["name"];
🔎 Observation - In the generated template the response was always an
OkResultObject
. This means that when a clients calls the function, an HTTP status 200, is always returned. Let's make the function a bit smarter and return aBadRequestObjectResult
(HTTP status 400). -
Add an
if
statement to the function that checks if the name value isnull
. If the name isnull
return aBadRequestObjectResult
, otherwise return aOkResultObject
.ObjectResult result; if(string.IsNullOrEmpty(name)) { var responseMessage = "Pass a name in the query string or in the request body for a personalized response."; result = new BadRequestObjectResult(responseMessage); } else { var responseMessage = $"Hello, {name}. This HTTP triggered function executed successfully."; result = new OkObjectResult(responseMessage); } return result;
Now the function has proper return values for both correct and incorrect invocations.
-
Run the function, once without name value in the querystring, and once with a name value.
❔ Question - Is the outcome of both runs as expected?
Let's change the function to also allow POST requests and test it by posting a request with JSON content in the body.
-
Add a new C# class file named
Person.cs
to the project. -
Make sure the content of the file looks like this (adjust the namespace so it matches yours):
namespace AzureFunctionsUniversity.Demo { public class Person { public string Name { get; set; } } }
-
Update the
HttpTrigger
attribute of the function to include the POST HTTP verb. You can choose to add the verb via the strongly typed way by addingnameof(HttpMethods.Post)
or use the"post"
string. -
The function method now only handles GET requests. We need to add some logic to use the querystring for GET requests and use the request body for POST requests. This can be done by checking the Method property of the request (if the request type is
HttpRequestMessage
) as follows:string name = default; if (req.Method.Method == HttpMethods.Get) { // Get name from querystring // name = ... } else if (req.Method.Method == HttpMethods.Post) { // Get name from body // name = ... }
-
Move the querystring logic inside the
if
statement that handles the GET request. -
Now let's add the code to extract the name from the body for a POST request.
📝 Tip - When the request type is
HttpRequestMessage
there's a very nice method available on the Content property calledReadAsAsync<T>
. This method returns a typed object from the request content. In our case we can return aPerson
object from the request as follows:var person = await req.Content.ReadAsAsync<Person>(); name = person.Name;
-
Change the method definition back to its asynchronous form since we're using async methods again:
public static async Task<IActionResult> Run(...)
-
Now run the function and do a POST request and submit JSON content with a
Name
property. If you're using the VSCode REST client you can use this in a .http file:POST http://localhost:7071/api/HelloWorldHttpTrigger Content-Type: application/json { "name": "Your name" }
❔ Question - Is the outcome of the POST as expected?
❔ Question - What is the response when you use an empty
name
property?
Instead of using the HttpRequest
or HttpRequestMessage
type for the req
parameter a custom .NET type can be used as the parameter type, in this case Person
. This is only useful when working solely with the request body and not the querystring, since the HttpRequest object will be unavailable. Let's add a new function to the existing class file which only responds to POST requests.
-
Create a copy of the
HelloWorldHttpTrigger.cs
file and rename the file, the class and the function toPersonTypeHttpTrigger.cs
.📝 Tip - Function names need to be unique within a Function App.
-
Remove the GET verb from the
HttpTrigger
attribute since this function will only be triggered by POST requests. -
Change the
HttpRequestMessage
type toPerson
and rename thereq
parameter toperson
. The HttpTrigger attribute should look like this:[HttpTrigger(AuthorizationLevel.Function, nameof(HttpMethods.Post), Route = null)]Person person,
-
Remove the logic inside the function which deals GET Http verb and with the querystring.
-
Update the logic which checks if the
name
variable is empty. You can now useperson.Name
instead. -
Run the Function App.
🔎 Observation - You should see the new HTTP endpoint in the output of the console.
-
Trigger the new endpoint by making a POST request.
❔ Question - Is the outcome as expected?
Instead returning "Hello {name}" all the time, it would be nice if we can supply our own greeting. So we could return "Hi {name}" or "Good evening {name}". We can do this by changing the route of the function so it contains the greeting. The function will only triggered for GET requests.
-
Create a copy of the
HelloWorldHttpTrigger.cs
file and rename the file, the class and the function toCustomGreetingHttpTrigger.cs
. -
Remove the
nameof(HttpMethods.Post)
parameter from theHttpTrigger
binding. -
Now update the
Route
parameter in theHttpTrigger
binding as follows:Route = "CustomGreetingHttpTrigger/{greeting:alpha?}")
🔎 Observation - The
Route
uses a route argument namedgreeting
and it has analpha
constraint. This means thatgreeting
may only contain characters from the alphabet (a-z). The question mark indicates thegreeting
parameter is optional. More info on route parameter constraints in the official docs. -
Add the following parameter to the function method:
string greeting,
🔎 Observation - By specifying
string greeting
as an additional parameter of the method, we can now use the greeting value (that is retrieved from the route) in our function code. -
Replace the existing body of the function method with the following:
var collection = req.RequestUri.ParseQueryString(); string name = collection["name"]; greeting = greeting ?? "Hello"; ObjectResult result; if(string.IsNullOrEmpty(name)) { var responseMessage = "Pass a name in the query string for a personalized response."; result = new BadRequestObjectResult(responseMessage); } else { var responseMessage = $"{greeting}, {name}. This HTTP triggered function executed successfully."; result = new OkObjectResult(responseMessage); } return result;
-
Run the Function App.
🔎 Observation - You should see the new HTTP endpoint in the output of the console.
-
Trigger the new endpoint by making a GET request to the following endpoint.
GET http://localhost:7071/api/CustomGreetingHttpTrigger/hi?name=YourName
❔ Question - Is the outcome as expected?
Ready to get hands-on? Checkout the homework assignment for this lesson.
-
For more info about the HTTP Trigger have a look at the official Azure Functions HTTP Trigger documentation.
-
A brief overview video by Gwyneth Pena
We love to hear from you! Was this lesson useful to you? Is anything missing? Let us know in a Feedback discussion post here on GitHub.