How-to-Build-a-Serverless-Web-App-with-Azure-Functions-and-RapidAPI

How to Build a Serverless Web App with Azure Functions and RapidAPI

Posted in

Serverless computing is a popular trend in cloud development, allowing developers to create scalable, cost-effective, and event-driven applications without managing servers. This article will guide you through building a serverless web app using Azure Functions and RapidAPI.

What is Serverless Computing?

Serverless computing is a cloud computing model where the cloud provider dynamically manages the allocation and provisioning of servers. A serverless application runs in stateless compute containers that are event-triggered, ephemeral, and fully managed by the cloud provider.

RapidAPI

RapidAPI is a platform that connects developers to thousands of APIs from various categories. Here’s how to sign up and get an API key.

  1. Visit the RapidAPI website: Go to RapidAPI.
  2. Sign up: Click the “Sign Up” button on the top right corner of the homepage. You can sign up using your Google, GitHub, or Facebook account or create a new account using your email address.
  3. Verify your account: After signing up, you’ll receive an email to verify your account. Click on the link in the email to verify your account.
  4. Access your dashboard: Once you’ve verified your account and logged in, click on your profile picture in the top right corner of the dashboard, and then click on “My Apps.” This will take you to a page with a list of your applications.
  5. Get your API key: By default, RapidAPI creates a default application for you named “Default Application.” Click on this application to view your API key. The API key is located under the “Security” section.
finding API key on RapidAPI

Find your API key to use RapidAPI.

Please note that the API key is sensitive information and should be kept secure. Do not share your API key publicly. You’ll use this API key to authenticate your requests when you use APIs from RapidAPI.

Terraform

Terraform is an open-source infrastructure as code (IaC) tool developed by HashiCorp. It allows you to define and provide data center infrastructure using a declarative configuration language. This means you describe your desired state of infrastructure, and Terraform will figure out how to achieve that state.

Why Use Terraform?

Terraform’s key features include:

  • Platform agnostic: You can use Terraform to manage a diverse set of service providers as well as custom in-house solutions.
  • State management: Terraform creates a state file when you create your infrastructure. This file helps Terraform track your resources and is necessary for modifying and destroying your resources.
  • Immutable infrastructure: Terraform treats infrastructure as immutable, meaning it doesn’t modify the actual resources in your infrastructure. Instead, it replaces the old resources with new ones as per the changes in the configuration.
Keep in mind that HaschiCorp has switched the Terraform license to a source-available Business Source License (BSL). The open-source fork, OpenTofu, is a viable alternative with similar functionality.

Dataflow

The following diagram illustrates the dataflow of the serverless web app that uses Azure Functions and RapidAPI.

The app consists of three main components:

  • Frontend: A static web page hosted on Azure Storage that displays the weather information to the user. The web page uses C# to call the Azure Function endpoint with the user’s location as a parameter.
  • Azure Function: A serverless function that acts as a proxy between the frontend and the RapidAPI Weather API. The function validates the user’s location, constructs the RapidAPI request with the API key, and returns the weather data to the frontend.
  • RapidAPI Weather API: An API that provides weather information for any location in the world. The API requires an API key to authenticate the requests.

The diagram shows how the data flows between these components when the user interacts with the web app. The app leverages the benefits of serverless computing, such as scalability, reliability, and cost-efficiency.

Setting Up a Development Environment Using Terraform

Here’s a basic outline of the process to set up a development environment using Terraform:

  1. Install Terraform: Download and install Terraform on your local machine.
  2. Configure your provider: In your Terraform configuration file, specify the provider (like AWS, GCP, Azure) that you want to interact with.
  3. Write the configuration: Define your infrastructure in a configuration file using HCL.
  4. Initialize Terraform: Run terraform init in your terminal. This will download the necessary provider plugins.
  5. Plan and apply: Run terraform plan to check what changes will be made. Then, run terraform apply to create the defined infrastructure.

Remember to replace placeholders with your actual values and adjust the code according to your requirements.

Azure Functions

Azure Functions is a serverless solution that allows you to write less code, maintain less infrastructure, and save on costs. Here’s how to set up our basic infrastructure by adding an account and a development environment using Terraform.

# Terraform code for setting up Azure Functions
# Define the provider
provider "azurerm" {
  features {}
}

# Create a resource group
resource "azurerm_resource_group" "rg" {
  name     = "example-resources"
  location = "West Europe"
}

