Uber Eats API - Fail to collect reports (Could not parse json: readObjectStart: expect { or n, but..) - uber-api

We are facing an error when we are trying to request UberEats API to collect report about our restaurants based on the Ubereats documentation here.
The error :
'{"error":"Could not parse json: readObjectStart: expect { or n, but found \x00, error found in #0 byte of ...||..., bigger context ...||..."}'
We tried to run the query in python and postman and still facing the same error.
Need help to understand where we failed.
Here the python code run in VSC
import requests
import json
payload = {
"report_type": "FINANCE_SUMMARY_REPORT",
"store_uuids": "xxx",
"start_date": "2022-09-01",
"end_date": "2022-09-15"
}
headers = {
"authorization": "Bearer xxx"
}
report_response = requests.post('https://api.uber.com/v1/eats/report', data=payload, headers=headers)
report_response.text
'{"error":"Could not parse json: readObjectStart: expect { or n, but found \x00, error found in #0 byte of ...||..., bigger context ...||..."}'
Best regards,

You have to convert the payload to valid JSON string and send the request.
headers = {
"Authorization" : "*********",
"Content-Type" : "application/json"
}
import json
response = requests.post("https://api.uber.co/v1/eats/report", data = json.dumps(payload), headers=headers)

Related

Unable to get resonse from import contacts sendgrid API using python

Below is the call I am trying to make -
I used field mapping in below data -
data = {
"file_type": "csv",
"field_mappings": [
"_rf2_T",
"_rf0_T",
"_rf1_T",
"_rf10_T",
"w1_T",
"w45_T",
"w46_T",
"w44_T",
"w2_D",
"w43_T"
]
}
print("--data---",data)
response = sg.client.marketing.contacts.put(
request_body=data
)
#print("--data---",data)
print(response.status_code)
print(response.body)
print(response.headers)
and getting below error
{'errors': [{'field': 'contacts', 'message': 'at least one contact is required'}]}
I am expecting upload url and header from api call

How to check for proper format in my API response

Currently running tests for my REST API which:
takes an endpoint from the user
using that endpoint, grabs info from a server
sends it to another server to be translated
then proceeds to jsonify the data.
I've written a series of automated tests running and I cannot get one to pass - the test that actually identifies the content of the response. I've tried including several variations of what the test is expecting but I feel it's the actual implementation that's the issue. Here's the expected API response from the client request:
{ "name": "random_character", "description": "Translated description of requested character is output here" }
Here is the testing class inside my test_main.py:
class Test_functions(unittest.TestCase):
# checking if response of 200 is returned
def test_healthcheck_PokeAPI(self):
manualtest = app.test_client(self)
response = manualtest.get("/pokemon/")
status_code = response.status_code
self.assertEqual(status_code, 200)
# the status code should be a redirect i.e. 308; so I made a separate test for this
def test_healthcheck_ShakesprAPI(self):
manualtest = app.test_client(self)
response = manualtest.get("/pokemon/charizard")
self.assertEqual(response.status_code, 308)
def test_response_content(self):
manualtest = app.test_client(self)
response = manualtest.get("/pokemon/charizard")
self.assertEqual(response.content_type,
'application/json') <<<< this test is failing
def test_trans_shakespeare_response(self):
manualtest = app.test_client(self)
response = manualtest.get("/pokemon/charizard")
self.assertFalse(b"doth" in response.data)
Traceback:
AssertionError: 'text/html; charset=utf-8' != 'application/json' - text/html; charset=utf-8 + application/json
Any help would be greatly appreciated

RestClient.post response generating "error groovyx.net.http.ResponseParseException : OK"

I' am using groovy to consume a POST Rest api : here is my code :
import groovyx.net.http.RESTClient
#Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.7.1')
def url = "https://poc-ser.tst.be/"
def client = new RESTClient(url)
client.ignoreSSLIssues()
client.auth.basic(login,pswd)
client.post(
path: "osidoc/api/rest/production/documents?id=46",
contentType:'application/json',
headers: [Accept: 'application/json' , Authorization: 'Authorization']
)
But I always get error " error groovyx.net.http.ResponseParseException: OK caused by: groovy.json.JsonException: Unable to determine the current character, " Knowing that the response should be "application/msword" type (i.e : the response should be a word doc)
EDIT
I tried to change the Accept to "application/octet-stream' but it showed me an other error "406Invalid Accept header. Only XML and JSON are supported.`"

Groovy script for Jenkins: execute HTTP request without 3rd party libraries

I need to create a Groovy post build script in Jenkins and I need to make a request without using any 3rd party libraries as those can't be referenced from Jenkins.
I tried something like this:
def connection = new URL( "https://query.yahooapis.com/v1/public/yql?q=" +
URLEncoder.encode(
"select wind from weather.forecast where woeid in " + "(select woeid from geo.places(1) where text='chicago, il')",
'UTF-8' ) )
.openConnection() as HttpURLConnection
// set some headers
connection.setRequestProperty( 'User-Agent', 'groovy-2.4.4' )
connection.setRequestProperty( 'Accept', 'application/json' )
// get the response code - automatically sends the request
println connection.responseCode + ": " + connection.inputStream.text
but I also need to pass a JSON in the POST request and I'm not sure how I can do that. Any suggestion appreciated.
Executing POST request is pretty similar to a GET one, for example:
import groovy.json.JsonSlurper
// POST example
try {
def body = '{"id": 120}'
def http = new URL("http://localhost:8080/your/target/url").openConnection() as HttpURLConnection
http.setRequestMethod('POST')
http.setDoOutput(true)
http.setRequestProperty("Accept", 'application/json')
http.setRequestProperty("Content-Type", 'application/json')
http.outputStream.write(body.getBytes("UTF-8"))
http.connect()
def response = [:]
if (http.responseCode == 200) {
response = new JsonSlurper().parseText(http.inputStream.getText('UTF-8'))
} else {
response = new JsonSlurper().parseText(http.errorStream.getText('UTF-8'))
}
println "response: ${response}"
} catch (Exception e) {
// handle exception, e.g. Host unreachable, timeout etc.
}
There are two main differences comparing to GET request example:
You have to set HTTP method to POST
http.setRequestMethod('POST')
You write your POST body to outputStream:
http.outputStream.write(body.getBytes("UTF-8"))
where body might be a JSON represented as string:
def body = '{"id": 120}'
Eventually it's good practice to check what HTTP status code returned: in case of e.g. HTTP 200 OK you will get your response from inputStream while in case of any error like 404, 500 etc. you will get your error response body from errorStream.

Backend Error (HttpError 500) on Google Search Console API calls (webmasters/v3)

I prepared code that should fetch data from google webmaster console new Web API (v3).
import os
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from apiclient.discovery import build
import googleapiclient
import json
client_email = '<ACCOUNT_IDENTIFIER>#<PROJECT_IDENTIFIER>.iam.gserviceaccount.com'
scopes = ['https://www.googleapis.com/auth/webmasters.readonly',
'https://www.googleapis.com/auth/webmasters']
private_key_path = os.getcwd() + os.path.normpath('/key.p12')
http = httplib2.Http()
credentials = ServiceAccountCredentials.from_p12_keyfile(client_email,
private_key_path,
private_key_password="notasecret",
scopes=scopes
)
http_auth = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', credentials=credentials, http=http_auth)
query_params = {"startDate": "2016-03-01", "endDate": "2016-03-02"}
try:
quered_results = webmasters_service.searchanalytics().query(
key="<KEY>",
siteUrl="http://<SITE_DOMAIN>/",
body=json.dumps(query_params),
fields="rows",
alt="json"
).execute()
print(quered_results)
except googleapiclient.errors.HttpError as e:
print(e)
Execution results with error:
<HttpError 500 when requesting https://www.googleapis.com/webmasters/v3/sites/http%3A%2F%2F<SITE_DOMAIN>%2F/searchAnalytics/query?key=<KEY>&alt=json&fields=rows returned "Backend Error"
The code from above is for authorization with ssh key with p12 format. Key file is correct. Using client_secrets.json end up with the same error, code. The json for error is:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "backendError",
"message": "Backend Error",
}
],
"code": 500,
"message": "Backend Error"
}
}
I did connect email to webmaster tools console.
Authorization seems to work since there is no errors for used key/account
Any ideas?
I've noticed that the same error occures when I fetch on https://developers.google.com/apis-explorer with "Request body" improperly set, but I do not see error in JSON I send. BTW It would be nice to have some validation message about that...
Found it! body parameter should actually by python object, not JSON formatted string!
body=json.dumps(query_params),
Should be
body=query_params,