Upload artifact using Nexus API with PowerShell - powershell

Does anybody know what the request body looks like if I want to use Nexus API to upload artifact to a repo?
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("admin123:password123"))
$header = #{authorization = "Basic $token" }
$body = #{
'raw.dictionary' = '/TestArtifact/Prod/'
'raw.asset1' = 'c:\temp\lenovo.zip'
'raw.asset1.filename' = 'lenovo.zip'
} | Convertto-Json
Invoke-RestMethod -Method POST -Uri 'http://xx.xx.xxx.xxx:8081/service/rest/v1/components?repository=TestRepo' -ContentType 'application/json'-Body $body -Headers $header
I'm getting 'Invoke-RestMethod: Response status code does not indicate success: 415 (Unsupported Media Type)'

Lets try and figure this out.
The command looks like you are trying to do is
curl -v -u admin:admin123 -X POST 'http://localhost:8081/service/rest/v1/components?repository=maven-releases' -F maven2.groupId=com.google.guava -F maven2.artifactId=guava -F maven2.version=24.0-jre -F maven2.asset1=#guava-24.0-jre.jar -F maven2.asset1.extension=jar -F maven2.asset2=#guava-24.0-jre-sources.jar -F maven2.asset2.classifier=sources -F maven2.asset2.extension=jar
It looks like the main issue we have is that you didnt convert the file to bytes.
-F #[FileName] is a Binary File
The only change really needing to be done was changing
'raw.asset1' = 'c:\temp\lenovo.zip'
to
'raw.asset1' = [System.IO.File]::ReadAllBytes("c:\temp\lenovo.zip")

Related

How to upload a file as binary data while using RestAPI through powershell like we use --data-binary in curl

I'm trying to upload a file on an API using RESTAPI method and using powershell task in Azure DevOps.
I'm able to upload the file but still there is some issue with the file.
I'm now trying to upload this file as a binary file on that API but I'm not getting how to upoad the file as a binary.
While using curl , we have an option --data-binary but how can we use this option in powershell method. Please guide.
Below is the code:
$Url = 'https://example.com/FileUploadSet'
$Path = 'D:\a\r1\a/_ci/drop/s/test.mtar'
$Body = #{
"path" = "$Path"
} | ConvertTo-Json
$headers = #{
'ContentType' = 'application/octet-stream'
'Accept' = '*/*'
'APIKey' = $env:API
}
curl -Uri $Url -Method Post -body $Body -Headers $headers

Upload file to API endpoint with PowerShell using multipart/form-data

This curl command works:
curl -v -X POST https://subdomain.playvox.com/api/v1/files/upload?context=quality -H "Content-Type: multipart/form-data" -u [username]:[password] -F file=#c:\path\to\file.wav
But I am unable to perform the same thing in PowerShell using the Invoke-RestMethod cmdlet. Here's my attempt:
$file_contents = [System.IO.File]::ReadAllBytes($($file_path))
Invoke-RestMethod -Uri "https://subdomains.playvox.com/api/v1/files/upload?context=quality" -Method Post -ContentType "multipart/form-data" -Headers #{ "Authorization" = "Basic $($playvox_base64_auth)" } -Body #{ file = $file_contents }
When run the API responds with invalid_param, "file" is required. However I confirmed the call to ReadAllBytes succeeds and gives back the raw file data. It seems like PowerShell is not sending the request body in the right format? I've looked at several other answers here and documentation online and nothing I found has worked.
Discovered there is a -Form parameter in Powershell 6 and later. I updated my powershell and used the following instead:
$file_contents = Get-Item $file_path
Invoke-RestMethod -Uri "https://subdomains.playvox.com/api/v1/files/upload?context=quality" -Method Post -ContentType "multipart/form-data" -Headers #{ "Authorization" = "Basic $($playvox_base64_auth)" } -Form #{ file = $file_contents }
And it worked.

Equivalent curl -F in PowerShell Invoke-webrequest

