Uploading Image in Azure Blob via Azure Function and API Management Service

Introduction

This article demonstrates steps by step process to upload images in azure blob via Azure Function and API Management Service. This step-by-step process will help any developer who wants to upload an image in Azure Blob via an Azure function with C#. Wants to use the Azure API Management Service and expose the APIM endpoint to the end user. The APIM endpoint will internally point to the Azure function.

So we are going to discuss the following steps,

Step 1. Creating Azure function in Visual Studio 2022. Create a new project in Visual Studio using the “Azure Functions (C#)” template.

Azure Function

Keep the settings as shown in the below screenshot.

Azure Function

Rename the Function1 class as “TestPostImage”. Open the TestPostImage.cs file and replace the Run function inside the class with the below code.

[FunctionName("TestPostImage")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest 
req, ILogger log)
{
    try
    {
        string Connection = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
        string containerName = Environment.GetEnvironmentVariable("ContainerName");
        Stream myBlob = new MemoryStream();
        var file = req.Form.Files["File"];
        myBlob = file.OpenReadStream();
        var blobClient = new BlobContainerClient(Connection, containerName);
        var blob = blobClient.GetBlobClient(file.FileName);
        await blob.UploadAsync(myBlob,overwrite:true);
        var url = blob.Uri;
        return new OkObjectResult(url);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Install the NuGet package “Azure.Storage.Blobs” and resolve any errors appearing after pasting the function with appropriate using statements variables are being referred in the newly pasted function, which will have their Value defined in the File local. settings,json file.

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "Storage-Account connectionstring",
    "ContainerName": "testcontainer",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  }
}

Later, we will create the Azure Blob Storage and Container and fill in those details in the 2 variables local. settings,json file.

Step 2. Get access to an Azure account or create a Free Azure account.

We can get Free access to Azure by using our credit card, which gives a $200 credit limit and is enough for this trying current example Or we can subscribe/Activate the  $50 Azure credit from an MSDN subscription if we have one.

Step 3. Creating Azure Function App in Azure

Search for the Resource “Function App”.

Azure

  1. Click Create in the top Menu once you land on the Function App page.
  2. Fill in all details in the Form for creating a Function App.
    • Subscription: Choose the free Subscription and the one you have purchased.
    • Resource Group: Create a Resource Group here since this may be the first time, and you will need this later.
    • Function App Name: FRBSFunctionApp.
    • Runtime Stack: .Net.
    • Version: 6 (LTS).
    • Region: EAST US.
    • OS: Windows.
    • Hosting Option and Plan: Consumption should be fine for the current example.
    • Leave the remaining options in all other tabs as a default and click on Create. Finally, after completing all steps, we get a Function App created, as shown below. I created a Function App, “FRBSFunctionApp”.

Create

Step 4. Creating Azure Storage Account and Container

Search for the resource “Storage” and click on the option “Storage Account”.

Storage

  1. Click on Create.
  2. Choose the
    • Subscription
    • Same resource group as the one created for “Function App”.
    • Storage Account Name: ImageUploadTestAccount.
    • Leave the remaining options as default, and click on the “Create” button in the last Review tab.

Create

Create the Container in the Azure Storage Account to store the images. Within the Storage Account, search for the option “Containers” and then click on “+ Container”.

Images

Provide a container Name “testcontainer” and leave the public access level as Private and click the Create button.

  New container

Find the Storage Account connection string and replace it in the Azure Function created earlier.

  • Search for the “Access Keys” option in the Storage Account.
  • Inside Access Keys, look for Key 1 and the connection string.
  • Copy the connection string and paste it against the key “AzureWebJobsStorage” in the local.settings.json.

Step 5. Publishing the Azure function in the Azure Function App.

  1. We all understand that the function created in Step 1 is the core function we need to deploy in Azure.
  2. One way to deploy this function is directly publishing via the Visual Studio Publish feature.
  3. So open the Azure Function project created in Step 1.
  4. After a successful build, click on the Publish option by right-clicking the project in the solution explorer. 
  5. Select/Enter all necessary details to reach the Azure Function App option. On the first screen in the wizard, select “Azure”. Then Sign into your Azure account and complete step by step process to push the function in the newly created function App.
  6. Once the above step is successful, go ahead and check the resource “Function App” in Azure and go to the “Functions” option inside, and you can see the newly deployed function.

Step 6. Creating Azure API Management Service

Search for the API Management (APIM) resource and click on Create, to create API Management Service.

Azure

Choose the standard options for creating the APIM resource.

  • Select the same Subscription as selected for other resources.
  • Select the same Resource Group.
  • Region East US.
  • Resource Name: APIMBlobServiceTest1234
  • Organization Name: Your company name.
  • Administrator Email: your company email.
  • Remaining options – keep as is and click on the Review tab “Create”.

API

Create a Product in APIM,

  1. Click on the “Products” option inside the newly created APIM resource.
  2. Click on Add,
    • Display Name: NewImageProduct.
    • Description: To add Azure function to access BLOB.
    • Leave the remaining blank and click on Create button

Step 7. Creating the API to Post images via Azure API Management Service

  1. Click on the option “APIs&rdquo.
  2. On the right-hand side, click on “Function App&rdquo.

API

  • Select the Browse button below “Please select Function App” and select the same Function App created earlier.
  • A screen will appear with all functions which have been published in that function App. Select the check box for the specific function name “TestPostImage”. Since we have only published 1 function yet, then click on the “select” button below. So now we are back to the previous screen to fill remaining details as mentioned below.
  • Display Name: PostMediaAPI.
  • Name: PostMediaAPI.
  • Products: Select the same Product created above.
  • Click on Create.
  • Once API is created, get the API endpoint and token from the “Test” option for the API and store it in a notepad. The API has 2 methods, i.e., Get and Post. In this case, click on the Post method and then click on the Test option. If you scroll to the bottom of the Test section, then the link with the token is visible.

Step 8. Test the Post API endpoint from Postman

  1. Create a new Request of type POST.
  2. Paste the Post API URL (created in the previous step) in the main URL text box.
  3. Click on the Body option and select the “Form-Data” radio button, then in Key, select “File” and browse the Image you want to upload in the Value.
  4. In the Headers section, add a new Key for “Ocp-Apim-Subscription-Key” and in Value, paste the Value you have retrieved in the previous step while creating the Post API.
  5. If all steps are completed, then you click on Send button.
  6. If all goes well, the File will be sent to Azure Blob via the API, and in return, you should see the Azure Blob Image URL in the Response section.

   Post

P

Summary

In this article, I discussed how we can create an Azure function in Visual Studio and publish it. We saw the usage of Azure Blob Storage which can store the images uploaded via the Azure function. I introduced an additional concept of API Management Service and linked it to the Azure function.