Home Azure Cloud Python for Serverless Programming with Azure Functions on VS Code

Python for Serverless Programming with Azure Functions on VS Code

249
0

Serverless computing lets you run your code without worrying about servers, infrastructure, or scaling. Instead of setting up a virtual machine or container, you simply write your function, and the cloud provider (in this case, Azure) takes care of execution, scaling, and billing. You only pay for the execution time of your code.

In short: You write code → Azure runs it → You pay only for what you use.

This guide shows you how to build, run, debug, and deploy Python Functions entirely from Visual Studio Code.


🐍 Why Python with Azure Functions?

Python is widely used for scripting, automation, web APIs, and data processing. Combining Python with Azure Functions gives you:

  • Zero server management
  • Automatic scaling
  • Pay-per-execution pricing
  • Easy integration with Azure services (Storage, Event Hub, Cosmos DB, etc.)

Prerequisites

Before you start, make sure you’ve completed the two setup posts:

  1. A decent understanding of Azure Functions and Serverless programming. Azure Web Developer (AZ-204) and Azure Architect (AZ-305) students can refer to the Azure Functions session recordings and labs from the course. 4MCEA and Azure AI students may skip this exercise if they are not familiar with Azure Functions.
  2. Following the post Getting Started with Python, install Python.
  1. Following the post Setting Up VS Code for Python Development, install VS Code, add the essential Python extensions, then create a project folder named py-az-functions-demo, set up a virtual environment inside it, create a hello.py file as shown, run it, and also set recommended VS code settings. You can remove the hello.py file once you test it successfully as we will create a new file.

Hint: You may also create the folder outside VS Code, and to open VS Code with that folder selected, navigate into it from Terminal/PowerShell and run:

code .
  1. Following Getting Started with Azure CLI on Your Local Machine, install Azure CLI and connect to Azure.
  2. Following Setting Up VS Code for Azure Development, install essential extensions and connect to Azure.

Create Your First Function (VS Code UI – no CLI required)

Create Your First Function from VS Code

Assuming you have already set up VS Code and logged into Azure from within VS Code, initialize a Function App:

  1. Press Ctrl/Cmd+Shift+P → select Azure Functions: Create New Project…
  2. Choose an empty folder (for example, the azure-python-demo folder created in the prerequisites).
  3. Language: Python
  4. Trigger: HTTP Trigger
  5. Function Name: e.g., CoCanPyFunction
  6. Authorization Level: Anonymous

Note Authorization Levels:

  • Anonymous – Anyone can call your function without a key.
    Best for demos, testing, or public endpoints.
  • Function – Requires a function key to be passed with the request.
    The key is auto-generated and can be retrieved from the Azure portal or VS Code.
    Suitable for service-to-service calls where you want lightweight security.
  • Admin – Requires the master key, which provides full access to all functions within the Function App.
    Reserved for administrative tasks; avoid exposing this in client applications.

Example Requests with Different Authorization Levels:

Anonymous Function (no key required):

curl "https://<your-function-app>.azurewebsites.net/api/CoCanPyFunction?name=Azure"

Function-Level Auth (with function key):

curl "https://<your-function-app>.azurewebsites.net/api/CoCanPyFunction?name=Azure&code=<function-key>"

Admin-Level Auth (with master key):

curl "https://<your-function-app>.azurewebsites.net/api/CoCanPyFunction?name=Azure&code=<master-key>"

⚠️ Best Practice Reminder
Never share your function keys or admin (master) key publicly (e.g., GitHub repos, client-side apps, blog posts). If a key is exposed, rotate it immediately from the Azure portal.


Understand the Anatomy

When you create a new Function App with Python (v2 model), VS Code scaffolds a project like this:

py-az-functions-demo/
├─ .funcignore
├─ .gitignore
├─ function_app.py
├─ host.json
├─ local.settings.json
└─ requirements.txt
  • .funcignore – tells Azure which files to skip during deployment.
  • .gitignore – standard ignore rules for Git.
  • function_app.py – the main entry point where you define and register functions using decorators.
  • host.json – global runtime settings (logging, extensions).
  • local.settings.json – local-only settings and secrets (never commit this file).
  • requirements.txt – dependencies (ensure azure-functions is included).

Understanding the Auto-generated Minimal HTTP Function

When you scaffold a new Function App, VS Code adds a starter HTTP function to function_app.py.

import azure.functions as func
import logging

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

@app.route(route="CoCanPyFunction")
def CoCanPyFunction(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 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
        )

Key points to notice

  • app = func.FunctionApp(http_auth_level=...) – initializes the Function App and sets the default auth level for all HTTP routes. Here it’s ANONYMOUS.
  • @app.route(route="CoCanPyFunction") – creates an HTTP endpoint at /api/CoCanPyFunction.
  • Logging – a message is logged whenever the function executes.
  • Request handling –
    • First looks for a name query string parameter.
    • If not found, tries to read JSON from the request body.
  • Response –
    • If name is found → personalized greeting.
    • If not → returns a generic message (with status 200).

