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 :)
Related
Id like to convert this curl command to python script
curl -v -H "Content-Type: application/json" -H "Authorization: Bearer MYTOKEN" https://www.zopim.com/api/v2/chats
I wrote the python script below but I get <Response [400]>and doesn't work.
import requests
url = "https://www.zopim.com/api/v2/chats"
access_token = "MYTOKEN"
response = requests.post(url,
headers={"Content-Type":"application/json;charset=UTF-8",
"Authorization": "Bearer {}".format(access_token)})
print(response)
Any advice will be appreciated.thanks.
You should be using requests.get instead of requests.post, since what you want is a GET request:
import requests
url = "https://www.zopim.com/api/v2/chats"
access_token = "MYTOKEN"
response = requests.get(url,
headers={"Content-Type":"application/json;charset=UTF-8",
"Authorization": "Bearer {}".format(access_token)})
print(response)
So I wrote this script in curl to generate a token
token=$(curl -s -H "Accept: application/json" -H "Content-Type: application/json" --data '{"identifier": "...", "password": "..."}' "$HOST:$PORT/login" | ggrep -Po '"token":"(\K[^"]+)')
which works fine. However with the simplicity of Python 3 I'd like to perform the same task using requests. As I understand running
import requests, json
http = '...'
head = {'accept': 'application/json', 'Content-Type':'application/json'}
data = { 'username' : '...', 'password' : '...' }
r = requests.post(http, data=json.dumps(data), headers=head, verify=False)
print(r.text)
should return the same but I get the error
{"id":"3bca1f46-0577-40a9-8e09-7d68557ad88f","rafalError":"WrongJson","message":"DecodingFailure at .identifier: Attempt to decode value on failed cursor"}
with r.status_code returning 422.
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?
The call I want to make is this:
curl -i \
-H 'Harvest-Account-ID: 3012210627'\
-H 'Authorization: Bearer 184740.pt.VgNF7lMe1YDTjTH4_nfhm8NiH(qMyRI9kFS4BBvztnLM9P0HNgQvAHnlglnTA9q0wlmtrpoEONHVaT7phZAaNw'\
-H 'User-Agent: Harvest API Example' \
"https://api.harvestapp.com/api/v2/time_entries.json"
but I am not quite sure of how to do this. Any help will be appreciated.
It does not authenticate, because you did not send the JWT Token in HTTP headers:
import requests
headers = {
"Harvest-Account-ID": "380637",
"Authorization": "Bearer 184740.pt.VgNF7mMe1YDTjTH4_nfhm8NiT5IMyRI9kFS4AAvztnLM9P0HNgQvAHnlglnTA9X0wlmtrpoEONHVaT7phZAaNw",
"User-Agent": "Harvest API Example"
}
print (requests.get("https://api.harvestapp.com/api/v2/time_entries.json", headers=headers)
Returns:
<Response [200]>
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.