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
Related
I try to authenticate to the Jira REST API with a token, but I get an error that Basic authentication with passwords is deprecated.
How do I tell the Jira API that I'm using Basic authentication with a token, not a password?
(venv) $ cat error_demo.py
import base64
import json
import requests
jira_user = 'me#myorg.com'
jira_token = '9rXXXXXXXXXX5B'
cred = "Basic " + base64.b64encode(b"jira_user:jira_token").decode("utf-8")
print("cred =", cred)
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization" : cred
}
projectKey = "NETOP-1987"
url = "https://myorg.atlassian.net/rest/api/3/search?jql=key=" + projectKey
response = requests.request("GET", url, headers=headers)
print("response =", response)
print("response.text =", response.text)
(venv) $ python error_demo.py
cred = Basic amYYYYYYYYYYYYYYW4=
response = <Response [401]>
response.text = Basic authentication with passwords is deprecated. For more information, see: https://developer.atlassian.com/cloud/confluence/deprecation-notice-basic-auth/
It was suggested that base64 is not needed for the credentials, but instead, the HTTPBasicAuth class from requests.auth should be used, and the resulting auth request object passed to the headers instead.
With that change, the script below returns the expected response:
import base64
import json
import requests
from requests.auth import HTTPBasicAuth
jira_user = 'me#myorg.com'
jira_token = '9rXXXXXXXXXX5B'
auth = HTTPBasicAuth(jira_user, jira_token)
print("auth =", auth)
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
projectKey = "NETOP-1987"
url = "https://myorg.atlassian.net/rest/api/3/search?jql=key=" + projectKey
response = requests.request("GET", url, headers=headers, auth=auth)
print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(".", ": ")))
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)
We can make REST api application with spring boot by start.spring.io web site easily, anyone know any good website through which I can get the skeleton REST api project with python? My intention is to make REST api application with python.
One of the ways to do this is by using the requests module in Python. Import it into your code with the following command:
import requests
Now, each API is different, so you'll have to see with the vendor what the requirements are. For testing and learning purposes, I recommend using httpbin (https://httpbin.org). You can test pretty much anything there.
Here are a few simple requests:
#returning status
url = 'https://httpbin.org/post'
response = requests.post(url)
print(response.status_code)
print(response.ok)
#sending data/getting text response
url = 'https://httpbin.org/post'
params = {'Jello':'World'}
response = requests.post(url, params=params)
print(response.text)
#sending data/getting json response
url = 'https://httpbin.org/post'
params = {'Jello':'World'}
response = requests.post(url, params=params)
print(response.json())
#sending time data to server
import datetime
url = 'https://httpbin.org/post'
params = {'Time':f'{datetime.datetime.now()}'}
response = requests.post(url, params=params)
print(response.text)
#Params vs Data
#params
url = 'https://httpbin.org/post'
params = {'username':'jsmith','password':'abc123'}
response = requests.post(url, params=params)
print(response.text)
#data
url = 'https://httpbin.org/post'
payload = {'username':'jsmith','password':'abc123'}
response = requests.post(url, data=payload)
print(response.text)
# ********* HEADERS **********
url = 'https://httpbin.org/get'
response = requests.get(url)
print(response.text)
url = 'https://httpbin.org/post'
headers = {'content-type': 'multipart/form-data'}
response = requests.post(url,headers=headers)
print(response.request.headers) #client request headers
print(response.headers) #server response headers
print(response.headers['content-type']) #request header value from server
To use actual APIs, I suggest RapidAPI (https://rapidapi.com/), which is a hub where you can connect to thousands of APIs. HEre is a sample code using Google translate:
#RapidAPI
#Google Translate
import requests
url = "https://google-translate1.p.rapidapi.com/language/translate/v2"
text = 'Ciao mondo!'
to_lang = 'en'
from_lang = 'it'
payload = f"q={text}&target={to_lang}&source={from_lang}"
headers = {
'content-type': "application/x-www-form-urlencoded",
'accept-encoding': "application/gzip",
'x-rapidapi-host': "google-translate1.p.rapidapi.com",
'x-rapidapi-key': "your-API-key"
}
response = requests.post(url, data=payload, headers=headers)
print(response.json()['data']['translations'][0]['translatedText'])
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())
I am attempting to access the NJTransit API, I have successfully queried it using the Postman application but no matter what I try I cannot get python to successfully return the desired query.
Using suds:
from suds.client import Client
url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx?wsdl"
client = Client(url, cache = None)
from suds.sax.element import Element
auth = Element('UserCredentials')
auth.append(Element('userName').setText(my_username))
auth.append(Element('password').setText(my_password))
client.set_options(soapheaders = auth)
client = Client(url, cache = None)
result = client.service.getTrainScheduleJSON("NY")
This results in "none".
I've also attempted to use the preformatted request suggested by the Postman app, however I keep getting a 404 error.
import requests
url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx"
querystring = {"wsdl":""}
payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Header>\n <UserCredentials xmlns=\"http://microsoft.com/webservices/\">\n <userName>---</userName>\n <password>---</password>\n </UserCredentials>\n </soap:Header>\n <soap:Body>\n <getTrainScheduleJSON xmlns=\"http://microsoft.com/webservices/\">\n <station>NY</station>\n </getTrainScheduleJSON>\n </soap:Body>\n</soap:Envelope>"
headers = {
'content-type': "text/xml; charset=utf-8",
'host': "traindata.njtransit.com",
'soapaction': "http//microsoft.com/webservices/getTrainScheduleJSON"
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
I would greatly appreciate any help/insight.
You never want to set the "Host" header, this is will be done by requests.
The 404 is triggered by the wrong SOAPAction. There is a missing : after http.
The following snippet is working fine for me.
import requests
url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx"
querystring = {"wsdl":""}
payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Header>\n <UserCredentials xmlns=\"http://microsoft.com/webservices/\">\n <userName>---</userName>\n <password>---</password>\n </UserCredentials>\n </soap:Header>\n <soap:Body>\n <getTrainScheduleJSON xmlns=\"http://microsoft.com/webservices/\">\n <station>NY</station>\n </getTrainScheduleJSON>\n </soap:Body>\n</soap:Envelope>"
headers = {
'content-type': "text/xml; charset=utf-8",
'soapaction': 'http://microsoft.com/webservices/getTrainScheduleJSON'
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print response
print(response.text)