powershellrestfreshdesk

Update contact image Freshdesk API with powershell


Trying to update contacts in Freshdesk with Powershell and simple updates of fields work great. Now I'd like to update the conatacts avatar/image but struggling with multipart/form-data.

I'm using Powershell 7 Core.

this is the code so far

    # Set global variables
$userEmail = "user.name@domain.se"
$myDomain = "domain"
$APIKey = '1234678910111213'
$EncodedCredentials = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $APIKey,$null)))
$HTTPHeaders = @{}
$HTTPHeaders.Add('Authorization', ("Basic {0}" -f $EncodedCredentials))
$jpgfile= 'C:\temp\scripts\Freshdesk\UserName.jpg'

#Get ID for User
$GET_URL = "https://$myDomain.freshdesk.com/api/v2/contacts?email=$userEmail"
$user=Invoke-RestMethod -Method GET -Uri $GET_URL -Headers $HTTPHeaders
$fd_id = $user.id

#Update User
$HTTPHeaders.Add('Content-Type', 'multipart/form-data')

$Image = [convert]::ToBase64String((get-content $jpgfile -AsByteStream))
$Update_URL="https://$myDomain.freshdesk.com/api/v2/contacts/$fd_id"
$UserAttributes = @{}
$customAttributes = @{}
$avatarAttributes = @{}
$UserAttributes.Add('name', 'User Name')
$UserAttributes.Add('job_title' , 'Boss')
$UserAttributes.Add('email' , $userEmail)
$customAttributes.Add('department', 'IT')
$customAttributes.Add('Subdepartment', 'Development')
$UserAttributes += @{'custom_fields' = $customAttributes}
$UserAttributes += @{'avatar' = $image}

$JSON = $UserAttributes | ConvertTo-Json

Invoke-RestMethod -Method PUT -Uri $Update_URL -Headers $HTTPHeaders -Body $JSON

From the API docs at https://developers.freshdesk.com/api/#contacts

This API request must have its Content-Type set to multipart/form-data.

Sample code | Curl
curl -v -u user@yourcompany.com:test -F 'avatar=@/path/to/image.ext' -F 'job_title=Superhero' -X PUT 'https://domain.freshdesk.com/api/v2/contacts/434'

Solution

  • Ok seems you can use -form now in powershell core. Invoke-RestMethod -Method PUT -Uri $Update_URL -Headers $HTTPHeaders -Form @{avatar=(Get-Item $jpgfile)}