# Create a storage account
resource "azurerm_storage_account" "sa" {
  name                     = "examplestorageacc"
  resource_group_name      = azurerm_resource_group.rg.name
  location                 = azurerm_resource_group.rg.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

# Create an app service plan
resource "azurerm_app_service_plan" "asp" {
  name                = "example-appserviceplan"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name

  sku {
    tier = "Standard"
    size = "S1"
  }
}

# Create a function app
resource "azurerm_function_app" "fa" {
  name                      = "example-functionapp"
  location                  = azurerm_resource_group.rg.location
  resource_group_name       = azurerm_resource_group.rg.name
  app_service_plan_id       = azurerm_app_service_plan.asp.id
  storage_connection_string = azurerm_storage_account.sa.primary_connection_string
}

Let’s dig into the above terraform code and the resources it creates.

  1. Resource group: In Azure, a resource group is a logical container for resources that are deployed within an Azure subscription. This means that all of your resources are organized and can be managed as a group rather than individually. In the code, azurerm_resource_group is used to define a resource group.
  2. Storage account: Azure Storage is a service that provides scalable and secure storage for data in the cloud. A storage account provides a unique namespace in Azure for your data. In the code, azurerm_storage_account is used to define a storage account.
  3. App service plan: In Azure, an App Service plan is a set of compute resources for a web app to run. These compute resources are analogous to the server farm in conventional web hosting. In the code, azurerm_app_service_plan is used to define an app service plan.
  4. Function app: Azure Functions is a serverless compute service that lets you run event-triggered code without having to explicitly provision or manage infrastructure. A function app lets you group functions as a logical unit for easier management, deployment, and sharing of resources. In the code, azurerm_function_app is used to define a function app.

In the provided code, you would replace the placeholders with your actual values to create these resources in your Azure environment. For example, you would replace “example-resources” with the name you want for your resource group, “West Europe” with the Azure region you want to use, “examplestorageacc” with the name you want for your storage account, and so on.

To create the infrastructure, we can simply execute: terraform apply.

output-from-terraform-apply

The output should look like this.

Building the Serverless Web App

Now that we have our tools, let’s start building our serverless web app.

Finding and Testing APIs with RapidAPI

Here is the manual process that you would go through if you are using RapidAPI. Once you have found an API you want to use on RapidAPI, you would typically use the API key you got when you signed up for RapidAPI to authenticate your requests to the API.

  1. Visit the RapidAPI website: Go to RapidAPI. This is a platform where you can find thousands of APIs across various categories.
  2. Search for an API: Use the search bar at the top of the page to find an API that suits your needs. You can search by the name of the API, the functionality you’re looking for, or the category of the API.
  3. Select an API: Click on the API from the search results to view its details. This includes the API’s endpoints, the parameters it accepts, the response it returns, and code snippets in various languages showing how to use the API.
  4. Test the API: On the API page, you can test the API directly. Select the endpoint you want to use, fill in any required parameters, and click the “Test Endpoint” button. RapidAPI will make a request to the API and show you the response.
  5. Get your API key: If you decide to use the API, you’ll need to subscribe to it and get your API key. The API key is used to authenticate your requests to the API. To get your API key, click on your profile picture in the top right corner of the dashboard and then click on “My Apps”. Click on your application (default is “Default Application”) to view your API key.

Here’s a sample Python code snippet showing how to use the API key to request an API on RapidAPI:

import requests

url = "https://weatherapi-com.p.rapidapi.com/current.json"
querystring = {"q": "53.1,-0.13"}
headers = {
    "X-RapidAPI-Key": "your-api-key",
    "X-RapidAPI-Host": "weatherapi-com.p.rapidapi.com"
}

response = requests.get(url, headers=headers, params=querystring)
print(response.json())

In this code snippet, replace “api-name.p.rapidapi.com” with the host of the API you want to use, “api-endpoint” with the endpoint of the API, and “your-api-key” with your actual API key. This will send a GET request to the API and print the response.

example output from code snippet

Example output from code snippet.

Note: Make sure you subscribe to the APIs you are using on RapidAPI

Creating an Azure Function App

Here is Terraform code for creating an Azure Function app and an HTTP trigger function. This will be necessary to create an Azure Function app.

# Define the provider
provider "azurerm" {
  features {}
}

# Create a resource group
resource "azurerm_resource_group" "rg" {
  name     = "example-resources"
  location = "West Europe"
}

# Create a storage account
resource "azurerm_storage_account" "sa" {
  name                     = "examplestorageacc"
  resource_group_name      = azurerm_resource_group.rg.name
  location                 = azurerm_resource_group.rg.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

# Create an app service plan
resource "azurerm_app_service_plan" "asp" {
  name                = "example-appserviceplan"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name

  sku {
    tier = "Standard"
    size = "S1"
  }
}

# Create a function app
resource "azurerm_function_app" "fa" {
  name                       = "example-functionapp"
  location                   = azurerm_resource_group.rg.location
  resource_group_name        = azurerm_resource_group.rg.name
  app_service_plan_id        = azurerm_app_service_plan.asp.id
  storage_connection_string  = azurerm_storage_account.sa.primary_connection_string
}

Below are the components in the code:

  • Provider: Specifies that Azure is the cloud provider.
  • Resource group: A group to hold related resources.
  • Storage account: Required to store function code.
  • App service plan: Defines the set of compute resources for a web app to run.
  • Function app: Hosts the execution of your functions in Azure. It uses the resource group, storage account, and app service plan.

Creating a Simple Web App

Here’s a simple example of a C# Azure Function that calls the OpenWeatherMap API from RapidAPI. This function will be triggered by an HTTP request and will return the current weather for a specified city.

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string city = req.Query["city"];

    using (var client = new HttpClient())
    {
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri($"https://api.openweathermap.org/data/2.5/weather?q={city}&appid=YOUR_API_KEY"),
            Headers =
            {
                { "x-rapidapi-key", "YOUR_RAPIDAPI_KEY" },
                { "x-rapidapi-host", "community-open-weather-map.p.rapidapi.com" },
            },
        };

        using (var response = await client.SendAsync(request))
        {
            response.EnsureSuccessStatusCode();
            var body = await response.Content.ReadAsStringAsync();
            dynamic data = JsonConvert.DeserializeObject(body);
            return new OkObjectResult($"Temperature in {city}: {data.main.temp}°C");
        }
    }
}

