Cannot get response from mailchimp API - python

I need to connect mailchimp API through python script and GET data, that i'd later move to PowerBI for BI solutions.
I have read the documentation :
https://mailchimp.com/developer/guides/get-started-with-mailchimp-api-3/#Parameters
And I am trying to get a specific report
https://mailchimp.com/developer/reference/reports/#get_/reports/-campaign_id-
First I managed to connect to reports (https://mailchimp.com/developer/reference/reports/#get_/reports/) with the following code:
import requests
import json
r=requests.get("https://us11.api.mailchimp.com/3.0/reports/",
headers={"content-type": "application/json"},
auth=('anystring', 'myapikey')
,params={'fields':['id']})
data=r.json()
print(data)
r_dict = json.loads(r.text)
print(r.status_code)
print(r.text)
for i in r_dict:
print("key:", i,"val",r_dict[i])
Then I get some sort of output, which is not an error and it seems i connected since i retrieved data. Now I am trying to connect to a specific report, i set up an id, but it seems i cannot understand how to set up parameters properly. My code looks like this:
r=requests.get("https://us11.api.mailchimp.com/3.0/reports/{80419197aa}",
headers={"content-type": "application/json"},
auth=('anystring', 'myapikey')
,params={'fields':['id','campaign_title','type','list_id']})
data=r.json()
print(data)
r_dict = json.loads(r.text)
print(r.status_code)
print(r.text)
for i in r_dict:
print("key:", i,"val",r_dict[i])
Then i get this error:
{'type':
'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
'title': 'Resource Not Found', 'status': 404, 'detail': 'The requested
resource could not be found.', 'instance':
'13af7a5e-9868-4dd3-abd6-6c3b0b58983f'} 404
{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Resource
Not Found","status":404,"detail":"The requested resource could not be
found.","instance":"13af7a5e-9868-4dd3-abd6-6c3b0b58983f"} key: type
val
http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
key: title val Resource Not Found key: status val 404 key: detail val
The requested resource could not be found. key: instance val
13af7a5e-9868-4dd3-abd6-6c3b0b58983f"
Could anyone help me how should i specify the parameters, because i suppose the mistake is there?

The reason why error 404 appears is because of the auth parameter, if you remove this parameter you will get the error 401 that is an invalid API Key, you would need to use the correct authentication method.
I would recommend that you first try it with a program like Postman, so that you discard some error outside the code.

Related

Event Notification Delivery Method - Ebay error - HTTP status code 405

I have used the following guide - https://developer.ebay.com/marketplace-account-deletion
So I've created a flask based website on python and uploaded in Heroku,
https://ebay-deletion.herokuapp.com/
If you create a query parameter, for the challenge code like so:
https://ebay-deletion.herokuapp.com/?challenge_code=123
It returns a challenge response and doc type (JSON).
I don't understand but why but I get this error below:
Notification delivery failed with HTTP status code 405 from https://ebay-deletion.herokuapp.com. Please ensure that the marketplace account deletion notification endpoint is ready to receive notifications.
Any thoughts on how to solve this?
Ebay's help page is just so terrible. Their python code examples for hashing in the top link have semi-colons after each line! It's close to completely useless.
Here is the Python Flask code:
#app.route('/')
def index():
args = request.args
args_dict = args.to_dict()
try:
resp_hash = hashlib.sha256(
args_dict['challenge_code'].encode() + verification_token.encode() + endpoint.encode())
resp = {'challengeResponse': resp_hash.hexdigest()}
return jsonify(resp), 200, {'content-type': 'application/json'}
except KeyError:
err = {'status_code': 400, 'message': 'no challenge response in params'}
return jsonify(err), 400, {'content-type': 'application/json'}

Data sent with the requests.delete method is disregarded

While trying to connect to an API from Alpaca (a broker that accepts automated orders), I found that I was unable to send data with the requests.delete method. Here is some code:
def close_position(symbol, percentage, api_key=api_key, secret_key=secret_key, base_url=base_url):
data = {"percentage": percentage}
headers = {
"APCA-API-KEY-ID": api_key,
"APCA-API-SECRET-KEY": secret_key
}
url = f"{base_url}/v2/positions/{symbol}"
order = requests.delete(url, json=data, headers=headers)
return order.json()
This code is supposed to close (i.e., liquidate) a specified percentage of a position. However, it seems that the data sent using the delete method is disregarded; this function always closes my entire position instead of the specified percentage. Here is the documentation for the Alpaca API: https://alpaca.markets/docs/api-references/trading-api/positions/#close-a-position
I have also tried the data and params parameter and json.dumps(data), but to no avail.
Any idea how to send data with the requests.delete method would be appreciated.

How can i insert list of Classifications into Apache Atlas using API

I am trying to insert set of classifications or tags into Apache Atlas using API.
I am facing an error.
Can any one help me any roundabouts of overcoming this error and insert the classifications.
My code:
import requests
import json
from requests.auth import HTTPBasicAuth
#specify url
url = 'http://aaaaa/api/atlas/v2/entity/classification'
print(url)
bulk = { "classification":{ "typeName":"Confidential","attributes":{ "retention_required":"true","max_retention_time_months":"12"}},"entityGuids":[ "be532571-1663-4550-af6d-28cfe39769f6"]}
#Call REST API
response = requests.put(url, data=bulk,auth=HTTPBasicAuth('xxx', 'yyy'))
print(response)
print(response.text)
This GUID is valid.
The error I face is :
<Response [500]>
There was an error processing your request. It has been logged (ID 7e31c72f5e0f5e3b).
In short, I want to achieve the given screen functionality thru python.
Thank you.
Send request to: http://aaaaa/api/atlas/v2/types/typedefs
You should use post if the classification doesn't exist already, if the classification exists, you will get 409 Client Error.
Use PUT to update existing classification.
Your json should look something like this:
{'classificationDefs: [{
'entityTypes': entityTypes,
'subTypes': subTypes,
'superTypes': superTypes,
'attributeDefs': attributeDefs,
'category': category,
'createdBy': createdBy,
'description': description,
'name': name,
'options': options,
'typeVersion': typeVersion,
'updatedBy': updatedBy,
'version': version
}]
}
Types of attributes in json:
list: entityTypes, attributeDefs, superTypes, subTypes
dictionary: options
number: version
rest is of type string or text

