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

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)

Related

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

Executing a PATCH api call from powershell

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.

Python 3.x - Web Server - extract json body from POST request

I am sending a Post request with a json body to a server but can not extract the json file when it arrives. I have does exhaustive searches but to no avail. I have provided both client and server scripts to illustrate what is happening.
All I need is to extract the json portion at the end of the received string so I can analyze the request and return the appropriate data.
I'm sure it's simple but I can't seem to find the answer. Any direction would be appreciated
***
CLIENT: script to test Server
import json
import requests
def info_send():
url = 'http:1234abcd.ngrok.io'
payload = {
'command': '["command", "status", "off", None]',
'userID': 'userID string',
'status': 'current status',
}
requests.post(url, data=json.dumps(payload))
info_send()
***
SERVER: receives json POST request
HOST, PORT = '', 5000
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print('Listening on port %s' % PORT)
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024).decode('utf-8')
print(request)
***
This is what is printed at the server
POST / HTTP/1.1
Host: 1234abcd.ngrok.io
User-Agent: python-requests/2.18.4
Accept-Encoding: gzip, deflate
Accept: /
Content-Length: 112
X-Forwarded-For: 112.162.214.265
{"command": "[\"command\", \"status\", \"off\", None]", "userID": "userID string", "deviceID": "current status"}

REST API Testing: HTTP Post returns 500 with Frisby.js

I am using Frisby.js to submit a POST request with JSON data and test the JSON response. However, my query returns HTTP Status 500. The same POST request works fine in CURL in my command line, as well as Postman. What could be the problem?
CURL request: curl -H "Content-Type: application/json; charset=UTF-8" -X POST -d "json_data" url
FRISBY test:
frisby
.create("Submit request")
.post(url, json_data, {"json": true, "content-type": "application/json;charset=UTF-8"})
.expectStatus(200)
.inspectBody()
.toss();
OUTPUT with Frisby:
Destination URL may be down or URL is invalid, Error: ETIMEDOUT
F
Failures:
1) Frisby Test: Submit request
[ POST url]
Message:
Expected 500 to equal 200.
Stacktrace:
Error: Expected 500 to equal 200.
at null.<anonymous>
at null.<anonymous>
at Timer.listOnTimeout (timers.js:92:15)
Finished in 5.032 seconds
1 test, 1 assertion, 1 failure, 0 skipped
The 500 error and accompanying message that results "Destination URL..." is from Frisby itself, not your server. Frisby adds the error if the connection times out. Try increasing it to 10 seconds.
...
.get(url)
.timeout(10000)
...

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'])