COVID-19 Response: Ensure business continuity with scalable IT helpdesk 10 AM PT / 1PM ET Register here

Start a new topic
Solved

API (400) Bad request error

Hi I get this error with my powershell script. How can I fix so the request goes through? 

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

 Here's the script:

 

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 

$APIKey = 'K58O3NlKuIMP2ZFh7BtY'
$EncodedCredentials = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $APIKey,$null)))
$HTTPHeaders = @{}
$HTTPHeaders.Add('Authorization', ("Basic {0}" -f $EncodedCredentials))
$HTTPHeaders.Add('Content-Type', 'application/json')

$URL = 'https://bcservices.freshservice.com/api/v2/tickets'

##########
$TicketAttributes = @{}
$TicketAttributes.Add('requester_id', '15000000000')
$TicketAttributes.Add('email', 'example_email@email.com')
$TicketAttributes.Add('phone', '555-555-5555')
$TicketAttributes.Add('status', '2')
$TicketAttributes.Add('priority', '2')
$TicketAttributes.Add('source', '2')
$TicketAttributes.Add('type', 'incident')
$TicketAttributes = @{'ticket' = $TicketAttributes}
$JSON = ($TicketAttributes | ConvertTo-Json) 

# Invoke the request
Invoke-RestMethod -Method POST -Uri $URL -Headers $HTTPHeaders -Body $JSON

 

I was having this same problem and I just figured it out! Unfortunately PowerShell isn't too friendly when it comes to troubleshooting REST errors, so I installed Ubuntu from the Windows Store so that I could get bash and curl.


When I ran the sample curl command from this page for API v2, it failed with this little message at the end:

{"description":"Validation failed","errors":[{"field":"group_id","message":"It should be of type Positive Integer","code":"missing_field"}]}

 Because we are set up with multiple agent groups, apparently the group_id field is mandatory when creating a ticket through the API. So I was able to modify my PowerShell to the below code and was able to POST a new ticket:

  

# Global Variables

$APIKey = 'your-api-key-here'
$EncodedCredentials = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $APIKey,$null)))
$HTTPHeaders = @{}
$HTTPHeaders.Add('Authorization', ("Basic {0}" -f $EncodedCredentials))
$HTTPHeaders.Add('Content-Type', 'application/json')
$URL = 'https://your-subdomain-here.freshservice.com/api/v2/tickets'

# Ticket Attributes

$TicketAttributes = @{}
$TicketAttributes.Add('email' , 'requester@contoso.com')
$TicketAttributes.Add('subject' , 'Ticket from PowerShell')
$TicketAttributes.Add('description' , 'This ticket was successfully created from PowerShell.')
$TicketAttributes.Add('status' , 2)
$TicketAttributes.Add('priority' , 2)
$TicketAttributes.Add('group_id' , 0000)

# Convert Attributes and POST

$JSON = $TicketAttributes | ConvertTo-Json 
Invoke-RestMethod -Method POST -Uri $URL -Headers $HTTPHeaders -Body $JSON

  

Login or Signup to post a comment