Creating and Deploying an Azure Function in Python

Creating and Deploying an Azure Function in Python

Introduction

Azure Functions is a serverless compute service that allows you to run event-driven code without the overhead of managing infrastructure. This guide walks you through creating a basic Azure Function using Python with an HTTP trigger and deploying it using the Azure Portal.

Prerequisites

Before you begin, ensure you have the following:

  • An active Azure account.

  • Basic knowledge of Python programming.

  • Familiarity with the Azure Portal.

Steps to Create and Deploy an Azure Function

Step 1: Set Up an Azure Function App

1. Log in to the Azure Portal

  • Navigate to the Azure Portal and log in with your Azure credentials.

2. Create a New Function App

  1. In the search bar, type “Function App” and click on the result.

  2. Click on the Create button to start the creation process.

Fill in the Required Details:
  • Subscription: Select your Azure subscription.

  • Resource Group: Create a new resource group or use an existing one.

  • Function App Name: Provide a globally unique name for your function app.

  • Publish: Select Code.

  • Runtime Stack: Select Python.

  • Version: Choose Python 3.8 or above.

  • Region: Choose the region closest to you.

Hosting:
  • Operating System: Select Linux.

  • Plan type: Choose Consumption (Serverless) unless specific scaling needs require otherwise.

Monitoring:
  • Enable Application Insights for monitoring (optional but recommended).
  1. Click Review + create and then Create to deploy your Function App.

Step 2: Create a New Azure Function with HTTP Trigger

1. Go to the Function App

  • In the Azure Portal, navigate to Function Apps and select the Function App you just created.

2. Add a New Function

  1. In the Functions tab, click on + Add.

  2. Choose HTTP trigger from the template options.

  3. Provide a Function Name (e.g., HttpTriggerFunction).

  4. Set the Authorization level to Anonymous (for testing purposes; you can modify this later based on security requirements).

  5. Click Create to add the function.

Step 3: Write Your Python Code

1. Navigate to the Code Editor

  • Go to your newly created function and select Code + Test from the left menu to access the code editor.

2. Write the Function Code

The default code will provide a basic HTTP trigger. Below is an example Python code to customize your Azure Function:

import logging
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    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 is your Azure Function!")
    else:
        return func.HttpResponse(
            "Please pass a name in the query string or in the request body",
            status_code=400
        )

This function checks for a name parameter in the query string or request body. If a name is provided, it responds with a greeting; otherwise, it returns an error message.

Step 4: Test the Function Locally (Optional)

You can test the function locally before deploying it using Azure Functions Core Tools.

1. Install Azure Functions Core Tools

  • Install the Azure Functions Core Tools if you want to test locally.

2. Run the Function

  • Run the following command in your project folder:

      func start
    
  • Your function will now be available at http://localhost:7071.

Step 5: Deploy the Function via Azure Portal

1. Navigate to the Function App

  • In the Azure Portal, go to Deployment Center under your Function App.

2. Choose Deployment Option

  • You can choose various deployment options like GitHub, Azure Repos, or Local Git. If deploying directly from the Azure Portal, you can use Code + Test to edit and deploy your code.

3. Deploy the Code

  • The code you edited in Code + Test will be deployed once saved.

Step 6: Test the Function in Azure

1. Get the Function URL

  • In the Function App, navigate to Functions, select your function, and click on Get Function URL.

2. Test the Function

  • Open the URL in your browser or use a tool like Postman to send an HTTP GET or POST request.

Example URL:

https://<Your_Function_App_Name>.azurewebsites.net/api/HttpTriggerFunction?name=John

3. Check the Response

  • If everything is working correctly, you should see:
Hello, John. This is your Azure Function!

Conclusion

In this guide, we covered the steps to create a simple HTTP-triggered Azure Function using Python, deploy it via the Azure Portal, and test it. Azure Functions provides an excellent serverless platform to run code in response to events without worrying about infrastructure management. With these steps, you're now ready to build and deploy your own serverless applications using Azure Functions!