REST API from PowerShell - "POST Method not allowed" - powershell

I am trying to upload one file to BitBucket repository (Git system).
I am trying to send that using the REST API but the error Indicates that POST method is not allowed, although I can of course using the "git push" command to send new files. But if I try to POST the file I am getting this error: "HTTP Status 405 – Method Not AllowedType Status ReportMessage Request method POST not supported"
I am trying to that with this code:
$API_KEY="NDU2"
$uri="https://bitbucket.dev/projects/TEST/repos/faselect/browse/test"
$jsonFile=Get-Content -Raw -Pat C:\Users\john\Downloads\test1.json
Invoke-RestMethod -Uri $uri -Headers #{Authorization="$("Basic {0}" -f $API_KEY)"} -Method Post -Body $jsonFile -ContentType 'application/json'

My approach to this would be to look on PowerShell gallery Powerhell Gallery and see if you can find what you are looking for as a start.. there are several projects that are using this rest api that you could use as an example. here is one that I found on one of those projects:
Ps-bitbucket in Github

Related

Cant' Access API with Powershell but can access using Postman, Python, or cURL

I'm trying to get data back from an API online using Powershell with the command Invoke-WebRequest -UseBasicParsing $request_string -Method Get -Headers $headers) but am getting back Invoke-WebRequest : The remote server returned an error: (403) Forbidden.
I am supplying a $headers dictionary. Strangely, I can access the API using Postman, Python, and cURL. It's only when using Powershell commands that I get the 403 error. In fact, I used Postman's Code Snippet feature to generate my Powershell code, and it still doensn't work! Postman's Powershell Code Snippet was:
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer {removed for security}")
$response = Invoke-RestMethod '{removed for security}' -Method 'GET' -Headers $headers
$response | ConvertTo-Json
To recap, both Invoke-WebRequest and Invoke-RestMethod don't work.
Any help here is much appreciated.
Thanks!
Figured it out on my own.
The API vendor enforced https requirement instead of just http. Apparently, Postman, Python, and cURL can figure that out on their own and change the request accordingly, but Powershell cannot.

How do you add clients to your Clockify workspace with the POST command?

Is there any way of using the POST command in PowerShell to add clients to my Clockify workspace?
Clockify has an API so I wonder how to do this. Anybody has experience with that?
You can use the following command to POST to a REST endpoint:
Invoke-RestMethod -Method POST -Uri 'rest api uri' -Credential 'credentials to endpoint' -Headers 'headers passed' -Body 'Content Body' -ContentType 'text? json? xml?'
For more details: Read the official documentation

Getting a file from BitBucket Rest API v2.0

I have a script which grabs a file from GIT using the bitbucket REST API (1.0) however it has recently stopped working. I'm theorizing this may be due to the v1 REST API being depreciated but I'm not sure.
Anyway I am trying to retrieve the file using the new 2.0 REST API but I can't seem to get the syntax right as the request continually fails.
I'm starting out with curl since its easiest to test. This is what I'm trying:
curl -u myusername#mydomain.com "https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/downloads/Scripts/Environment Setup/test.txt"
Enter host password for user 'myusername#mydomain.com': redacted
{"type": "error", "error": {"message": "Resource not found", "detail": "There is no API hosted at this URL.\n\nFor information about our API's, please refer to the documentation at: https://developer.atlassian.com/bitbucket/api/2/reference/"}}
Here is the reference documentation I am using: https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/downloads/%7Bfilename%7D
Maybe I am using the wrong function? I'm not sure.
For posterities sake, you don't want to use the following to download an individual file from bitbucket:
https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/downloads/path/to/your/file.txt
("Downloads" is to download entire repo files like a .zip file)
Instead you want to do:
curl --user myuser#mydomain.com:password "https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/src/master/path/to/file.txt"
If you're trying to use Invoke-RestRequest (in powershell) note there are some extra steps. With the old 1.0 API you could do:
$cred = Get-Credential
$uri = "https://api.bitbucket.org/1.0/repositories/MyCompany/$($filepath)"
# Get the files from bitbucket (GIT)
Invoke-RestMethod -Credential $cred -Uri $uri -Proxy $proxyUri -OutFile $destination
With the new 2.0 API that no longer works. Powershell's Invoke-RestMethod waits for a 401 response before sending the credentials, and the new 2.0 bitbucket api never provides one, so credentials never get sent causing a 403 forbidden.
To work around that you have to use the following ugly hack to force Invoke-RestMethod to send the credentials immediately in an Authorization header:
$cred = Get-Credential
$uri = "https://api.bitbucket.org/2.0/repositories/MyCompany/$($filepath)"
$username = ($cred.GetNetworkCredential()).username
$password = ($cred.GetNetworkCredential()).password
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
# Get the files from bitbucket (GIT)
Invoke-RestMethod -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Uri $uri -Proxy $proxyUri -OutFile $destination
Hopefully that helps someone else out in the future!
Thanks #Jim Redmond for the help.
You can also use the PowerShell module BitbucketServerAutomation. There's not a ton of cmdlets, they do have Get-BBServerFile and Get-BBServerFileContent. I have found it is well written, very usable and being updated regularly. The Invoke-BBServerRestMethod cmdlet is available if you need a command it doesn't have.