Mapbox API PUT Datasets Feature return "Provide a single Feature to insert"

I am trying to add a feature to the Dataset via Mapbox API using Python. I'm following this instruction https://docs.mapbox.com/api/maps/#update-a-dataset but keep getting this error:
{'message': 'Provide a single Feature to insert'}
The code looks like this:
rs = []
dictionary = {
"id":1,
"type":"Feature",
"properties":{},
"geometry":{"coordinates":[-83.750246, 42.269375],"type":"Point"}}
url = "https://api.mapbox.com/datasets/v1/voratima/"+dataset+"/features/1?access_token="+access_token
rs.append(grequests.put(url, data=dictionary, hooks = {'response' : do_something}))
grequests.map(rs, exception_handler=exception_handler)
I've tried the following but none of them work:
using requests instead of grequests
wrapping the dictionary with json.dumps()
changing the put parameter from data=dictionary to json=dictionary
Making sure the id for both data and URL are set to 1.
Postman of the exact same request does not have the error. What am I missing?
Given a dataset with dataset ID dataset exists, your request body looks ok.
Please add the header
headers = {'Content-type': 'application/json'}
Also can you check if you meet these specs:
This should be one individual GeoJSON feature, not a GeoJSON
FeatureCollection. If the GeoJSON feature has a top-level id property,
it must match the feature_id you use in the URL endpoint.
It turns out I forgot the header. Thanks to Mortiz for pointing that out. After the update I got
<Response [400]> {'message': 'Unexpected token i'}
That's because I need to wrap the dictionary inside json.dumps(). Then the error became
<Response [422]> {'message': 'Request URI does not match feature id'}
That's because the id in the dictionary has to be a string i.e. "id":"1" not "id":1. Here's the code that works:
rs = []
dictionary = {
"id":"1",
"type":"Feature",
"properties":{},
"geometry":{"coordinates":[-83.750246, 42.269375],"type":"Point"}}
headers = {'Content-type': 'application/json'}
url = "https://api.mapbox.com/datasets/v1/voratima/"+dataset+"/features/1?access_token="+access_token
rs.append(grequests.put(url, data=json.dumps(dictionary), headers=headers, hooks = {'response' : do_something}))
grequests.map(rs, exception_handler=exception_handler)

Google maps reverse geocoding always responds with 602 (Unknown Address) on server side

I have server-side code that calls the Google geocoding API, like this:
http://maps.google.com/maps/geo?q=40.714224,-73.961452&output=json&sensor=false&key=API_KEY
where API_KEY is my API key. I get a JSON reply, as expected, but the reponse is always 602 (Unknown Address). Is my URL wrong? (I've also tried the URL in the Google docs, but that returns a status: 'REQUEST_DENIED'.
What else could be wrong?
Update:
Well, it seems to actually be a mistake in my implementation, not the URL. This was how I did it:
api_params = {
'q': '40.714224,-73.961452',
'sensor': 'false',
'key': KEY,
'output': 'json'
}
# make the api call
http_response = urllib.urlopen('http://maps.google.com/maps/geo',
urllib.urlencode(api_params))
r = json.load(http_response)
but changing it to:
api_params = {
#'q': str(lat) + ',' + str(lng),
'q': '40.714224,-73.961452',
'sensor': 'false',
'key': KEY,
'output': 'json'
}
# make the api call
http_response = urllib.urlopen('http://maps.google.com/maps/geo?q='+api_params['q']+'&output=json&sensor=false&key='+api_params['key'])
r = json.load(http_response)
print r
fixes the problem. So my new question is, what's wrong with the first one?
The first one executes POST request, the second - GET request.
You may also want to use the urllib.urlencode function for concatenation.
But the easiest way is to use geopy.
Try using a HTTP watcher to make sure that this is the actual URL that is being sent within your application. There could be a chance that it isn't being encoded correctly or maybe is being incorrectly assembled. Since you aren't getting request denied and we were able to get a good response when we viewed it directly it seems that could be the best place to start. Hope that helps!

Categories

Resources