Freshdesk API - Contacts Import with PowerShell

Hello,
I’m trying to Import Contacts using the V2 API and PowerShell. I can get it working with curl, but there appears to be a problem with how I am structuring the multipart form in PS. Any help is appreciated!

Here is my code:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::TLS12

$APIKey = $(Get-Content -Path Z:\Freshdesk\token.txt)
$Auth = "$($APIKey):X"
$Bytes = [System.Text.Encoding]::ASCII.GetBytes($Auth)
$Base64 = [System.Convert]::ToBase64String($Bytes)
$BasicAuth = "Basic $Base64"

$Headers = @{ Authorization = $BasicAuth }

$URI = 'https://myDomain.freshdesk.com/api/v2/contacts/imports'

$FilePath = 'C:\data\20220815-FreshdeskUsers.csv'

$Form = [ordered]@{
    file = Get-Item -Path $FilePath
    name = '0'
    email = '1'
    title = '2'
}

Invoke-WebRequest -Uri $URI -Headers $Headers -Method POST -Body $Form -ContentType 'multipart/form-data'

The API response:

Invoke-WebRequest : The remote server returned an error: (400) Bad Request.

And debug:

Invoke-WebRequest: Z:\Freshdesk\test.ps1:22
Line |
  22 |  Invoke-WebRequest -Uri $URI -Headers $PostHeaders -Method POST -Body  …
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | {"description":"Validation failed","errors":[{"field":"name","message":"Unexpected/invalid field in
     | request","code":"invalid_field"},{"field":"email","message":"Unexpected/invalid field in
     | request","code":"invalid_field"},{"field":"title","message":"Unexpected/invalid field in
     | request","code":"invalid_field"}]}

Thank you

Hi @Jesse, welcome to the community!

Looks like you’ll have to change the order of the fields here:

According to the docs for Trigger A Contact Import, the name, email, and title fields should be nested under a field named fields. I do not know how to represent this in Powershell.

This is the corresponding cURL command from the docs. Look at how the email and name fields are nested under fields[]:

curl -v -u abracadabra:X -H 'Content-Type: multipart/form-data' -F "file=@sample.csv" -F "fields[name]=0" -F "fields[email]=2" POST 'https://domain.freshdesk.com/api/v2/contacts/imports'
2 Likes