i am trying to pull data by referencing this guide.
I'm a little new. can i just pull data with api key and url. Because i have only api key and url. I don't have any of the other parameters. Here are the ways i tried:
import urllib.parse
import urllib.request
url = "https://commerce.campaignmonitor.com/api/v1/abandoned-carts/campaigns"
header={"x-api-key" : 'my_api_key'}
post_param = urllib.parse.urlencode({
'user' : 'i_dont_know',
'status-update' : 'i_dont_know'
}).encode('UTF-8')
req = urllib.request.Request(url, post_param, header)
response = urllib.request.urlopen(req)
and this:
from requests.auth import HTTPBasicAuth
import requests
import urllib
url ="https://commerce.campaignmonitor.com/api/v1/abandoned-carts/campaigns"
headers = {"Accept": "application/json"}
auth = HTTPBasicAuth('my_api_key', 'i_dont_know')
req = requests.get(url, headers=headers , auth=auth)
response = urllib.request.urlopen(req)
but i have error:
AttributeError: 'Response' object has no attribute 'type'
in other methods, I get 401 error
python-requests alone can do this for you (no need for urllib).
You have the API key so you shouldn't use the HTTPBasicAuth
this should work for you:
import requests
url ="https://commerce.campaignmonitor.com/api/v1/abandoned-carts/campaigns"
# like the doc says, provide API key in header
headers = {"Accept": "application/json",
'X-ApiKey': 'my_api_key'}
req = requests.get(url, headers=headers)
print(req.json())
Related
I've have been accessing an supportpal API via curl just fine using the following command. (https://docs.supportpal.com/current/REST+API)
curl.exe -i -u 'APIKEY:x' -X GET https://support.url.org/api/user/user/3697
This correctly grabs the data. I've trying replicate this with python but i continually have issues with authentication and get the following error.
Failed to authenticate because of bad credentials or an invalid authorization header
The code i'm using is straight forward.
import requests
import json
url = "https://support.url.org/api/user/user/3697"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer: {APIKEY:x}"
}
response = requests.request("GET", url, headers=headers)
print(response. Text)
I'm thinking i have an issue with the auth header, but can't figure it out.
from requests.auth import HTTPBasicAuth
import requests
url = 'https://support.url.org/api/user/user/3697'
headers = {'Accept': 'application/json'}
auth = HTTPBasicAuth('apikey', x)
req = requests.get(url, headers=headers, auth=auth)
I need to create a post request, which is repeatedly failing as the auth headers are either being send in incorrect format or are missing/not matching signature, I need help on this as I am new to python and despite rigorous searching still cant find answer to this.
Below is the code which I got from postman for a get request but the same headers aren't working for post request, post request even doesn't work with postman either
import requests
url = "https://aaaaa-bbbb.xxxx.exampleapis.net/cps/v2/enrollments?enrollmentId=81053"
payload={}
files={}
headers = { 'Accept': 'application/vnd.aaaa.xxx.eeeee.v11+json', 'Authorization': 'EG1-HMAC-SHA256 c_token=cccc;access_token=aaaa;timestamp=20220526T14:06:11+0000;nonce=nnn123;signature=Abcde123=' }
response = requests.request("GET", url, headers=headers, data=payload, files=files)
print(response.text)
What I have tried so far:
from http import client
from multiprocessing.connection import Client
import requests
import json
from hostgrid import hostAuth
from urllib.parse import urljoin,urlencode
import time
import uuid
import hashlib
from hashlib import sha1
import hmac
s = requests.Session()
url = "https://aaaa-wwww.xxxx/ppp/v2/certs?contractId=A-12345"
s = requests.Session()
s.auth = hostAuth(
client_token= ' ctctct',
client_secret = 'cccc',
access_token=aaaaa'
)
payload = open('test.json')
data = json.load(payload)
timestamp = str(int(time.time()))
nonce = uuid.uuid4().hex
hmac.new(client_secret,f'{timestamp}{nonce}'.encode('ascii'),hashlib.sha256).hexdigest()
headers={
"Accept" : "application/vnd.aaaa.ccc.cert-status.v11+json",
'Content-Type' : "application/vnd.akamai.ccc.cert.v11+json",
‘Authorization’ : 'EG1-HMAC-SHA256 c_token=cccc;access_token=aaaa;timestamp=20220526T14:06:11+0000;nonce=nnn123;signature=Abcde123='
}
response = s.post(url,data,headers)
print(response.text)
import requests
import json
def test_request_response():
# Send a request to the API server and store the response.
data = { 'username' : 'sxxxt#xxx.com', 'password' : 'xxxxe' }
headers = {'Content-type': 'application/json'}
response = requests.get('https://xx.xxx.com/xx/xx',headers=headers,data=json.dumps(data))
return response
test_request_response()
output
I have an api key also API_KEY = '0x-x-x-x0 is there any I can give API_KEY in requests.get as like username and password
example in headers headers = {'Content-type': 'application/json','X-IG-API-KEY':'0x-x-x-x0'}
is this what you are looking for ?
from requests.auth import HTTPBasicAuth
import requests
url = "https://api_url"
headers = {"Accept": "application/json"}
auth = HTTPBasicAuth('apikey', '1234abcd')
files = {'filename': open('filename','rb')}
req = requests.get(url, headers=headers , auth=auth , files=files)
reference : Calling REST API with an API key using the requests package in Python
I'm trying to use requests in python to post a json dictionary to a url. I need to get a string back from the url but I keep getting a code 141 error -{"code":141,"error":"Missing a github repository link"}. I'm using this website(http://docs.python-requests.org/en/latest/user/quickstart/) to do requests.
Any ideas on why I keep getting that error? Code is below.
import requests
import json
payload = { "email" : "jade#gmail.com", "github" : "https://github.com/"}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/register", params = payload, headers = headers)
print(r.url)
print r.text
Update: The suggestion worked but now I'm getting an{"code":141,"error":"success/error was not called"} error when I try to save the response I recieve from the url into a variable and then post it back to a different url.
#Store the token into a variable
token = r.text
payload = { "token" : token}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/getstring", json = payload, headers = headers)
print r.text
Since you are making a POST request and you need to provide a JSON in the request body, use json argument, not params:
r = requests.post("http://challenge.code2040.org/api/register",
json=payload,
headers=headers)
(tested - got back a token)
Note that json argument was introduced in requests 2.4.2.
I want to write an app to shorten url. This is my code:
import urllib, urllib2
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
postdata = urllib.urlencode({'longUrl':url})
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
post_url,
postdata,
headers
)
ret = urllib2.urlopen(req).read()
return json.loads(ret)['id']
when I run the code to get a tiny url, it throws an exception: urllib2.HTTPError: HTTP Error 400: Bad Requests.
What is wrong with this code?
I tried your code and couldn't make it work either, so I wrote it with requests:
import requests
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
payload = {'longUrl': url}
headers = {'content-type': 'application/json'}
r = requests.post(post_url, data=json.dumps(payload), headers=headers)
print(r.text)
Edit: code working with urllib:
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
postdata = {'longUrl':url}
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
post_url,
json.dumps(postdata),
headers
)
ret = urllib2.urlopen(req).read()
print(ret)
return json.loads(ret)['id']
I know this question is old but it is high on Google.
Another thing to try is the pyshorteners library it is very simple to implement.
Here is a link:
https://pypi.python.org/pypi/pyshorteners
With an api key:
import requests
import json
def shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(API_KEY)
payload = {'longUrl': url}
headers = {'content-type': 'application/json'}
r = requests.post(post_url, data=json.dumps(payload), headers=headers)
return r.json()