Azure Python HTTP Functions: A Comprehensive Guide

Inception

Hello everyone, this article is part of The Azure Series and builds upon Azure Python SDK Libraries - Concept essentials article. I use this series to publish-out Azure Projects & Knowledge.


Overview

Azure Functions is a serverless solution that allows you to build robust apps while using less code, and with less infrastructure and lower costs. Instead of worrying about deploying and maintaining servers, you can use the cloud infrastructure to provide all the up-to-date resources needed to keep your applications running.[1]

[1] Azure Functions overview | Microsoft Learn

Azure Function is a serverless solution that enables you to deploy your code with minimal resources & effort. It’s a bit similar to other cloud-provider functions; Yeah, ‘a bit’. Indeed, there are quite differences in implementation. However, at the end, the purpose is the same, which is providing a ‘serverless' resource holds your code. Azure Function supports a wide range of Run-time languages, like C#, Java, JavaScript, PowerShell, or Python.

First and foremost, I should notify you that -i.e. if you’re experience with other provider functions- the Azure Function implementation is really quite different than other cloud providers. Hence, I would like to recommend not relying on your previous experience.

Today’s Blog post will walk through a comprehensive guide to implement an HTTP function locally and test it, then deploy it to an Azure Function App by common ways.


Environment Preparation

There are some tools that need to be prepared in order to build, test, and deploy your function. will cover that in this section. Follow-up the next guidance:

  • Well, we're gonna use VS Code editor, managing Azure resources and code. Hence, installing the Azure Tools extension is required.

    After installation, the extension Icon will appear in the left bar. Open it up and follow the guidance to authenticate and login to your Azure account.
    That will list your subscriptions and resources as following screenshot.

  • Next, Install the Azure Functions Core Tools | Microsoft
    and check installed version by:

# Check installed version
func --version
4.0.6821
  • Next, Install the Azure CLI on Linux | Microsoft

    • Check installed version by az —version

    • Authenticate by typing az login command in your terminal, which will pop-up a web page to authenticate.

💡
I prefer to use Linux Terminal. Feel free to choose the intended OS version you like.

Initiate The HTTP function - locally

Microsoft provides two ways to build and deploy your functions: by using Azure Functions Core Tools and the Azure Tools extension. let’s discover both:

💡
There are more ways will discover them in the next articles, but we gonna discover two ways in this blog post.

Initiate an HTTP function by Function core tools

  1. Open-up your terminal, and make a directory for the function.
mkdir az_http_func_demo; cd az_http_func_demo
  1. Next, Function Project initialization, and specify the runtime language as Python.
    That will auto-generate a couple of files, as follows:
 func init
Select a number for worker runtime:
1. dotnet (isolated worker model)
2. dotnet (in-process model)
3. node
4. python
5. powershell
6. custom
Choose option: 4
python
Found Python version 3.12.3 (python3).
The new Python programming model is generally available. Learn more at https://aka.ms/pythonprogrammingmodel
Writing requirements.txt
Writing function_app.py
Writing .gitignore
Writing host.json
Writing local.settings.json
Writing /home/user/az_http_func_demo/.vscode/extensions.json
  1. Note that the function_app.py file has no configurations yet. and consider the function_app.py as the entry point of your function.

  2. Let’s continue creating a local function by using func new command as follows; Then, specify HTTP Trigger, set a function name as “eraki_http_func_demo“, and auth level as Anonymous as a demo for the current implementation.

    💡
    Anonymous will fire up the function once accessed by anyone. Function and Admin authentications will require access by an API Key created in the function resource.
     func new
     Select a number for template:
     1. Blob trigger
     2. CosmosDB trigger
     3. Dapr Publish Output Binding
     4. Dapr Service Invocation Trigger
     5. Dapr Topic Trigger
     6. Blob trigger (using EventGrid source)
     7. EventGrid trigger
     8. EventHub trigger
     9. HTTP trigger
     10. Queue trigger
     11. ServiceBus Queue trigger
     12. ServiceBus Topic trigger
     13. Timer Trigger
     Choose option: 9
     Function Name: [http_trigger] eraki_http_func_demo
     Select a number for Auth Level:
     1. FUNCTION
     2. ANONYMOUS
     3. ADMIN
     Choose option: 2
     Appending to /home/user/az_http_func_demo/function_app.py
     The function "eraki_http_func_demo" was created successfully from the "HTTP trigger" template.
    

    That will update the function_app.py file as follows; The created function accepts a name and then retrieves that name as an HTTP response.
    Feel free to update the function code by replacing the if conditions there with your code. We're gonna leave it as is, as it’s enough as a demo.
    Check the code comments below for more understanding.

     import azure.functions as func  # Azure funciton SDK library.
     import datetime
     import json
     import logging
    
     app = func.FunctionApp()  # Fetch for decoration.
    
     # Setup function decoration - passing the function name and auth level - 
     # and accecpt the comming access traffic.
     @app.route(route="eraki_http_func_demo", auth_level=func.AuthLevel.ANONYMOUS)
     # start function that accept the comming http request with typehint return as http response.
     def eraki_http_func_demo(req: func.HttpRequest) -> func.HttpResponse:
         logging.info('Python HTTP trigger function processed a request.')
    
         name = req.params.get('name')  # fetch the value for name params, passed in the URL.
         # if the name param not exist will print the last else condition - 
         # if not will print if name condition.
         if not name:
             try:
                 req_body = req.get_json()
             except ValueError:
                 pass
             else:
                 name = req_body.get('name')
    
         if name:
             return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
         else:
             return func.HttpResponse(
                  "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
                  status_code=200
             )
    
  3. Now, let’s start our function locally and test it by func start command. (i.e. CTRL+C to stop the function)
    That will prompt a URL of the local function built, open it up.

  4. By passing a value for the name parameter, the response will be as follows

