Building FastAPI Azure Function Applications

Author

Reads 187

Modern data center corridor with server racks and computer equipment. Ideal for technology and IT concepts.
Credit: pexels.com, Modern data center corridor with server racks and computer equipment. Ideal for technology and IT concepts.

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It's perfect for building Azure Functions.

To get started, you'll need to create a new Azure Function project using the Azure Functions Core Tools. This will create a basic directory structure for your project.

The Azure Functions Core Tools also allow you to create new Azure Functions using the `func` command. For example, you can create a new HTTP-triggered Azure Function using `func new --language python --template "HTTP trigger"`.

Prerequisites

To start building a FastAPI Azure Function, you'll need to have the fastapi and azure-functions Python libraries installed. I recommend using versions 0.111.0 and 1.20.0 respectively, as they are the versions used in this tutorial.

FastAPI is a modern web framework for building APIs with Python based on standard Python type hints, making it a great choice for building high-performance APIs.

The first step is to create a FastAPI app, which is a straightforward process.

Project Setup

Credit: youtube.com, Deploying FastAPI app to Azure Functions + API Management

To set up a FastAPI Azure Function, you'll need to install the required packages, including FastAPI, uvicorn, and azure-functions.

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.

Create a new directory for your project and navigate to it in your terminal or command prompt.

Azure Functions is a serverless compute service that allows you to run code without provisioning or managing infrastructure.

Install the required packages by running the command `pip install fastapi uvicorn azure-functions`.

The `fastapi` package can be installed using pip, and it's a great choice for building APIs quickly.

You can verify the installation by running the command `fastapi --version` in your terminal or command prompt.

The `azure-functions` package is used to interact with Azure Functions, and it's a crucial part of setting up your serverless compute service.

FastAPI Framework

FastAPI Framework is a popular choice for building Azure Functions. It supports WSGI and ASGI-compatible frameworks with HTTP-triggered Python functions.

Credit: youtube.com, Secure Serverless APIs with Python FastAPI, Azure AD and Azure Functions

Azure Functions can be used with FastAPI by including the fastapi module in the requirements.txt file.

FastAPI uses pydantic to formalize how data needs to be received and returned by the API. It auto-generates useful API docs as well.

To use FastAPI with Azure Functions, you need to update the host.json file with the routePrefix key set to an empty string.

Fast Blueprint.py

The Fast Blueprint.py is an example of a very simple HTTP function in the FastAPI framework. It defines one optional parameter, name, which defaults to "world" if not provided.

This parameter is defined using an Annotated class and a Query class, which are minor additions that build towards a fully documented API. Defining the type as Optional[str] means that the reader of the docs knows what type to submit for that parameter.

The description of the parameter will appear as an information block in the docs, making it clear to see once the app is launched. The Fast Blueprint.py example provides a basic structure for creating a simple FastAPI app.

Using FastAPI Framework

Credit: youtube.com, FastAPI - A python framework | Full Course

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It's designed to be easy to use, fast, and flexible, and can be used to create Azure Function apps.

FastAPI supports WSGI and ASGI-compatible frameworks with HTTP-triggered Python functions. This means you can use it to create Azure Function apps if you're familiar with a particular framework or have existing code you want to reuse.

Here are some key features of FastAPI:

  • Supports WSGI and ASGI-compatible frameworks
  • Can be used to create Azure Function apps
  • Designed to be easy to use and fast
  • Flexible and can be used for a variety of use cases

You can use FastAPI to create a simple HTTP function, such as the one shown in example 6, "fast_blueprint.py". This example shows how to define a function with an optional parameter, name, which defaults to "world" if not provided.

Credit: youtube.com, FastAPI Tutorial | FastAPI vs Flask

FastAPI also supports using pydantic for request and response schemas, as shown in example 5, "Request and Response Schemas". This allows you to formalize how data needs to be received and returned by the API, and auto-generates useful API docs.

In addition, FastAPI can be used to create a FastAPI app that can be deployed to Azure, as shown in example 3, "function_app.py". This example shows how to create a FastAPI app, add middleware to compress the response, and load the app into an Azure Function App class.

Here's a summary of the key steps to create a FastAPI app:

1. Create a new FastAPI app

2. Add middleware to compress the response

3. Load the app into an Azure Function App class

4. Deploy the app to Azure

By following these steps, you can create a FastAPI app that can be deployed to Azure and provides a high-performance API.

Azure Function

