Executing a PATCH api call from powershell - json

I'm trying to run the following API 'Patch' command from powershell which I'm looking to execute a release in Azure DevOps ...
$deploy = Invoke-RestMethod -Uri $patchurl -Method Patch -Body $body -Headers $header -ContentType "application/json-patch+json"
The url example is below
https://vsrm.dev.azure.com/test/Fixed%20Income/_apis/Release/releases/567/environments/1072?api-version=6.0-preview.6
The body of the patch call is ...
"Status": "inProgress",
"scheduledDeploymentTime": null,
"comment": null,
"variables": {}
Running the invoke command from powershell returns the following response ...
Invoke-RestMethod : {"$id":"1","innerException":null,"message":"TF400898: An Internal Error Occurred. Activity Id:
759888ab-9828-4cb6-ba2f-e90cde1cd39a.","typeName":"System.Web.Http.HttpResponseException, System.Web.Http","typeKey":"HttpResponseException","errorCode":0,"eventId":0}
When I run the same url to run a 'patch' request from Postman I get the below response, which is what I'm expecting to get from Powershell.
"$id": "1",
"innerException": null,
"message": "TF400813: The user '' is not authorized to access this resource.",
"typeName": "Microsoft.TeamFoundation.Framework.Server.UnauthorizedRequestException, Microsoft.TeamFoundation.Framework.Server",
"typeKey": "UnauthorizedRequestException",
"errorCode": 0,
"eventId": 3000
Any ideas what I'm doing wrong?

According to your description, when you call this REST API from Postman, the response returns an error: "message": "TF400813: The user" is not authorized to access this resource." The cause of this problem is incorrect authorization.
Please create a new personal access token in the organization first, then select the type: Basic Auth in the Authorization tab, and type your PAT in the password input box on the right.
When you call this REST API from powershell, the response returns an error: "TF400898: An Internal Error Occurred. Activity Id: 759888ab-9828-4cb6-ba2f-e90cde1cd39a." The cause of this problem is Content- Type is incorrect.
Please use ContentType "application/json" instead of ContentType "application/json-patch+json" .
Script template:
$token = "PAT"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$url3="https://vsrm.dev.azure.com/{organization}/{project}/_apis/Release/releases/{releaseId}/environments/{environmentId}?api-version=6.0-preview.6"
$body = "{
`"status`": `"inProgress`",
`"scheduledDeploymentTime`": null,
`"comment`": null,
`"variables`": {}
}"
$response3 = Invoke-RestMethod -Uri $url3 -Headers #{Authorization = "Basic $token"} -Method Patch -Body $body -ContentType application/json
Please refer to the following steps to create a PAT:
From your home page, open your user settings, and then select Personal access tokens.
From your home page, open your user settings, and then select Personal access tokens. Name your token, select the organization where you want to use the token, and then choose a lifespan for your token. Select Create.
When you're done, make sure to copy the token. For your security, it won't be shown again. Use this token as your password.

Related

Unauthorized to get list of terminals

I'm getting a 401 Unauthorized error when trying to use the management API to get a list of terminals. I'm using PowerShell Invoke-RestMethod.
Here's what I'm trying to run:
$Key = [API Key]
$Headers = #{'Content-Type' = 'application/json'; 'X-API-Key' = $Key}
$Uri = "https://management-test.adyen.com/v1/terminals"
Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers
Result is this:
Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.
At line:1 char:1
+ Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
The API library states that the API Credential must have the 'POS Terminal Management API' and 'Management API—Terminal settings read' roles assigned, which it does.
I do get a success code when I try the API to get company account, so I know the API key works. Is there something else I'm missing?
I was able to access /v1/terminals after granting also the PSP Terminal Action Management API role.
Assign to the API credential that owns the API Key the following roles:
POS Terminal Management API
Management API—Terminal settings read
PSP Terminal Action Management API

Trying to make a POST request, works with cURL, get a 403 when using Python requests