Upload Files to Azure Web App using Kudu Rest API - 409 Error

I'm trying to upload some files to my webapp using Kudu to the below url:
https://($websitename.scm.azurewebsites.net/api/vfs/site/wwwroot/ using powershell
I have obtained the publishing username and password and can authenticate fine
However when i try to upload the files i'm getting the below error using the below code:
function Upload-FileToWebApp($kuduHeader,$KuduURL,$files)
{
$kuduURL = https://$websitename.scm.azurewebsites.net/api/vfs/site/wwwroot/
$result = Invoke-RestMethod -Uri $kuduUrl `
-Headers #{Authorization=$kuduheader;"If-Match"="*"} `
-Method PUT `
-InFile $files `
-ContentType "multipart/form-data"
Invoke-RestMethod : {"Message":"The resource represents a directory which can not be updated."}
I have tried to access this URL using the ARC chrome addin and this brings back the same error '409 conflict Message": "The resource represents a directory which can not be updated."
Get seems to work fine
Thanks in Advance!
The problem is that you are doing a PUT on a directory, which has the semantic of creating the directory, when what you're trying to do is upload a file.
You need to change https://$websitename.scm.azurewebsites.net/api/vfs/site/wwwroot/ to https://$websitename.scm.azurewebsites.net/api/vfs/site/wwwroot/MyFile.txt.
And note that the vfs API can only upload one file at a time. If you want to upload multiple, you can use the zip API. See https://github.com/projectkudu/kudu/wiki/REST-API#zip for details.

How to use Release Definition REST API for VSTS?

I have been successfully able to use Release Definition API on our TFS 2015 Update 3 on prem instance using API Version "3.0-preview.1". But ever since I started testing this on VSTS, I am continuously getting a 404 error stating
Page not found And a long block of HTML.
I am using PowerShell to call the API. And I am creating the API request as mentioned in the documentation using Personal Access Token and Alternate credential method.
https://fabfiber.vsrm.visualstudio.com/DefaultCollection/ff213d65-d61d-447c-b39d-d16f21b18364/_apis/release/definitions?api-version=3.0-preview.1
Can someone let me know if I am missing something.
Try this code:
$vstsAccount = "[your vsts name]"
$user = "test"
$accessToken="[personal access token]"
$teamProject="[team project name]"
Function QueryWorkItem{
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$accessToken)))
$uri="https://$vstsAccount.vsrm.visualstudio.com/defaultcollection/$teamProject/_apis/release/definitions?api-version=3.0-preview.1"
$result = Invoke-RestMethod -Uri $uri -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
}
You may refer the blog :-
https://blogs.msdn.microsoft.com/chandananjani/2016/04/15/using-releasemanagement-rest-apis/
https://blogs.msdn.microsoft.com/chandananjani/2016/04/27/using-releasehttpclient-for-interacting-with-releasemanagement-service/
as well to know as how to use the release management REST API's.