405 error when trying to delete environment from REST API

I’m trying to delete an Environment using the REST API (through PowerShell Invoke-RESTMethod) but receiving “error 405 method not allowed”. Using the same REST API call I can create the environment (only difference is the HTTP method of POST or DELETE). The same user account is able to delete the environment from the standard HTTP interface, so I don’t believe it’s a permissions issue. Please advise.

Hi there,

Thanks for getting in touch. Could you share us the code snippet you are using to do this?

Thanks,

Dalmiro

Below is the command line that gets generated by a PS script. When specifying a method of “POST”, the command executes successfully and creates a new environment.

Invoke-RESTMethod -URI “http://myoctoserver.mydomain.com/api/environments/?name=ENV123” -ContentType application/json -Headers @{“X-Octopus-ApiKey”=“API-1234567890”} -Method DELETE

When using method of “DELETE” this error is returned:

Invoke-RESTMethod : The remote server returned an error: (405) Method Not Allowed.

Hi,

The problem is that you cannot filter environments using ?name=. You’re gonna need to get all the environments and then filter by name using powershell. This code snippet will help you with what you are trying to do

#Name of the environment to delete
$environmentName = "Env123"

#Getting all environments and filtering by name
$environment = (Invoke-RestMethod -Uri "http://MyOctoserver.mydomain.com/api/environments/all" -Headers @{"X-Octopus-ApiKey"="API123"} -Method Get) | ?{$_.name -eq $environmentName}

#Little error handler
IF($environment){
    Throw "No environments found with name: $environmentName"
}

#Using the id of the selected environment to create the URL for the DELETE
Invoke-RESTMethod -URI "http://MyOctoserver.mydomain.com/api/environments/$($environment.id)" -ContentType application/json -Headers @{"X-Octopus-ApiKey"="API123"} -Method DELETE

Dalmiro - Deleting by EnvironmentID worked perfectly; thanks for your help.