I'm trying to get some JSON data from this API - https://ped.uspto.gov/api/queries
This cURL request works fine and returns what is expected:
curl -X POST "https://ped.uspto.gov/api/queries" -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"searchText\":\"*:*\", \"fq\":[ \"totalPtoDays:[1 TO 99999]\", \"appFilingDate:[2005-01-01T00:00:00Z TO 2005-12-31T23:59:59Z]\" ], \"fl\":\"*\", \"mm\":\"100%\", \"df\":\"patentTitle\", \"facet\":\"true\", \"sort\":\"applId asc\", \"start\":\"0\"}"
I have this python script to do the same thing:
from requests.structures import CaseInsensitiveDict
import json
url = "https://ped.uspto.gov/api/queries"
headers = CaseInsensitiveDict()
headers["accept"] = "application/json"
headers["Content-Type"] = "application/json"
data = json.dumps({
"searchText":"*:*",
"fq":[
"totalPtoDays:[1 TO 99999]",
"appFilingDate:[2005-01-01T00:00:00Z TO 2005-12-31T23:59:59Z]"
],
"fl":"*",
"mm":"100%",
"df":"patentTitle",
"facet":"true",
"sort":"applId asc",
"start":"0"
})
resp = requests.post(url, headers=headers, data=data)
print(resp.status_code)
but it returns a 403 error code and the following response header:
"Date":"Mon, 24 Oct 2022 16:13:58 GMT",
"Content-Type":"text/html",
"Content-Length":"919",
"Connection":"keep-alive",
"X-Cache":"Error from cloudfront",
"Via":"1.1 d387fec28536c5aa92926c56363afe9a.cloudfront.net (CloudFront)",
"X-Amz-Cf-Pop":"LHR50-P8",
"X-Amz-Cf-Id":"RMd69prehvXNAl97mo0qyFtuBIiY8r9liIxcQEmbdoBV1zwXLhirXA=="
I'm at quite a loss at what to do, because I really don't understand what my Python is missing to replicate the cURL request.
Thanks very much.
I was interested in this. I got an account with uspto.gov and acquired an access key. Their other API's work well. But the PEDS API? I kept getting the Cloudflare Gateway Timeout 503 error. While I was on their website, I looked into the PEDS API, I could not load any link to a https://ped.uspto.gov page.
I called them and they gave me an email address. I got this reply:
The PEDS API was taken down, because repeated data mining was bringing the entire PEDS System down.
The PEDS Team is working on a solution to fix the PEDS API, so that it can be re-enabled.
I tried it using PHP.
Cloudflare has been causing a lot of problems for curl.
I got a timeout.
I may have gotten past the 403 Forbidden, but did not have credentials and so the server dropped the connection.
An HTTP 504 status code (Gateway Timeout) indicates that when
CloudFront forwarded a request to the origin (because the requested
object wasn't in the edge cache), one of the following happened: The
origin returned an HTTP 504 status code to CloudFront. The origin
didn't respond before the request expired.
AWS Cloudflare Curl Issues
bypassing CloudFlare 403
How to Fix Error 403 Forbidden on Cloudflare
403 Forbidden cloudflare
██████████████████████████████████████████████████████████████
This is a conversion from you curl.
The Content-Type:application/data is added by default when you send JSON data.
I do not know about your json_data.dump or you putting the JSON in parentheses.
import requests
headers = {
'accept': 'application/json',
}
json_data = {
'searchText': '*:*',
'fq': [
'totalPtoDays:[1 TO 99999]',
'appFilingDate:[2005-01-01T00:00:00Z TO 2005-12-31T23:59:59Z]',
],
'fl': '*',
'mm': '100%',
'df': 'patentTitle',
'facet': 'true',
'sort': 'applId asc',
'start': '0',
}
response = requests.post('https://ped.uspto.gov/api/queries', headers=headers, json=json_data)

Can't create webhook through v2 api endpoint

I am trying to dispatch webhook create endpoint and getting 403 Forbidden response code with no error information in body. My request looks like:
POST /v2/apps/618ce23498488b00e1582723/integrations/618ce235a6ccf400e1a4b992/webhooks HTTP/1.1
Host: api.smooch.io
Content-Type: application/json
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6ImFwcF82MThjZTIzNGZiYTk5MDAwZTFiZDgyYWMifQ.eyJzY29wZSI6ImFwcCJ9.hXigeREGoUQ8YtM_gPUXfgWEGumbnlbBNLk_*******
Content-Length: 120
{
"target": "https://example.com/inbound-smooch-request",
"triggers": [
"conversation:message"
]
}
Response I am getting:
{"errors":[{"code":"forbidden","title":"Forbidden"}]}
That's how I generate Bearer token:
$signer = new Sha256();
$a = (new Builder())
->withHeader('alg', 'HS256')
->withHeader('typ', 'JWT')
->withHeader('kid', 'app_618ce234fba99000e1bd8***')
->withClaim('scope', 'app')
->getToken($signer, new Key('4K5KoVqLixLOUrkJSebr4rFsvZAu66d2WD8WEhXDgAZnJaltEpnHWpF_PUwQUGuNlFnBXvr8mtGsvNKj******'));
echo $a . PHP_EOL;
die();
Webhook api documentation: https://docs.smooch.io/rest/#operation/createWebhook
There is a bearerAuth (integration, app) explanation but there is no information what does this means. Documentation says that there are only two scopes: account and app. So what is this?
Other endpoints work normally (app create, app keys create, integration create)
Tried Basic auth also but it did not help.
The *Webhook endpoints are used (in v2) to create/update/remove webhooks from an existing customIntegration (integration with type: custom).
This endpoint will allow you to create a new integration, and when you set type: custom, it will also accept a webhooks list: https://docs.smooch.io/rest/#operation/createIntegration

Jenkins job adding new line only when run via jenkins pipeline not stand alone

I have a jenkins pipeline that builds a job that uses powershell to make json based requests. When I run the job through the pipeline my script adds various line breaks throughout the json. When I run the job by hitting 'rebuild' the script runs without issue.
Output of my request via jenkins pipeline:
Invoke-RestMethod -Uri http://api.newrelic.com/v2/applications/17303495/deployments.json -Method 'POST' -Headers System.Collections.Hashtable -ContentType 'application/json' -Body {
"deployment": {
"revision": "Deployment of e0ca4b7
",
"changelog": "See Release Email Notes",
"description": "Beginning Deployment of e0ca4b7
",
"user": "pcort"
}
}
Output of my request via 'rebuild' or manual:
Invoke-RestMethod -Uri http://api.newrelic.com/v2/applications/17303495/deployments.json -Method 'POST' -Headers System.Collections.Hashtable -ContentType 'application/json' -Body {
"deployment": {
"revision": "Deployment of e0ca4b7",
"changelog": "See Release Email Notes",
"description": "Beginning Deployment of e0ca4b7",
"user": "pcort"
}
}
Help! This is really weird and breaks my code :) Any ideas would be great!
Jenkins is running ver. 2.46.2 and all plugins are up to date.
The issue was with getting the build label. I'm not entirely sure how it works, maybe someone with more knowledge can inform me, but getting the short git commit git rev-parse --short HEAD was leaving a space or new line character at the end of the variable (I was returning this via powershell). By adding .trim() I cleared this up.

