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 lesson consists of the following exercises:
Nr | Exercise |
---|---|
1 | Creating a Function App |
2 | Changing the template for GET requests |
3 | Changing the template for POST requests |
4 | Adding a new function for POST requests |
📝 Tip - If you're stuck at any point you can have a look at the source code in this repository.
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 or F1 in CodeSpaces). -
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#
. When asked for a runtime, select `.NET 6.0 LTS'. -
Select
HTTPTrigger
as the template. -
Give the function a name (e.g.
HelloWorldHttpTrigger
). -
Enter a namespace for the function (e.g.
AzureFunctions.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 in a terminal by executing
dotnet build
in the just created folder and validate that it compiles without errors. -
Start the Function App by running
func host start
. If the default port (7071) is in use, you can specify a different port by runningfunc host start --port 7072
.🔎 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 AzureFunctions.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.
-
Copy & paste the function method from the exercise above and give this method a new name in the
FunctionName
attribute.📝 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 two HTTP endpoints in the output of the console.
-
Trigger the new endpoint by making a POST request.
❔ Question Is the outcome as expected?
- For more info about the HTTP Trigger have a look at the official Azure Functions HTTP Trigger documentation.