ℹ️ Note: At this stage, you may see an error like:

Import "azure.functions" could not be resolved (Pylance)

That’s expected because we haven’t installed the required dependencies yet. We’ll fix this in the next section.


Installing Dependencies

The scaffolded project includes a requirements.txt file that already lists azure-functions, the core library your code needs to run as an Azure Function.

Make sure you are in your project’s virtual environment (created during setup). In VS Code, the terminal should show the environment name in parentheses, for example:

(venv) $

Then install dependencies:

pip install -r requirements.txt

Without this step in the right environment, the generated code won’t execute locally because the azure-functions package is missing.

✅ After running the install, the azure.functions library is now available in your virtual environment. The earlier error message Import “azure.functions” could not be resolved (Pylance) should be gone, and the generated code is ready to run locally.


Test it locally

Run the Function App with F5 in VS Code. You’ll see a URL printed, usually:

http://localhost:7071/api/CoCanPyFunction

Note 1: The first time you do this, VS Code may prompt you to install Azure Functions Core Tools. Accept the prompt (or install them manually later) — these tools are required to run and debug Azure Functions on your local machine.

Note 2 (Windows): Installing Azure Functions Core Tools
The first time you run with F5, VS Code may prompt you to install Azure Functions Core Tools (required to run/debug locally). If the npm-based install fails (e.g., EPERM/ECONNRESET), install via winget instead:

winget install --id Microsoft.Azure.FunctionsCoreTools -e --source winget
func --version

Then re-open VS Code and press F5 again.
(If winget isn’t available: choco install azure-functions-core-tools-4 --params "'/x64'")

Note 3: If F5 doesn’t start the host (quick CLI check)
Sometimes F5 won’t launch or attach the local host. Run it directly from the CLI instead (from your project root where host.json is, with your venv active):

PowerShell

. .\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
func --version
func start

bash (Git Bash in VS Code)

source .venv/Scripts/activate
"/c/Program Files/Microsoft/Azure Functions Core Tools/func.exe" --version
"/c/Program Files/Microsoft/Azure Functions Core Tools/func.exe" start

If these commands work, the issue is with VS Code’s debugger session—continue using the CLI or restart VS Code and try F5 again. If func isn’t found or points to the wrong path, see Note 4.

Note 4 (Windows): If func points to the wrong location
Sometimes func resolves to an old npm/nvm shim. Check what’s being called and use the MSI-installed Core Tools instead.

PowerShell

# See which 'func' is being used
Get-Command func -All
where func

# Run the correct binary by full path (adjust if needed)
& "C:\Program Files\Microsoft\Azure Functions Core Tools\func.exe" --version
& "C:\Program Files\Microsoft\Azure Functions Core Tools\func.exe" start

# (Optional) Prefer MSI path for this session
$env:Path = "C:\Program Files\Microsoft\Azure Functions Core Tools;$env:Path"

bash (Git Bash in VS Code)

# See which 'func' is being used
which -a func

# Run the correct binary by full path (adjust if needed)
/c/Program\ Files/Microsoft/Azure\ Functions\ Core\ Tools/func.exe --version
/c/Program\ Files/Microsoft/Azure\ Functions\ Core\ Tools/func.exe start

# (Optional) Prefer MSI path for this session
export PATH="/c/Program Files/Microsoft/Azure Functions Core Tools:$PATH"

If an old npm shim keeps taking precedence (optional cleanup)

Having trouble with func on your PATH?
See: Fixing PATH: How to Make Your Shell Use the Right Tool (Windows, macOS, Linux) for step-by-step checks and fixes.

More Local Testing Scenarios

1. GET request with query string

Add ?name=Azure to the URL:

http://localhost:7071/api/CoCanPyFunction?name=Azure

Output:

Hello, Azure. This HTTP triggered function executed successfully.

2. POST request with JSON body

curl -X POST http://localhost:7071/api/CoCanPyFunction \
     -H "Content-Type: application/json" \
     -d '{"name": "Calgary"}'

Output:

Hello, Calgary. This HTTP triggered function executed successfully.

Deploy from VS Code (the easy button)

A) Create the Function App (cloud resource)

  1. Open the Azure panel (left sidebar) → expand your Subscription.
  2. Right-click Function App → Create Function App in Azure (simple).
  3. Enter a globally unique name, e.g., CoCanHelloFnApp.
  4. Choose a Region (e.g., East US).
  5. Select Python and pick your version (you used 3.13 (Preview); a stable version is fine too—match your local venv when possible).

VS Code’s simple flow uses sensible defaults and may auto-create supporting resources.
If you need to pick OS/plan/auth/storage/RG explicitly, use the Advanced option (below).


