I am able to run curl successfully but not worked with python request for mailchimp API.It gives an error like urllib2.HTTPError: HTTP Error 401: Unauthorized
CURL
curl --request POST \
--url 'https://us9.api.mailchimp.com/3.0/lists' \
--user 'anystring:6a983664930fc8ba1eecdsdf334344f40-us9' \
--header 'content-type: application/json' \
--data '{"name":"My test","contact":{"company":"Cool","address1":"Awesome place","city":"Lanka","state":"MH","zip":"43472","country":"IN","phone":""},"permission_reminder":"You'\''re receiving this email because you signed up.","campaign_defaults":{"from_name":"VD","from_email":"hey#sdfsdf.com","subject":"","language":"en"},"email_type_option":true}' \
--include
Python request :
import urllib2
import json
import requests
url = 'https://us9.api.mailchimp.com/3.0/lists/'
all_params={"user":"my_username:6a983664930fc8ba1eecd1d5d68f4f40-us9",
"name":"My test",
"contact":{"company":"Cool","address1":"Awesome place","city":"Lanka","state":"MH","zip":"43472","country":"IN","phone":""},"permission_reminder":"You'\''re receiving this email because you signed up.","campaign_defaults":{"from_name":"VD","from_email":"hey#sdfsdf.com","subject":"","language":"en"},
"email_type_option":'true'}
post_data = urllib2.quote(json.dumps(all_params))
headers = {'Content-Type': 'application/json'}
request = urllib2.Request(url, post_data, headers)
response = urllib2.urlopen(request)
I have referred Converting cURL to Python Requests but not worked.
I had solved it. It was problem of URL with data center. I was using us9.api... instead of us6.api.mailchimp.com/3.0/lists because my account was created under us6. So, I need to use data center where my account is registered with my URL in request.
Related
I have been trying to use requests to pull json data with client id and api key, but it won't work.
Here is the info I received from IT:
Request:
curl --location --request GET 'https://api.abc.com/def' \
--header 'clientid: testuser' \
--header 'Accept: application/json' \
--header 'apikey: testapikey1234' \
--header 'dc_session: UUID' \
--header 'dc_transaction_id: UUID'
I wrote the following code in python
import requests
import json
url = 'https://api.abc.com/def'
headers = {'Accept': 'application/json', 'clientid': 'testuser', 'apikey': 'testapikey1234', 'dc_session': 'UUID', 'dc_transaction_id': 'UUID'}
response = requests.get(url, verify = False, headers = headers)
print(response.status_code)
print(response.json())
Unfortunately the code returns 401 status code, with the error message:
{'error': {'type': 'INVALID_CLIENT_IDENTIFIER', 'message': 'Unauthorized. Missing or invalid clientID.'}}
Does anyone have any suggestions?
How do I convert
curl -X POST -T 'sample_data.json' -H "Content-Type: application/json" https://sample_url.com
to Python using requests?
Specifically, how do I provide "-T" parameter to the request?
I believe you could do something like this:
import requests
import json
requests.post('https://sample_url.com',
headers = {'Content-type': 'application/json'},
data = json.loads(open('sample_data.json').read())
}
You can check out the requests page for more details.
Or, to show a fully self-contained example without having to load the json from a file, you could do:
import requests
requests.post('https://httpbin.org/post', data = {'key':'value'})
<Response [200]>
Note, from the requests docs:
Using the json parameter in the request will change the Content-Type in the header to application/json.
So, you could just do the following instead:
r = requests.post(url, json=payload)
curl -X POST -T 'sample_data.json' \
-H 'Content-Type: application/json' \
https://sample_url.com/
is effectively equivalent to
curl -X POST \
-H 'Content-Type: application/json' \
-d "$(cat sample_data.json)" \
https://sample_url.com/sample_data.json
so using requests, it would be
with open('sample_data.json') as fh:
response = requests.post(
"https://sample_url.com/sample_data.json",
data=fh.read(),
header={'Content-Type': 'application/json'}
)
There are a couple of ways that you could do it. But the best way is to use the requests library. It's not part of the standard library (yet), but makes HTTP requests super straight-forward.
$ pip install requests
or
$ conda install requests
Then
import json
import requests
url = r"https://sample_url.com"
with open("sample_data.json", "r") as fh:
data = json.load(fh)
requests.post(url=url, data=data)
The best way is to use the Python Requests library - https://2.python-requests.org/en/master/. To be able to post a JSON payload in the message is
import Requests
import json
result = requests.post(URL,json=json.loads(open('sample_data.json').read()))
The requests library natively understands how to send your JSON data
There are some more examples of how to post messages with Form encoded payloads on this part of the page as well - https://2.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests
To be able to do other verbs you just need to change the function for requests -
for a GET, requests.get(url)
for a PUT, requests.put(url,data=DATA) or requests.put(url,json=JSON)
for a DELETE, requests.delete(url)
and so on.
I'm trying to grab some data from a website using API, but I'm having trouble converting the example curl command to python requests.
example curl command
curl -X POST "some_url" \
-H "accept: application/json" \
-H "Authorization: <accesstoken>" \
-d #- <<BODY
{}
BODY
My python requests that didn't work
headers = {
'Authorization': "Bearer {0}".format(access_token)
}
response = requests.request('GET', "some_url",
headers=headers, allow_redirects=False)
I get error code 400, can anyone help me figure out what was wrong?
The equivalent requests code for your curl should be:
import requests
headers = {
'accept': 'application/json',
'Authorization': '<accesstoken>',
}
data = "{} "
response = requests.post('http://some_url', headers=headers, data=data)
You can use https://curl.trillworks.com/ to convert your actual curl invocation (note that it won't handle heredocs, as in your example).
If you see different behavior between curl and your python code, dump the HTTP requests and compare:
Python requests - print entire http request (raw)?
How can I see the request headers made by curl when sending a request to the server?
I am running below API query using curl I am getting json response.
curl -X POST -H 'Content-Type: application/json' -H 'X-Metabase-Session: sdfeffff-sdfdf-ffff-ffff-fffffffff' https://dash.test.sh/api/card/140/query/json
But when I am trying to run same query using python requests I am getting response
"API endpoint does not exist."
Below is the python code which I am trying
import requests
url = 'https://dash.test.sh/api/card/140/query/json'
header = {
'X-Metabase-Session': 'sdfeffff-sdfdf-ffff-ffff-fffffffff'
}
response = requests.get(url, headers=header)
print (response.text)
I expect actual json content
With curl, you are doing a POST request but in Python you are calling GET method of same API. And possibly, the GET method does not exists for the API.
So just change your Python code
From requests.get to requests.post
curl is using Post and you are using get, the issue is there:
response = requests.post(url, headers=header)
Having way too much trouble making this cmd line curl statement work in python script...help! Attempting to use URLLIB.
curl -X POST "http://api.postmarkapp.com/email" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "X-Postmark-Server-Token: abcdef-1234-46cc-b2ab-38e3a208ab2b" \
-v \
-d "{From: 'sender#email.com', To: 'recipient#email.com', Subject: 'Postmark test', HtmlBody: 'Hello dear Postmark user.'}"
Ok so you should probably user urllib2 to submit the actual request but here is the code:
import urllib
import urllib2
url = "http://api.postmarkapp.com/email"
data = "{From: 'sender#email.com', To: 'recipient#email.com', Subject: 'Postmark test', HtmlBody: 'Hello dear Postmark user.'}"
headers = { "Accept" : "application/json",
"Conthent-Type": "application/json",
"X-Postmark-Server-Token": "abcdef-1234-46cc-b2ab-38e3a208ab2b"}
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
Check out: urllib2 the unwritten manual
I get a 401 unauthorized response so I guess it works :)