Cannot Parse JSON in Azure Function

I work for a MSP and am currently working on creating an automation process for offboarding employees for all of our clients. Currently, I am using Pipedream to receive HTTP requests and then execute code on what is received before sending it to Azure Functions. I have to use PowerShell to convert mailboxes to shared mailboxes as this is not supported by the Graph API and my reason for needing Azure Functions. The issue I am running into is that the Azure Function cannot parse the JSON that I am sending it from Pipedream. Therefore, no mailbox is ever converted to shared. I have created multiple different Python scripts and verified that it is sending what I want. The function key is included in the URL so that should not be causing any issues. I have also tested the mailbox conversion portion of the Azure Function and know that it works. I just need it to be able to actually use the JSON I am sending it. Any advice on what I may need to add to the Azure Function in dependencies or in the function itself would be greatly appreciated. I have pasted the code snippets below. The Azure Function URL and the other things have been replaced by *** for obvious security reasons. The JSON body being sent is:

{
“Name”: “***”
}

Here is the Python code for sending a HTTP request to the Azure Function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import requests
import json
def handler(pd: "pipedream"):
url = "***"
headers = {
"Content-Type": "application/json"
}
username_value = pd.steps["create_username"]["$return_value"]["username"]
payload = {
"Name": username_value
}
response = requests.post(url, headers=headers, json=payload)
print("Payload being sent:", json.dumps(payload))
print("Status Code:", response.status_code)
print("Response Body:", response.text)
</code>
<code>import requests import json def handler(pd: "pipedream"): url = "***" headers = { "Content-Type": "application/json" } username_value = pd.steps["create_username"]["$return_value"]["username"] payload = { "Name": username_value } response = requests.post(url, headers=headers, json=payload) print("Payload being sent:", json.dumps(payload)) print("Status Code:", response.status_code) print("Response Body:", response.text) </code>
import requests
import json

def handler(pd: "pipedream"):
    url = "***"
    headers = {
        "Content-Type": "application/json"
    }
    
    username_value = pd.steps["create_username"]["$return_value"]["username"]
    payload = {
      "Name": username_value
    }
    
    response = requests.post(url, headers=headers, json=payload)
    
    print("Payload being sent:", json.dumps(payload))
    print("Status Code:", response.status_code)
    print("Response Body:", response.text)

Here is the Azure Function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
# Add initial logging
Write-Host "Function triggered"
# Variables for OAuth 2.0 authentication
$tenantId = "***"
$clientId = "***"
$clientSecret = "***"
$tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
# Log the raw request body
Write-Host "Raw Request Body: $($Request.Body)"
# Try to parse the JSON request body
try {
$requestBody = $Request.Body | ConvertFrom-Json
}
catch {
Write-Host "Failed to parse JSON: $_"
return
}
# Extract the "Name" value from the JSON request
$name = $requestBody.Name
# Log the extracted name value
Write-Host "Extracted Name: $name"
# Ensure that $name has a value
if (-not [System.String]::IsNullOrEmpty($name)) {
Write-Host "Name parameter received: $name"
try {
Write-Host "Obtaining access token"
$body = @{
grant_type = "client_credentials"
scope = "https://outlook.office365.com/.default"
client_id = $clientId
client_secret = $clientSecret
}
$tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -ContentType "application/x-www-form-urlencoded" -Body $body
$accessToken = $tokenResponse.access_token
Write-Host "Access token obtained successfully."
# Connect to Exchange Online using the obtained access token
Write-Host "Connecting to Exchange Online"
Connect-ExchangeOnline -AppId $clientId -AccessToken $accessToken -Organization $tenantId -ShowBanner:$false
# Convert the mailbox to shared
Write-Host "Converting mailbox to shared: $name"
Set-Mailbox -Identity $name -Type Shared -ErrorAction Stop
Write-Host "Mailbox converted to shared successfully."
}
catch {
Write-Host "Error during script execution: $_"
}
}
else {
Write-Host "Name parameter is missing or empty in the JSON request."
}
Write-Host "Script execution completed."
</code>
<code>using namespace System.Net # Input bindings are passed in via param block. param($Request, $TriggerMetadata) # Add initial logging Write-Host "Function triggered" # Variables for OAuth 2.0 authentication $tenantId = "***" $clientId = "***" $clientSecret = "***" $tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" # Log the raw request body Write-Host "Raw Request Body: $($Request.Body)" # Try to parse the JSON request body try { $requestBody = $Request.Body | ConvertFrom-Json } catch { Write-Host "Failed to parse JSON: $_" return } # Extract the "Name" value from the JSON request $name = $requestBody.Name # Log the extracted name value Write-Host "Extracted Name: $name" # Ensure that $name has a value if (-not [System.String]::IsNullOrEmpty($name)) { Write-Host "Name parameter received: $name" try { Write-Host "Obtaining access token" $body = @{ grant_type = "client_credentials" scope = "https://outlook.office365.com/.default" client_id = $clientId client_secret = $clientSecret } $tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -ContentType "application/x-www-form-urlencoded" -Body $body $accessToken = $tokenResponse.access_token Write-Host "Access token obtained successfully." # Connect to Exchange Online using the obtained access token Write-Host "Connecting to Exchange Online" Connect-ExchangeOnline -AppId $clientId -AccessToken $accessToken -Organization $tenantId -ShowBanner:$false # Convert the mailbox to shared Write-Host "Converting mailbox to shared: $name" Set-Mailbox -Identity $name -Type Shared -ErrorAction Stop Write-Host "Mailbox converted to shared successfully." } catch { Write-Host "Error during script execution: $_" } } else { Write-Host "Name parameter is missing or empty in the JSON request." } Write-Host "Script execution completed." </code>
using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Add initial logging
Write-Host "Function triggered"

