Send JSON to restful API via Logic App and Azure Function - azure

I have JSON file which is composed in Logic Apps, Now i need to send this JSON file to a Rest API using the Post method through Azure Function.
Does anyone know how to achieve this using PowerShell in Function if not any other languages like c# or python?

I would recommend you to upload the file to a blob storage and generate a SAS url. Then you can use azure function to call the http and send the url.
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
List<FileAndUrl> filenamesAndUrls;
if (req.Method == HttpMethod.Get)
{
filenamesAndUrls = req.RequestUri.Query
.Remove(0, 1) // remove '?' at the start of the query
.Split('&') // all comands are seperated by '&'
.Select(s =>
{
var keyValue = s.Split('=');
return new FileAndUrl() { FileName = keyValue[0], Url = keyValue[1] };
}).ToList();
}
else
{
filenamesAndUrls = await req.Content.ReadAsAsync<List<FileAndUrl>>();
}
return CreateResult(filenamesAndUrls);
}
EXAMPLE

You can use the Azure functions connector in your workflow (logic apps). Then, you just need to set the body of the request with your payload, also specify the header 'Content-Type' as 'application/json'
https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-azure-functions

Related

Azure Function HTTP Triggers / Method Routing / Open API Implementation

I am currently making an API that will be hosted via Azure Functions. I'm running .net core 3.1. The way I have the project routed right now is defining the accepted methods as a parameter for the HttpTrigger then I have an if statement for determining how the endpoint was called. I am attempting to use the OpenAPI package to create API definitions, but when I assign Methods to the function, the Swagger document only picks up the first Method listed (PUT). I am unsure of the intended structure / usage of endpoints that have multiple possible request methods.
See code below. (OpenAPI tags are placeholder descriptions)
namespace Dyn.Sync.Func.PractifiSync
{
public class Prospect
{
[FunctionName("Prospect")]
[OpenApiOperation(operationId: "Run", tags: new[] { "name" })]
[OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)]
[OpenApiParameter(name: "name", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The **Name** parameter")]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "The OK response")]
public async Task<IActionResult> Create([HttpTrigger(AuthorizationLevel.Anonymous, "post", "put", Route = null)] HttpRequest req, ILogger log)
{
string primarySecretsContainerName = "Main";
DynUser user = await DynAuthManager.CreateDynUserAsync(req);
DynProspect prospect = JsonSerializer.Deserialize<DynProspect>(req.Body);
PFIConnection pfiConnector = PFIConnectionsCache.GetConnection(user, DynSecretsCache.GetSecretsContainer(primarySecretsContainerName));
try
{
if (!pfiConnector.IsConnected) { await pfiConnector.Connect(); }
if (req.Method == "POST") { return await pfiConnector.CreateProspect(prospect); }
if (req.Method == "PUT") { return await pfiConnector.UpdateProspect(prospect); }
else { return new ObjectResult("Invalid method.") { StatusCode = 400 }; }
}
catch (Exception ex)
{
DynError dynError = new DynError(ex);
log.LogError(ex, "Exception " + dynError.RequestID.ToString() + " occured.");
return (IActionResult)new ExceptionResult(ex, true);
}
}
}
}
My question is this: When the swagger document is created, it only lists whatever method I defined first (in other words, it ignores the "put" method). What is the intended way to structure an API when creating it in Azure functions? I tried creating a separate method in the same class for each HTTP method that it would accept, but then I couldn't even hit the endpoint when making requests. Does microsoft want us to create a new function class for each endpoint? So then instead of:
PUT http://myapi.azure.com/api/prospect
POST http://myapi.azure.com/api/prospect
it would be:
PUT http://myapi.azure.com/api/updateprospect
POST http://myapi.azure.com/api/prospect
I should note that this will eventually live under and Azure API Management instance, which makes me even more worried to implement it in a "one function per method" fashion as when loading azure functions the way I have done it, it correctly assigns the methods in APIM and I'd prefer not to have to manually configure it.
I have been searching for documentation on this specific issue with no luck. Anyone have any ideas how Microsoft intended this to be used?
Thanks.

Azure Functions with SignalR: Unauthorized when trying to get access to SignalR Service

i am currently developing a real time analytic Dashboard with Stream Analytics -> Azure Functions -> SignalRService -> Angular Web App.
I am struggling when i want to authorize my function with the signalr service. Therefore i added the Connectionstring to my Appsettings. When i try to send a SignalRMessage, it says that i am unauthroized. Isnt it just setting the Connectionstring with the Accesskey in AppSettings of the Function?
Current Error:
Microsoft.Azure.SignalR.Common.AzureSignalRUnauthorizedException: 'Authorization failed. If you were using AccessKey, please check connection string and see if the AccessKey is correct. If you were using Azure Active Directory, please note that the role assignments will take up to 30 minutes to take effect if it was added recently. Request Uri: https://signalrtest2.service.signalr.net/api/v1/hubs/pa'
FunctionCode:
[FunctionName("CreateRealTimeAnalytics")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
[SignalR(HubName = "pa")] IAsyncCollector<SignalRMessage> signalRMessages)
{
// Extract the body from the request
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
if (string.IsNullOrEmpty(requestBody)) { return new StatusCodeResult(204); } // 204, ASA connectivity check
var data = JsonConvert.DeserializeObject<StreamUsageHeartbeatAnalytics>(requestBody);
var dataString = Newtonsoft.Json.JsonConvert.SerializeObject(data);
await signalRMessages.AddAsync(
new SignalRMessage
{
Target = "pa",
Arguments = new[] { dataString }
});
return new OkResult(); // 200
}
[FunctionName("Negotiate")]
public static SignalRConnectionInfo Negotiate(
[HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req,
[SignalRConnectionInfo(HubName = "pa")] SignalRConnectionInfo connectionInfo)
{
return connectionInfo;
}
To achieve the above requirement we have tried to add the below connection string format which is working fine So please make sure that you have provided proper Connection string with below format in your Appsettings.
Azure__SignalR__ConnectionString : Value(My connection string)
For more information please refer the below Links:-
MICROSOFT DOCUMENTATION - Azure Function SignalIR Bindings
SO THREAD:- Unable to read Azure SignalR Connection String from Azure App Service Configuration Application Settings

Azure Function App documentation using API Management

I have created a Azure Function App. The function app connects to a SQL DB and has the following features
Return all the records in a table
Returns the records based on the column name using the below code
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
string loan_id = req.Query["loanid"];
string loan_amount = req.Query["loanamount"];
if (string.IsNullOrEmpty(loan_id)) {
//Do something when dont give loan id.
} else if (string.IsNullOrEmpty(loan_amount)) {
//DO something when dont give loan amount.
}
return new OkObjectResult("This is a test.");
}
I would like to document the function app using API Management/Swagger. Can you please let me know how this can be achieved?
Thanks in advance
You just need to create an API management service instance from the portal and add the function endpoint using the open api.
You can follow this documentation on how to do the same.

HTTPTrigger Azure Function with CosmosDb input is not working after deployment

I have created below HttpTrigger function which takes CosmosDb item as input. This code works perfectly fine on when run locally. I am using Visual Studio Code to create function and deploying to Azure after successfully ran locally. But it doesn't work on Azure, it doesn't give error or it seems it not getting any response.
public static class HttpTriggerWithCosmosDb
{
[FunctionName("HttpTriggerWithCosmosDb")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "HttpTriggerWithCosmosDb/{id}")] HttpRequest req,
[CosmosDB(
databaseName : "func-io-learn-db",
collectionName : "Bookmarks",
ConnectionStringSetting = "CosmosDBConnection",
Id = "{id}",
PartitionKey = "{id}"
)] BookMarkItem item,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = item.Url;
Console.Write( item.Id);
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $"Hello, {name}. This HTTP triggered function executed successfully.";
return new OkObjectResult(responseMessage);
}
}
While publishing, in output I see below message:
HttpTriggerCSharp1:
https://nps-func.azurewebsites.net/api/HttpTriggerCSharp1
TestMessage: https://nps-func.azurewebsites.net/api/TestMessage
5:33:02 PM nps-func: WARNING: Some http trigger urls cannot be
displayed in the output window because they require an authentication
token.
It is not showing This above function in response.
Update:
Full code can be found on Git
I got the issue, what is happening here. I had to manually add CosmosDBConnection to Azure with Azure Function:Add New Settings... command before I publish the function.
I am new to function, I was not aware this is how app_settings need to be added.

