Creating a azure Python or C# function dynamically using Azure Rest API

Shervin Mirsaeidi 61 Reputation points
2021-05-14T23:09:35.983+00:00

Hi Team,

I have been trying to follow the documentation :

https://learn.microsoft.com/en-us/rest/api/appservice/webapps/createfunction

to create azure function using Azure Rest API. I have not been able to create a C# or Python HTTP trigger function using the API. After some research I found a solution to a question that was posted on these forms but that one is showing example for creating a JavaScript function. The following is the link to that questing on Microsoft form :

https://social.msdn.microsoft.com/Forums/en-US/f4c91356-4de4-481c-83dc-7974f9ab1aae/creating-a-function-dynamically-using-azure-rest-api?forum=AzureFunctions

Can you please provide a example similar to the question above but creating simple python or C# Azure HTTP Trigger Function using this rest API similar to above example?

Thanks for your time

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,909 questions
0 comments No comments
{count} votes

Accepted answer
  1. MayankBargali-MSFT 70,936 Reputation points Moderator
    2021-05-17T02:46:47.177+00:00

    Hi @Shervin Mirsaeidi

    Welcome to Microsoft Q&A! Thanks for posting the question.

    You can modify the request body as per your requirement as mentioned in the Create Function REST API document. For your reference sharing the request body that I have tested at my end for creating the HTTP trigger function.

    Request Body for C# HTTP Trigger Function:

    {  
       "properties":{  
          "files":{  
             "run.csx":"#r \"Newtonsoft.Json\"\r\n\r\nusing System.Net;\r\nusing Microsoft.AspNetCore.Mvc;\r\nusing Microsoft.Extensions.Primitives;\r\nusing Newtonsoft.Json;\r\n\r\npublic static async Task<IActionResult> Run(HttpRequest req, ILogger log)\r\n{\r\n    log.LogInformation(\"C# HTTP trigger function processed a request.\");\r\n\r\n    string name = req.Query[\"name\"];\r\n\r\n    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();\r\n    dynamic data = JsonConvert.DeserializeObject(requestBody);\r\n    name = name ?? data?.name;\r\n\r\n    string responseMessage = string.IsNullOrEmpty(name)\r\n        ? \"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.\"\r\n                : $\"Hello, {name}. This HTTP triggered function executed successfully.\";\r\n\r\n            return new OkObjectResult(responseMessage);\r\n}\r\n"  
          },  
          "config":{  
             "bindings":[  
                {  
                   "authLevel":"function",  
                   "name":"req",  
                   "type":"httpTrigger",  
                   "direction":"in",  
                   "methods":[  
                      "get",  
                      "post"  
                   ]  
                },  
                {  
                   "name":"$return",  
                   "type":"http",  
                   "direction":"out"  
                }  
             ]  
          }  
       }  
    }  
    

    Request Body for Python HTTP Trigger Function:

    {  
       "properties":{  
          "files":{  
             "__init__.py":"import logging\nimport azure.functions as func\n\n\ndef main(req: func.HttpRequest) -> func.HttpResponse:\n    logging.info('Python HTTP trigger function processed a request.')\n\t\n    name = req.params.get('name')\n    if not name:\n        try:\n            req_body = req.get_json()\n        except ValueError:\n            pass\n        else:\n            name = req_body.get('name')\n\n    if name:\n        return func.HttpResponse(f\"Hello, {name}. This HTTP triggered function executed successfully.\")\n    else:\n        return func.HttpResponse(\n             \"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.\",\n             status_code=200\n        )\n"  
          },  
          "config":{  
             "bindings":[  
                {  
                   "authLevel":"function",  
                   "name":"req",  
                   "type":"httpTrigger",  
                   "direction":"in",  
                   "methods":[  
                      "get",  
                      "post"  
                   ]  
                },  
                {  
                   "name":"$return",  
                   "type":"http",  
                   "direction":"out"  
                }  
             ]  
          }  
       }  
    }  
    

    Hope the above helps. Feel free to get back to me if you need any assistance.

    Please 'Accept as answer' and ‘Upvote’ if it helped so that it can help others in the community looking for help on similar topics.

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Shervin Mirsaeidi 61 Reputation points
    2021-05-17T23:57:20.08+00:00

    @MayankBargali-MSFT

    Hi Mayank,

    Thank you for your response. This is exactly what I was looking for. However I believe there is a bug for creating the "init.py" azure function. When I copy paste your request body and send a put request I get a status code "201" for both the C# and Python Azure Function. However when I navigate to azure portal to test the HTTP Trigger function, it runs successfully for the C# one but for the Python I can see the "init.py" script and when I click "Test/Run" in azure portal. The response is "404 Not Found" and when I refresh the page seems like the "init.py" script disappears. Also when I navigate back to the "Functions" page under the Function App using the portal, the newly created function disappears when I click refresh. Have you tried testing the Python function after creation? Or you just assumed it was working when you got the created status code "201" response. Seems that there is some issues with the Python one. I will provide all the screen shots of what I observed. Also sometimes when you create the Python function. It creates it on the portal but when you click it, there is no script. Also sometimes the script names changes to "WarmUp" , than disappears after clicking refresh few times using the Azure portal. Can you please let me know if you notice the same issue on your end. Also if there is something that I missed. I can also provide you a video reproducing's what I have explained above. I did not want to expose my subscription ID and other info in the video. I have attached the screenshots below :

    97315-screenshot-1.png97306-screenshot-2.png97268-screenshot-3.png97227-screenshot-4.png97259-screenshot-5.png97250-screenshot-6.png


  2. Shervin Mirsaeidi 61 Reputation points
    2021-05-18T17:16:32.087+00:00

    @MayankBargali-MSFT

    You are correct, I just tried it using the "App Service Plan" and it works. There is not specific use case. I'm working on a web app that will be used by a manufacturing company, and we want allow them to upload Python or C# scripts which will run against there data. This means they will use Angular web app to upload text scripts and I will use a C# back end to create azure functions using REST API. Given the Azure Function App that was previously created. Pretty much I will hard code everything for the PUT request except the text script that they will upload using a text area for example. I could not find any NuGet packages that I can import into my C# backend that I can use to create Azure Functions on a previously created Azure Function App. The only solution I found was to use REST API. These scripts will need to be able to be executed at any time triggered from web app, also I plan to use Application Insights to check some status, logs and performance via REST API. I figured the best option would be HTTP Trigger Function App that I can call when user clicks run from my web app. Also I could not find anything that I can use to stop a single Azure Function once its started. The only option I can find is a REST API end point which will stop the Azure Function App which contains all the Azure Functions. What I need is to be able to stop a single Azure Function, for example the Python "Function1" that I have posted above.

    Please let me know if there are any other options that would simply my flow. Or if you have any other suggestions.

    One last thing, could you please also provide examples on how I would pass the applications insights "Instrumentation Key" for Python or C# function using the rest API given I have enabled application insight for the Azure Function App. Like what would the request body look like?

    I will now accept your answer.

    Once again thank you for your time


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.