I'm trying to find the equivalent of this curl command in PowerShell with Invoke-webrequest :
curl -k https://url/api \
-H "Authorization: mykey" \
-F "json=#test.json;type=application/json" \
-F "file=#test.txt; type=application/octet-stream"```
-H is ok, but I didn't find for two -F option.
Any idea ?
Many thanks.
The -f switch in cUrl is used for a multi-part formdata content type. PowerShell fortunately natively supports it, here's a generic example to get you started.
$Uri = 'https://api.contoso.com/v2/profile'
$Form = #{
firstName = 'John'
lastName = 'Doe'
email = 'john.doe#contoso.com'
avatar = Get-Item -Path 'c:\Pictures\jdoe.png'
birthday = '1980-10-15'
hobbies = 'Hiking','Fishing','Jogging'
}
$Result = Invoke-WebRequest -Uri $Uri -Method Post -Form $Form
And for your specific scenario, something like this should get you moving in the right direction.
$url = 'https://url/api'
$Form = #{
json = Get-Content .\test.json
file = Get-Content .\test.txt
}
$Result = Invoke-WebRequest -Uri $Uri -Method Post -Form $Form -Token "mkey"
It seems like you should be able to do -Form ... -Form ... but you can't, you need to build a multipart form object to submit.
see example 5 of the Microsoft docs https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.1
or this https://stackoverflow.com/a/65093133/89584 answer
or just install curl on windows (https://stackoverflow.com/a/16216825/89584) and use curl's nicer API

Converting Curl API Call to Invoke-WebRequest in PowerShell 5

I have done a bunch of searches, but nothing so far as helped me solve this. Any help is appreciated.
I am trying to convert a curl command to Invoke-WebRequest, but for some reason I am not getting a response back. I have tried:
$headers = #{
outh_a = "WEBREQ";
oauth_key = "key";
etc...
}
Invoke-WebRequest -Uri $url -Method POST -Body "{}" -Headers $headers -Verbose
The curl command looks like this:
.\curl.exe -x POST -d "{}" -H "oauth_a: WEBREQ" -H "oauth_key:key" -H "Content-Type: application/json" -H "oauth_sm:HMAC-SHA2" -H "oauth_t:timestamp"-H "oauth_s:key+signature=" "https://example.com/services/api/request?t=data&a=data2&n=404&i=0"
The command works perfectly and returns the data. I am using PowerShell as we want to parse through the data once received. Any help is greatly appreciated.
The curl command will fail if I submit it without -d "{}", so that part is required. The server I guess is expecting to receive a specific amount of data.
I am not sure what is going on to prevent a response. I have tried curl from the same machine I am doing the PowerShell script on and it works. I even used SoapUI to make the same call and it works there too.
Edit:
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[System.Net.WebRequest]::DefaultWebProxy.Credentials =
[System.Net.CredentialCache]::DefaultCredentials
[Net.ServicePointManager]::SecurityProtocol =
[Net.SecurityProtocolType]::Ssl3, [Net.SecurityProtocolType]::Tls,
[Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls12
$Domain = "https://example.com/services/api/request?t=oauth_auth_token&a=appid&n=404&i=0"
# OAUTH Authorization Request Header
$Header = #{
o_nonce = 'TEST'
o_con_key = 'key'
o_sig_meth = 'type'
o_timestamp = 'timestamp'
o_sig = 'signature'
o_ver = '1.0'
o_realm = 'http://example.com/services'
}
$Body = #{}
$API_Response = Invoke-RestMethod -Method POST -Headers $Header -Uri $Domain -Body $Body -Verbose -TimeoutSec 20
Update:
#MikeW I'd have to look at your PS code in more detail, could you post the entire API call minus the sensitive information (api key etc...)?
Also, on a side note, sometimes just passing the parameters on the URI works just as well. Have you tried passing the parameters through the URI? You can see the following example of an API call I'm making using just the URI:
Invoke-RestMethod -Uri ("$EndpointURL/Tickets/$TicketID/?username=$ServiceAccount&apiKey=$APIKey");

convert curl command to invoke-WebRequest or Invoke-RestMethod

I have a requirement to convert a working curl command to Invoke-WebRequest command
The command is used to create a project in SonarQube
Curl:
curl -u as123123112312: -X POST "http://sonarqube.it.company.net:9000/api/projects/create?key=%project_key%&name=%project_name%" > NUL
the command I tried:
$e = #{
Uri = "http://sonarqube.it.company.net:9000/api/projects/create?key=%project_key%&name=%project_name%"
Headers = #{"Authorization" = "Token as123123112312"}
}
Invoke-WebRequest #e -Method POST
Error:
Invoke-WebRequest : The remote server returned an error: (401) Unauthorized
Does anyone have an idea of converting curl to invoke-webrequest
This has been asked before. When you are posting, you need to have a body to send too, example:
$username = "as123123112312";
$password = "blah";
$Bytes = [System.Text.Encoding]::UTF8.GetBytes("$username`:$password");
$encodedCredentials = [System.Convert]::ToBase64String($bytes);
$body = "your content (i.e. json here)";
Invoke-WebRequest -Method Post -Body $body -Headers #{ "Authorization" = "Basic " + $encodedCredentials} -Uri "http://sonarqube.it.company.net:9000/api/projects/create?key=%project_key%&name=%project_name%"