Azure Functions can be combined with your FastAPI app to create a powerful and scalable application. This can be achieved by defining Azure trigger functions in a separate file, such as azure_blueprint.py.

Credit: youtube.com, Fix : No HTTP triggers found (Azure Functions) - Python FastApi

You can create a blob trigger function that reads a target blob into memory, for example, a blob.csv file stored in a storage container. The path to the blob is specified as path/to/my/blob.csv and the credential is an environment variable named STORAGEACCOUNTCREDENTIAL.

In function_app.py, you can import the new blueprint and load it into the app using register_functions(). This allows you to blend the FastAPI app with Azure-native function types.

Combining Azure-Native Functions

You can blend your FastAPI app with Azure-native function types such as a blob trigger function. This is done by defining some Azure trigger functions in azure_blueprint.py. For example, a blob trigger function might read the target blob into memory.

A standard blob trigger function might look like this: it reads the path to the blob in the storage container, which is path/to/my/blob.csv, and uses the credential from an environment variable named STORAGEACCOUNTCREDENTIAL.

In function_app.py, you can import the new blueprint and load it into the app using register_functions(). This makes it possible to combine the FastAPI app with Azure-native http trigger functions.

Credit: youtube.com, The 8 Different Types Of Azure Function Triggers | Azure Function Triggers | Azure Function

However, combining FastAPI with azure-native http triggers can lead to complications with route mapping, where Microsoft assigns priority alphabetically. As of now, it's not possible to manually assign priority to functions, so be very careful in this case.

Here are some Azure-native functions that blend effectively with FastAPI:

  • Blob trigger functions
  • Cosmos trigger functions
  • Timer trigger functions

Testing in Azure

Testing in Azure is a crucial step in ensuring your Azure Function works as expected.

You can test different paths on the deployed URL using either a browser or a tool like Postman.

If you encounter an error about handle_async not being defined, it's likely because the Azure Functions runtime doesn't have the latest version of azure-functions.

Add an environment variable named PYTHON_ISOLATE_WORKER_DEPENDENCIES with a value of 1 to work around this issue for now.

This environment variable ensures that the packages in your requirements.txt are installed in a separate virtual environment than the packages of the functions runtime.

Deploy to Azure

To deploy your FastAPI Azure function, you'll need to sign up for a free Azure account. This will give you access to the necessary tools and resources for deployment.

Credit: youtube.com, How to Launch a FastAPI Service in Azure Containers in Less Than 10 Minutes!

You'll also need to install the Azure Developer CLI, which relies on the azure.yaml file and the configuration files in the infra folder. These files contain the necessary information for deployment.

To get started, sign in to your Azure account using the command `azd auth login`. This will authenticate your account and allow you to access the necessary resources.

Next, initialize a new azd environment using the command `azd env new`. This will prompt you to provide a name for your environment, which will be used in the name of the deployed resources.

Here are the steps to deploy your function to Azure:

  1. Sign up for a free Azure account
  2. Login to your Azure account: azd auth login
  3. Initialize a new azd environment: azd env new
  4. Provision and deploy all the resources: azd up
  5. Once it finishes deploying, navigate to the API endpoint URL from the output
  6. To get a subscription key for API calls, navigate to the portal URL from the output, open the Subscriptions page from the side nav, and copy one of the built-in keys

Alternatively, you can use the Azure extension to deploy your function. To do this, sign in to Azure, open the Azure extension, and select Create resource. Then, search for "Create Function App" and follow the prompts to deploy your function.

Credit: youtube.com, How to build serverless APIs with Azure Functions | Azure Tips and Tricks

Here are the specific steps to deploy your function using the Azure extension:

  1. Sign-in to Azure (if needed)
  2. Open Azure extension, select Create resource and search for “Create Function App”
  3. Fill the pro
  1. Select subscription — Choose the subscription (you won’t see this if there is only one subscription)
  2. Enter globally unique name — Enter the name of your function
  3. Select a runtime stack — Choose the language version which you are using in your local machine
  4. Select a location for new resource — Choose some region near you
  5. In the WORKSPACE section of the Azure extension select the project folder and click on Deploy

Calvin Connelly

Senior Writer

Calvin Connelly is a seasoned writer with a passion for crafting engaging content on a wide range of topics. With a keen eye for detail and a knack for storytelling, Calvin has established himself as a versatile and reliable voice in the world of writing. In addition to his general writing expertise, Calvin has developed a particular interest in covering important and timely subjects that impact society.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.