# Variables for OAuth 2.0 authentication
$tenantId = "***"
$clientId = "***"
$clientSecret = "***"
$tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

# Log the raw request body
Write-Host "Raw Request Body: $($Request.Body)"

# Try to parse the JSON request body
try {
    $requestBody = $Request.Body | ConvertFrom-Json
}
catch {
    Write-Host "Failed to parse JSON: $_"
    return
}

# Extract the "Name" value from the JSON request
$name = $requestBody.Name

# Log the extracted name value
Write-Host "Extracted Name: $name"

# Ensure that $name has a value
if (-not [System.String]::IsNullOrEmpty($name)) {
    Write-Host "Name parameter received: $name"

    try {
        Write-Host "Obtaining access token"
        $body = @{
            grant_type    = "client_credentials"
            scope         = "https://outlook.office365.com/.default"
            client_id     = $clientId
            client_secret = $clientSecret
        }
        $tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -ContentType "application/x-www-form-urlencoded" -Body $body
        $accessToken = $tokenResponse.access_token

        Write-Host "Access token obtained successfully."

        # Connect to Exchange Online using the obtained access token
        Write-Host "Connecting to Exchange Online"
        Connect-ExchangeOnline -AppId $clientId -AccessToken $accessToken -Organization $tenantId -ShowBanner:$false

        # Convert the mailbox to shared
        Write-Host "Converting mailbox to shared: $name"
        Set-Mailbox -Identity $name -Type Shared -ErrorAction Stop
        Write-Host "Mailbox converted to shared successfully."
    }
    catch {
        Write-Host "Error during script execution: $_"
    }
}
else {
    Write-Host "Name parameter is missing or empty in the JSON request."
}

Write-Host "Script execution completed."

Here is the requirements file for the Azure Function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
# For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'.
# To use the Az module in your function app, please uncomment the line below.
# 'Az' = '12.*'
'ExchangeOnlineManagement' = '3.*'
'PowerShellGet' = '2.*'
'PackageManagement' = '1.*'
}
</code>
<code># This file enables modules to be automatically managed by the Functions service. # See https://aka.ms/functionsmanageddependency for additional information. # @{ # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. # To use the Az module in your function app, please uncomment the line below. # 'Az' = '12.*' 'ExchangeOnlineManagement' = '3.*' 'PowerShellGet' = '2.*' 'PackageManagement' = '1.*' } </code>
# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
    # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. 
    # To use the Az module in your function app, please uncomment the line below.
    # 'Az' = '12.*'
    'ExchangeOnlineManagement' = '3.*'
    'PowerShellGet' = '2.*'
    'PackageManagement' = '1.*'
}

Thank you for taking the time to read this and any help is greatly appreciated.

Here are the invocation details for the function:

8/8/2024, 12:24:36 PM
Information
Executing ‘Functions.Convert_to_Shared_Mailbox’ (Reason=’This function was programmatically called via the host APIs.’, Id=97bb041f-a775-4091-ad9e-aeb8314dc193)

8/8/2024, 12:24:37 PM
Information
INFORMATION: Function triggered

8/8/2024, 12:24:37 PM
Information
INFORMATION: Raw Request Body: System.Management.Automation.OrderedHashtable

8/8/2024, 12:24:37 PM
Information
INFORMATION: Failed to parse JSON: Conversion from JSON failed with error: Unexpected character encountered while parsing value: S. Path ”, line 0, position 0.

8/8/2024, 12:24:37 PM
Information
Executed ‘Functions.Convert_to_Shared_Mailbox’ (Succeeded, Id=97bb041f-a775-4091-ad9e-aeb8314dc193, Duration=1104ms)

New contributor

CodeWithClark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật