Trying to post data to firestore using requests - python

im trying to post JSON data to firestore using requests and it keeps returning this error.
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"{\"data\": \"message\"}\": Cannot bind query parameter. Field '{\"data\": \"message\"}' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"{\"data\": \"message\"}\": Cannot bind query parameter. Field '{\"data\": \"message\"}' could not be found in request message."
}
]
}
]
}
}
I've tried different method using different types of JSON Encoding and still returns the same error. i would appreciate if someone could look into this for me. Below is my code
def thestream(self, instance):
app = App.get_running_app()
s = requests.Session()
self.data = {u'data': u'message'}
self.headers = {"authorization": "bearer " + app.idToken}
r = s.post("https://firestore.googleapis.com/v1/projects/*******************************/databases/(default)/documents/messages/TemitayoAdefemi", params=json.dumps(self.data), headers=self.headers)
print(r.ok)
print(r.content.decode())

Try defining a Document resource in your payload:
self.data = {u'fields': {u'data': {u"stringValue": u'message'}}}
In your POST request, try passing the payload in data=self.data instead of param:
r = s.post("https://firestore.googleapis.com/v1/projects/***/databases/(default)/documents/messages/TemitayoAdefemi", data=self.data, headers=self.headers)

Related

Can I get this Python code snippet translated for usage with Axios+Vue?

