Working with Azure Function – An HOL for Calculator
Create a Function app from the Azure Portal
Pass on the necessary information like Name, Subscription, Resource Group, Hosting Plan( Consumption Plan), Location and storage account (create new fro dropdown if not pre existing).
Click on the + Button for functions and name the function “Addition”.
You will to migrated to the Run.csx which is the default entry point of the application. Put in the following code.
Run.csx
#r "Newtonsoft.Json" |
|
| #load "models.csx" |
|
|
| using System; |
| using System.Net; |
| using Newtonsoft.Json; |
|
|
| public static async Task<object> Run(HttpRequestMessage req, TraceWriter log) |
| { |
| log.Verbose($"Webhook was triggered!"); |
| |
| string jsonContent = await req.Content.ReadAsStringAsync(); |
| dynamic data = JsonConvert.DeserializeObject(jsonContent); |
| |
| ApiResult result = new ApiResult(); |
| |
| if (data.a == null || data.b == null) { |
| result.Success = false; |
| result.Error = new Error(1, "Please provide both a and b as paremeters."); |
| return req.CreateResponse(HttpStatusCode.BadRequest, result); |
| } |
| |
| int a = int.Parse(data.a.ToString()); |
| int b = int.Parse(data.b.ToString()); |
| |
| int sum = a + b; |
| result.Result = sum; |
| return req.CreateResponse(HttpStatusCode.OK, result); |
| } |
Click on Add Files on the Right Hand panel and create a new file Models.csx and put the following code:
Models.csx
public class Error {
public Error() {}
public Error(int code, string message) {
this.Code = code;
this.Message = message;
}
public int Code {get;set;}
public string Message {get;set;}
}
public class ApiResult {
public ApiResult() {
Success = true;
}
public int? Result {get;set;}
public Error Error {get;set;}
public bool Success {get;set;}
}
Now in order to test the application, Click on the TEST tab on right hand panel and select POST as the HTTP method and add the values of a & b in the following format and hit on run button.
{“a” :10, “b” :5}
You will get the output as
Now in order to use this calculator API in your applications. You have to click on the Get function Url link and copy the generated url.
In order to test the API, we are using POSTMAN tool and passing the url with a POST http verb and the body as { “a” :4, “b” :5}