In this code:

  • The function is triggered by an HTTP request.
  • It reads the city parameter from the query string.
  • It sends a GET request to the OpenWeatherMap API with the specified city.
  • It reads the API response, deserializes the JSON, and returns the temperature.

Remember to replace “YOUR_API_KEY” with your actual API key from OpenWeatherMap and “YOUR_RAPIDAPI_KEY” with your RapidAPI key. Also, note that you would typically not expose your API keys directly in your code for security reasons. In a real-world scenario, you would store these keys securely in Azure Key Vault or use Managed Identities.

Deploying and Testing the Azure Function App

If you already have an Azure Function App, that’s great! You can skip the creation step and directly deploy your code to the existing Function App. Here’s how you can do it using Azure CLI:

  • Login to Azure: Use the command az login to login to your Azure account from the CLI.
  • Deploy the Function App: Navigate to your local project directory and use the func azure functionapp publish <FunctionAppName> command to deploy your local project to the existing Function App. Replace with the name of your existing Function App.

Here’s a sample script:

# Login to Azure
az login
# Navigate to your local project directory
cd path-to-your-local-function-app
# Deploy the function app
func azure functionapp publish your-existing-function-app-name

Replace “path-to-your-local-function-app” and “your-existing-function-app-name” with your actual values.

example output of a successful upload

Example output of a successful upload.

Testing the Azure Function App

After deploying your function app, you can test it by making an HTTP request to the function’s URL. The URL is usually in the following format: https://<Your Function App>.azurewebsites.net/api/<Your Function Name>?code=<your access code>&name=<Enter a name here>.

Conclusion: Tips and Best Practices

Serverless computing is a different paradigm compared to traditional web development. Understanding its benefits and limitations will help you make the most of it. For example, serverless functions are stateless and have a maximum execution time, which can affect how you design your application. Here are some other tips to consider:

  • Use Terraform for infrastructure as code (IaC): Terraform allows you to define and provide data center infrastructure using a declarative configuration language. This approach enables versioning, reuse, and sharing of configurations, making it easier to manage and scale your applications.
  • Secure your API keys: When using APIs from RapidAPI, always secure your API keys. Do not expose them in client-side code or check them into source control. Consider using Azure Key Vault to store and manage your secrets securely.
  • Handle errors gracefully: Your Azure Functions should handle errors gracefully and return useful error messages to the client. This is especially important when calling APIs, as network issues, API rate limits, and other problems can occur.
  • Optimize your function’s performance: Azure Functions are billed based on execution time, so optimizing your function’s performance can reduce costs. This could involve efficient API usage, optimizing your code, or using Azure’s scaling and deployment slots features.
  • Test your functions locally: Azure Functions Core Tools allow you to run and debug your functions locally before deploying them to Azure. This can speed up development and help catch issues early.
  • Monitor your application: Use Azure Monitor and Application Insights to track how your functions are performing in production. They can provide valuable insights into your application’s performance and usage patterns.
  • Keep learning and exploring: The landscape of serverless computing, APIs, and infrastructure as code is constantly evolving. Keep learning and exploring new features, services, and best practices.

Building serverless web apps with Azure Functions, Terraform, and RapidAPI can be a powerful and efficient way to develop applications. By following these tips and best practices, you can ensure that your applications are secure, scalable, and maintainable. Happy coding! 😊