pythonazureazure-functionsazure-blob-storageazure-http-trigger

Save API JSON Response directly to Azure Blob Storage json file


I am calling to a 3rd party API directly in an Azure HTTP Function. I would like to save the json response to a file inside Azure Blob Storage container. The below code I built (based on microsoft documentation) hangs when I try debugging the Azure Function. When hitting the Azure Function URL endpoint, the above process hangs and never finishes the tasks. Is my code missing something?

import os
import logging
import requests
import azure.functions as func
from azure.storage.blob import BlobServiceClient,BlobClient
import json

def main(req: func.HttpRequest) -> func.HttpResponse:
    connection_string = os.getenv([Azure Blob Storage Connection String])
    file_name = 'SurveySchema.json'
    blob = BlobClient.from_connection_string(conn_str=connection_string, container_name=[container name], blob_name=[name of json file])
    request = requests.get('[The API endpoint that returns json response body]')
    try:
        logging.info(request.text)
        blob.set(str(request.text))
    except ValueError as err:
        logging.info("Error getting data from endpoint, %s", err)

    return func.HttpResponse('Request processed successfully.', status_code=200)

Solution

  • This was an easy fix! I had to use "upload_blob" method from Blob Client library

    import os
    import logging
    import requests
    import azure.functions as func
    from azure.storage.blob import BlobServiceClient,BlobClient
    import json
    
    def main(req: func.HttpRequest) -> func.HttpResponse:
        connection_string = os.getenv([Azure Blob Storage Connection String])
        file_name = 'SurveySchema.json'
        blob = BlobClient.from_connection_string(conn_str=connection_string, container_name=[container name], blob_name=[name of json file])
        request = requests.get('[The API endpoint that returns json response body]')
        try:
            logging.info(request.text)
            **blob.upload_blob(str(request.text))**
        except ValueError as err:
            logging.info("Error getting data from endpoint, %s", err)
    
        return func.HttpResponse('Request processed successfully.', status_code=200)