Initiate an HTTP function by Azure Tools extension

  1. Open-up your terminal, make a directory for the function, and open in VS Code:
mkdir az_http_func_demo; code az_http_func_demo
  1. Press F1, and search for Azure Functions: Create Function

  2. Next, specify the current path.

  3. Next, set the runtime as Python, Model V2.

  4. Then, select Skip virtual environment, or even provide a full path for it.

  5. Next, Set the Function Trigger as HTTP Trigger.

  6. Next, for Function name, set “eraki_http_func_demo”

  7. Next, for Auth level,l select Anonymous.

That's gonna build up function files and fill up the function_app.py file:

  1. Start your function by running the VS Code debugging tool:

    That will prompt your terminal with the local function URL. If not, press CTRL + ~ to open up the terminal. and test the URL as in the previous example.


Deploy The HTTP function to Azure Function App

First and foremost, must have a function app in place in order to deploy to, and that's what we're gonna build now:

  1. Navigate the Azure Portal. Then, Function App, and Create.

  2. Next, for Hosting Option, Select Flex Consumption.
    The Flex Consumption is a pay-as-you-go and it’s recommended by Microsoft for Linux machines.

  3. Next, for Function name, Set as “eraki-eastus-func-app-demo-1001”

  4. Next, for Region, Select East US.

  5. Next, set Run-time as Python, and leave others as is.

  6. Press Review + Create.

As recently mentioned, we have two ways to deploy a local function to an Azure function app. by Function core tools and VS Code extension. Let’s discover both

💡
There are more ways will discover them in the next articles, but we gonna discover two ways in this blog post.

Deploy by Function Core tools

  1. Ensure you select the correct function directory.

  2. Authenticate by typing az login command in your terminal, which will pop-up a web page to authenticate.

  3. Start deployment by:

# func azure functionapp publish <function_name>
func azure functionapp publish eraki-eastus-func-app-demo-1001
func azure functionapp logstream publish  # view logs - Optional
  1. Ensure the output includes the name of the deployed functions.

  1. Optional - Remove your function by removing the content of the function directory, then re-run:
# func azure functionapp publish <function_name>
func azure functionapp publish eraki-eastus-func-app-demo-1001

Deploy by Azure Tools extension

  1. Navigate to The Azure Tools extension within your VS Code.

  2. Ensure your function code exists at function_app.py. If not, follow the quick guidance above again.

  3. Next, navigate to Function App, collapse the Created Function App “eraki-eastus-func-app-demo-1001”

  4. Next, right-click on the “eraki-eastus-func-app-demo-1001” Function app. Then, Deploy to Function app.

  5. That will take a moment. Collapse the “eraki-eastus-func-app-demo-1001” Function app to list the deployed function.

Check and Test Deployed Function

  1. Navigate to The Azure Tools extension within your VS Code.

  2. Next, navigate to Function App, collapse the Created Function App “eraki-eastus-func-app-demo-1001”

  3. Next, right-click and Copy the function URL.

  4. Open your browser and test the URL by passing a value for the name parameter: ?name=eraki

As well as you can discover the deployed function with Azure portal:

  1. Navigate to Azure portal. Then, Function App.

  2. At the bottom of the overview page, it will list the deployed functions.


Resources


That's it, Very straightforward, very fast🚀. Hope this article inspired you and will appreciate your feedback. Thank you

0
Subscribe to my newsletter

Read articles from Mohamed El Eraki directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mohamed El Eraki
Mohamed El Eraki

Cloud & DevOps Engineer, Linux & Windows SysAdmin, PowerShell, Bash, Python Scriptwriter, Passionate about DevOps, Autonomous, and Self-Improvement, being DevOps Expert is my Aim.