The code snippet is simply about performing a post request to a machine learning model endpoint and logging out the response if successful.
import urllib.request
import json
import os
import ssl
def allowSelfSignedHttps(allowed):
# bypass the server certificate verification on client side
if allowed and not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None):
ssl._create_default_https_context = ssl._create_unverified_context
allowSelfSignedHttps(True) # this line is needed if you use self-signed certificate in your scoring service.
# Request data goes here
# The example below assumes JSON formatting which may be updated
# depending on the format your endpoint expects.
# More information can be found here:
# https://learn.microsoft.com/azure/machine-learning/how-to-deploy-advanced-entry-script
data = {
"Inputs": {
"data": [
{
"test_date": "2000-01-01T00:00:00.000Z",
"cough": false,
"fever": 0,
"sore_throat": false,
"shortness_of_breath": 0,
"head_ache": 0,
"age_60_and_above": "example_value",
"gender": "example_value"
}
]
},
"GlobalParameters": {
"method": "predict"
}
}
body = str.encode(json.dumps(data))
url = 'http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score'
api_key = '' # Replace this with the API key for the web service
# The azureml-model-deployment header will force the request to go to a specific deployment.
# Remove this header to have the request observe the endpoint traffic rules
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib.request.Request(url, body, headers)
try:
response = urllib.request.urlopen(req)
result = response.read()
print(result)
except urllib.error.HTTPError as error:
print("The request failed with status code: " + str(error.code))
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(error.info())
print(error.read().decode("utf8", 'ignore'))
I have tried this, but I keep getting
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score. (Reason: CORS request did not succeed). Status code: (null)."
function predict() {
axios
.post(
"http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score",
{
Inputs: {
data: [
{
cough: S1Val.value,
fever: S2Val.value,
sore_throat: S3Val.value,
shortness_of_breath: S4Val.value,
head_ache: S5Val.value,
age_60_and_above: a1.value,
gender: a2.value,
},
],
},
GlobalParameters: {
method: "predict",
},
},
{
headers: {
"Access-Control-Allow-Orgin": "*",
"Content-Type": "application/json",
},
}
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}
Also note that this endpoint doesn't require any authentication that's why I didn't append an API key to the Bearer when performing the request.

Why am I getting a 403 error when making a POST request using tetpyclient?

Trying to make a POST request in Cisco's Tetration API using their tetpyclient. I get a 200 response when using a get request, but 403 when making POST request with json filters for querying flows. Is my syntax for the json data incorrect or is there a syntax error in my python?
from tetpyclient import RestClient
import urllib3
import json
import requests
from datetime import datetime
from flask import *
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
API_ENDPOINT = "https://"
restclient = RestClient(API_ENDPOINT, credentials_file = 'path/to/credentials.json', verify = False)
get = restclient.get("/flowsearch/metrics")
print (get.status_code) ##to test if api can be reached
req_payload = {"t0": "2020-08-01T09:00:00-0700",
"t1": "2020-08-01T10:00:00-0700",
"scopeName": "Default",
"limit": 10,
"filter": {
"type": "and",
"filters": [
{"type": "eq", "field": "src_address","value": "00.000.0.000" },
{"type": "eq", "field": "dst_address","value": "000.000.00.00" }
]
}
}
resp = restclient.post('/flowsearch', json_body=json.dumps(req_payload))
print(resp.content)
print (resp.status_code)
if resp.status_code == 200:
parsed_resp = json.loads(resp.content)
print (json.dumps(parsed_resp, indent=4, sort_keys=True))
I appreciate any and allfeedback!
Here is link to tetration api docs: https://www.cisco.com/c/en/us/td/docs/security/workload_security/tetration-analytics/sw/config/b_Tetration_OpenAPI/m_flow-search.html
The HTTP 403 is a HTTP status code meaning access to the requested resource is forbidden for some reason
It looks like the credentials you are using are not allowed to call /flowsearch

Unsupported Media type error for request.post

I am working on a api call with python. Here I have the parameters in json format that was generated in the website I am trying to access. But when I try to run the program I get an 415: unsupported Media Type error. Not sure what I am doing wrong, as I am using the parameters generated by the website.
this is my code so far
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
url = 'https://einv-apisandbox.nic.in/gstvital/api/auth'
parameters = {
"header": {
"ClientID": "TheClientIDGoesHere",
"ClientSecret": "TheClientSecretGoesHere"
},
"data": {
"UserName": "Username",
"Password": "Password",
"AppKey": "AppKey",
"ForceRefreshAccessToken": "false"
}
}
response = requests.post(url, params=parameters)
jprint(response.json())
In the above code, I have removed the actual parameters and replaced them with dummy text. But when I try them with the actual parameters I get the following error
{
"status": 415,
"title": "Unsupported Media Type",
"traceId": "|df46105a-49e1b43f80675626.",
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.13"
}
One thing I changed was this code "ForceRefreshAccessToken": "false". In the generated json code, the false was not inside quotes
Not sure what I am doing wrong. Please help me.
import requests
import json
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
url = 'https://einv-apisandbox.nic.in/gstvital/api/auth'
parameters = {
"header": {
"ClientID": "TheClientIDGoesHere",
"ClientSecret": "TheClientSecretGoesHere"
},
"data": {
"UserName": "Username",
"Password": "Password",
"AppKey": "AppKey",
"ForceRefreshAccessToken": False
}
}
hdr = {"Content-Type": "application/json"}
response = requests.post(url, data=parameters, headers=hdr)
print(response.status_code)
print(response.json())
Error 415 indicates that the media type is not supported by the site. This can be fixed by explicitly stating in the header that the content-type will be JSON.
hdr = {"Content-Type": "application/json"} The response code from the site is "200:OK", therefore your request works.

Can not parse JSON share document.\nRequest body:\n\nError:\nnull

I am trying to send a request to Linkedin's rest share api. I have been receiving this error message:
{
"errorCode": 0,
"message": "Can not parse JSON share document.\nRequest body:\n\nError:\nnull",
"requestId": "ETX9XFEI7N",
"status": 400,
"timestamp": 1437910620120
}
The request is send through the following python code:
import requests,json
auth_token = "some auth token"
url = "https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token="+auth_token
headers = {'content-type': 'application/x-www-form-urlencoded','x-li-format':'json'}
data = {
"comment":"Check out developer.linkedin.com!",
"content":{
"title": "LinkedIn Developers Resources",
"description": "Leverage LinkedIn's APIs to maximize engagement",
"submitted-url": "https://developer.linkedin.com",
"submitted-image-url": "https://example.com/logo.png"
},
"visibility":{
"code": "anyone"
}
}
response = requests.post( url , json= data , headers=headers )
return HttpResponse( response )
I made sure that I followed all the instructions in their documentation and can't find the mistake I am making.
Note: i have tried json=data and data=data both are not working
Remove content-type from the headers dictionary.
requests sets the correct Content-Type when using the json keyword argument.
You have three basic problems:
Please read the documentation on oauth2; because you are not passing in the token correctly.
The share URL does not take a oauth2_token argument.
You have the wrong content-type header.

QPX Express API from Python

I am trying to use Google's QPX Express API from python. I keep running into a pair of issues in sending the request. At first what I tried is this:
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=MY_KEY_HERE"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)
based upon the code from: urllib2 and json
When I run the above code I get the following error message:
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
I searched for a solution and adapted my code based upon the following question: TypeError: POST data should be bytes or an iterable of bytes. It cannot be str
I changed my code to this:
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyCMp2ZnKI3J91sog7a7m7-Hzcn402FyUZo"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
data = data.encode("utf-8")
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)
However, when I run this code I get the following error message:
urllib.error.HTTPError: HTTP Error 400: Bad Request
I also tried changing utf-8 to ascii but I was unsuccessful. How can I get this working properly?
Here is a solution using the excelent requests library.
import json
import requests
api_key = "YOUR API KEY HERE"
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=" + api_key
headers = {'content-type': 'application/json'}
params = {
"request": {
"slice": [
{
"origin": "TXL",
"destination": "LIM",
"date": "2015-01-19"
}
],
"passengers": {
"adultCount": 1
},
"solutions": 2,
"refundable": False
}
}
response = requests.post(url, data=json.dumps(params), headers=headers)
data = response.json()
print data
I am not sure why you request is not working. Maybe it is really the request parameters that were wrong. The date definitely needs to be in the future!
False needs to be in lowercase in JSON, so you need to quote it in Python, like this "refundable" : "false". Otherwise, your query looks good (obviously you'll need to update the date). By the way, it isn't good practice to include your API key in a public forum.

Categories

Resources