B) Publish your local project

  1. In the Azure panel, expand your Subscription → expand Function App.
  2. Right-click your newly created app (e.g., CoCanHelloFnApp) → Deploy to Function App…
  3. In the popup, click Deploy.
    • If asked which folder to deploy, pick your project root (where host.json lives).
    • If prompted to overwrite existing content, confirm.
    • If you don’t see the app yet, click Refresh in the Azure panel.
  4. After deployment completes, click See Output in the popup.
    • The OUTPUT panel shows the deployment logs and your Function URL—click it to open and test.

Tip: If the URL isn’t shown in Output, expand your Function App → Functions, right-click the function (e.g., CoCanPyFunction) → Copy Function URL.


C) Test the deployed function

  1. In the Azure panel, expand your Function App → Functions → right-click your function (e.g., CoCanPyFunction) → Copy Function URL.
  2. Open the URL in a browser or use curl, for example: https://<your-app-name>.azurewebsites.net/api/CoCanPyFunction?name=Azure

Advanced options (optional)

If you want to control hosting details during creation, use:
Right-click Function App → Create Function App in Azure (Advanced)

Recommended selections (you’ll see these in the Advanced flow):

  • Operating system: Linux (recommended for Python)
  • Hosting plan: Consumption (serverless / pay-per-use)
  • Authentication type: Secrets
  • Resource Group / Storage Account / Application Insights: choose existing or create new
  • Name availability: names are globally unique—if it’s taken, pick another

You can also adjust most of these later in the Azure Portal under your Function App’s settings.


Post-deploy quick checks

  • Configuration (App Settings):
    FUNCTIONS_WORKER_RUNTIME=python, a valid AzureWebJobsStorage, and your chosen Python version.
  • Logs: Right-click the Function App → Start Streaming Logs.
  • Cold start: First call after deploy can be slower on Consumption.

Monitoring & Logs

  • Application Insights (enable on creation or later) gives:
    • Live logs & traces
    • Request rates & failures
    • Performance metrics
  • In VS Code, right-click your Function App → Start Streaming Logs to watch production logs live.

Cost & Scaling (in a nutshell)

  • Consumption plan: scales to zero; pay only for executions and GB-seconds.
  • Premium plan: pre-warmed instances for lower cold starts, VNET support.
  • Python cold starts are usually fine for most APIs/automation; use Premium if you need consistently warm performance.

Common Gotchas (and fixes)

  • Wrong Python version: Ensure local interpreter matches the runtime you choose in Azure (e.g., Python 3.10).
  • Module not found in Azure: Re-install dependencies locally and redeploy; ensure requirements.txt includes everything.
  • Local vs cloud settings: Put secrets in App Settings in Azure, not local.settings.json.
  • CORS for browser calls: Configure CORS under your Function App → API → CORS.

When to Use Azure Functions with Python

  • Event-driven tasks: process queue messages, blobs, or webhooks.
  • Micro-APIs: quick endpoints without a full web framework.
  • Scheduled jobs: nightly cleanups, reports, snapshots.
  • Data pipelines: validate, transform, or route data on the fly.

If you later need complex workflows, explore Durable Functions (stateful orchestration in Python).


Next Steps

  • Add another trigger (Queue or Blob) and connect it to your HTTP function.
  • Turn on Application Insights and inspect live telemetry.
  • Wire up CI/CD with GitHub Actions for automatic deploys on push.

Handy Shortcuts

  • Create project: Azure Functions: Create New Project
  • Create function: Azure Functions: Create Function
  • Start/Debug: F5
  • Deploy: Right-click the project → Deploy to Function App
  • Stream logs: Right-click Function App → Start Streaming Logs
Previous articleUnderstanding a Simple Web Server Code Using Python (Flask)
Next articleBreaking Down the Python Azure Function App Step by Step
Heartin Kanikathottu
As a seasoned Cloud and Security Architect, I’ve led transformative initiatives in key roles, including Vice President at Morgan Stanley, Principal Architect at Societe Generale, and Tech Lead & Cloud Security Architect at VMware, among others. I’m also an internationally published author with multiple books available on platforms like Amazon and O'Reilly. Notably, one of my books was recognized as the 8th best cloud computing book of all time in 2020, reflecting the impact of my contributions to the field. With over 15 professional certifications from providers such as Microsoft (Azure), Amazon (AWS), Oracle (Java), Pivotal (Spring), and IBM, I bring a wealth of expertise to my work. Academically, I hold dual Master’s degrees in Cloud Computing and Data Analytics. I’m passionate about sharing knowledge and mentoring others, which is why I actively speak at global technical forums such as Tech Opportunities Fest at Platform Calgary, Google's Kubernetes Meetup, Java User Group, Elasticsearch Meetup, and the Agile India Conference.

LEAVE A REPLY

Please enter your comment!
Please enter your name here