Azure functions http trigger Unity3d 2019.3

I've created a test HTTP Trigger azure function. I can trigger it correctly on azure portal and browser. However trigger from Unity editor gives "Error HTTP/1.1 500 Internal Server Error".
starting Azure function:
public static async Task<IActionResult> Run(HttpRequest req, ILogger log){
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");}
My Unity code:
formData.Add(new MultipartFormDataSection("name", "SampleName", "text/plain"));
UnityWebRequest www = UnityWebRequest.Post("https://samplefunction.azurewebsites.net/api/HttpTriggerTest?herelongblob", formData);
yield return www.SendWebRequest();
Azure CORS configuration: Request Credentials ON: Enable Access-Control-Allow-Credentials.
Function is setup always on. Integrate-Trigger: selected methods GET, POST. Authorisation level:Function.
function's host.json: "version": "2.0", "extensionBundle": { "id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[1.*, 2.0.0)"
App Service authentication:Anonymous
Unity-Azure sdk and google setup search results seems all outdated/not supported :(
What route should I take to get this to work please? happy to try any sdk / unity asset store to reach azure you may suggest! Cheers!
The error occurs in the two lines below in your code:
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
Since you set text/plain in your code. So when you do the www.SendWebRequest(), it will send a form data but not a json format data. So it will show the error message.
Below I provide the code for your reference:
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var arr = req.Form.Keys;
foreach (var key in arr) {
log.LogInformation(key);
log.LogInformation(req.Form[key]);
}
return (ActionResult)new OkObjectResult("success");
}
You can get the key and the value of the form data in the code above and then compose them to json format and then do DeserializeObject. Or if you want to use the data to create a object, you can even do not do DeserializeObject and just set the value into your object directly.
By the way, you can also try to change the text/plain to application/json in your code new MultipartFormDataSection("name", "SampleName", "text/plain"). But, as I don't know much about MultipartFormDataSection, so I'm not sure if this solution can work.
Hope it helps.

Resources