Tastypie deserialize results in {"error": ""}

I'm using tastypie with django. I have one line of code:
data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
I use this code from the command line to send a post request to my webserver:
curl -X post -d "{ 'username' : 'user', 'password' : 'password' }" http://127.0.0.1:8000/api/employee/login/ --header "Content-Type:application/json"
When I run this, it results in a json response of
{"error": ""}
Looking at my server logs I see:
[15/Feb/2014 20:39:49] "post /api/user/login/ HTTP/1.1" 400 13
A log message logged immediately before the deserialize line will be logged successfully, but a log message logged immediately after the deserialize line will not be logged, so I am pretty sure the deserialize is wrong. Does anyone know what could be wrong or if I should consider something else as the problem?
Your JSON is not valid. Please check it here. The 400 (bad request) status should give you clue about that. It should be: {"username": "user", "password": "password"}. Here you have some solutions how to escape " char in CURL command. Tastypie unfortunately raises exception without message here but we can easily fix that for future to save time for other people which will use your API.
from tastypie.exceptions import BadRequest
from tastypie.serializers import Serializer
class VerboseSerializer(Serializer):
"""
Gives message when loading JSON fails.
"""
# Tastypie>=0.9.6,<=0.11.0
def from_json(self, content):
"""
Override method of `Serializer.from_json`. Adds exception message when loading JSON fails.
"""
try:
return json.loads(content)
except ValueError as e:
raise BadRequest(u"Incorrect JSON format: Reason: \"{}\" (See www.json.org for more info.)".format(e.message))
class MyResource(BaseModelResource):
class Meta:
serializer = VerboseSerializer(formats=['json'])