I am trying to request/ POST a JSON, but the DICT has some accents. I am getting the data from a CSV file. When I request, I get an error because the client does not recognize the parameters.
url='https://OracleERP/fscmRestApi/resources/11.13.18.05/cashBankAccounts'
encoded_u = base64.b64encode(userpass.encode()).decode()
headers = {'Content-Type' : 'application/vnd.oracle.adf.resourceitem+json',"Authorization" : "Basic %s" % encoded_u}
input_file = csv.DictReader(open(sys.argv[1]))
data ={
"BankBranchName" : row["AGENCIA_NOME"]
}
response = requests.post(url, json=data, auth = senha, headers = headers)
CSV FILE:
AGENCIA_NOME
"3396 - AGÊNCIA CORPORATE MORUMBI, SP"
Output:
'BankBranchName': '3396 - AGÊNCIA CORPORATE MORUMBI, SP'
Related
My Json is like this
[
{
"name":"abc"
"emai":"hotmail"
},
{
"name":"def"
"emai":"gmail"
}
]
I have to read one record at time and post request
in 1st post request with data
'{
"name":"abc"
"emai":"hotmail"
}'
in 2nd post request with data
'{
"name":"def"
"emai":"gmail"
}'
i tried with this code,
import json
import requests
from requests.structures import CaseInsensitiveDict
url = "https://testurl.com"
headers = CaseInsensitiveDict()
headers["accept"] = "text/plain"
headers["username"] = "username"
headers["password"] = "password"
headers["Content-Type"] = "application/json"
with open("data.json", encoding='utf-8', errors='ignore') as json_data:
for i in json_data:
data = json.load(i, strict=False)
idata = json.dumps(data) ## converting to string
fData = idata.replace("'", '"') # replacing ' with "
output = "'"+fData+"'" ## placing ' before and after json string which is mandatory in my case
print(fData)
# resp = requests.post(url, headers=headers, data=fData)
# print(f"status_code: : {resp.status_code}, response : {resp.json}")
I'm getting error 'str' object has no attribute error, can you please suggest me what i have to change ?
load all json, then loop through it
import json
import requests
from requests.structures import CaseInsensitiveDict
url = "https://testurl.com"
headers = CaseInsensitiveDict()
headers["accept"] = "text/plain"
headers["username"] = "username"
headers["password"] = "password"
headers["Content-Type"] = "application/json"
with open("data.json", encoding='utf-8', errors='ignore') as json_string:
json_data = json.load(json_string.read(), strict=False)
for i in json_data:
data = i
idata = json.dumps(data) ## converting to string
fData = idata.replace("'", '"') # replacing ' with "
output = "'"+fData+"'" ## placing ' before and after json string which is mandatory in my case
print(fData)
# resp = requests.post(url, headers=headers, data=fData)
# print(f"status_code: : {resp.status_code}, response : {resp.json}")
I guess you want to convert your JSON data to python structure first and then process it, something like:
import json
with open("data.json", encoding='utf-8', errors='ignore') as json_data:
data = json.loads(json_data.read())
for obj in data:
resp = requests.post(url, headers=headers, data=obj)
print(f"status_code: : {resp.status_code}, response : {resp.json}")
I have the following code in Python and want to move the request over to VBA. How do I write this in VBA?
import requests
import json
url = "https://us.market-api.kaiko.io/v1/data/order_book_snapshots.v1/exchanges/drbt/option/btc26jun2010000c/snapshots/full?" \
"start_time=2020-05-29T17:33:00.000000Z&end_time=2020-05-29T17:33:10.000000000Z"
payload = {}
headers = {
'Accept': 'application/json',
'x-api-key': '123456'
}
response = requests.request("GET", url, headers=headers, data = payload)
result = json.loads(response.text)
Public Sub testAPI()
Dim http As Object
Dim JSON As Object
Dim pm As Worksheet
Set pm = Sheets("Params")
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", ("https://us.market-api.kaiko.io/v1/data/order_book_snapshots.v1/exchanges/drbt/option/btc26jun209000p/snapshots/full?start_time=2020-05-29T17:33:00.000Z&end_time=2020-05-29T17:33:30.0Z"), False
http.SetRequestHeader "Accept", "application/json"
http.SetRequestHeader "x-api-key", "1234"
http.Send
Set JSON = ParseJson(http.ResponseText)
pm.Cells(2, 8).Value = JSON("data")(1)("asks")(1)("price")
End Sub
In order to extract data from a private API, I need to generate access tokens using my auth key and credentials. My current code is split in two parts. The first generates the access token:
import requests
url = "https://api.abcdef.com/AuthorizationServer/Token"
payload = "{\r\n \"grant_type\" : \"password\",\r\n \"username\" : \"user#aldfh.com\",\r\n \"password\" : \"kajshdgfkuyb\",\r\n \"scope\" : \"API\"\r\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
The response looks like this:
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpY0JVSWQiOjQ1OTg0MjEsIm5hbWUiOiJyYW15YS5nb3RldHlAY2lveGhlYWx0aC5jb20iLCJpc3MiOiJodHRwczovL2FwaS5pbmNvbnRhY3QuY29tIiwic3ViIjoidXNlcjoxNTMyMDI2MiIsImF1ZCI6IlRhYmxlYXVfQ2lveEBUYWJsZWF1X0Npb3giLCJleHAiOjE1Nzk2Mjg1NzcsImlhdCI6MTU3OTYyNDk3OCwiaWNTY29wZSI6IjgiLCJpY0NsdXN0ZXJJZCI6IkMzMSIsImljQWdlbnRJZCI6MTUzMjAyNjIsImljU1BJZCI6MTQ5NiwibmJmIjoxNTc5NjI0OTc4fQ.rEZiMHPsE1inwuWFME1oV_oD54TqkU00-uml3NjCkClW3R-_bVC7A3PxI4zGlJms1rvsZkgO3XX8-1coeV6_jtI-l3nCHixVk2nboepqAspoxT3o9w4vhBhZzvs-TAsqyk4fCrSwwHFXwn8xOMdfrqZqknXHLlVtKlGJg_Uy3bmwEiioocMN3BRZE_269_v5Ez4b94_juUHLPDWye7kS5-8cs4Izsk7HePn-Sm_-FLEqEeb2C09NUGWU8SdyA3EtQhMAiHkU-wN8uQ8wKcWoUfO7WtrSO4zbicFZHgA9Cw",
"token_type":"bearer",
"expires_in":3600,
"refresh_token":"pDYllH2UsVIYq3Pn3Dg==",
"scope":"Api",
"resource_server_base_uri":"https://api-c31.it.com/itAPI/",
"refresh_token_server_uri":"https://api-c31.it.com/AuthorizationServer/Token",
"agent_id":162,
"team_id":24355,
"bus_no":4421}'
The access token is part of the output and I paste this into the following code to generate the response:
def getPerformance():
# api-endpoint
#Give the specified url ,accessToken
BASEURL = 'https://api-c31.ict.com/tAPI/'
accessToken = "{eyJ0eXAiOiJKV1QiLCJhbGciSUzI1NiJ9.eyJpY0JVSWQiOjQ1OTgyYW15YS5nb3RldHlAY2lveGhlYWx0aC5jb20iLCJpc3MiOiJodHRwczovL2FwaS5pbmNvbnRhY3QuY29tIiwic3ViIjoidXNlcjoxNTMyMDI2MiIsImF1ZCI6IlRhYmxlYXVfQ2lveEBUYWJsZWF1X0Npb3giLCJleHAiOjE1Nzk1NjA0MjYsImlhdCI6MTU3OTU1NjgyNywiaWNTY29wZSI6IjgiLCJpY0NsdXN0ZXJJZCI6IkMzMSIsImljQWdlbnRJZCI6MTUzMjAyNjIsImljU1BJZCI6MTQ5NiwibmJmIjoxNTc5NTU2ODI2fQ.JIzsPLK8kg8Zqq_uITeNp6b24xuglcmtjVbD9Ll-ooq943gIILvr_SQ8cTKNl50YMyiX_mu48pupf-D0b-Ntbmb7hYOTNY7tjp8skM8uBDmuSzG1GnVQh3ZotdlofhiEDU9_U4sQsovqdDtXyi5inaoJ95TeBS_YQp_3LSv3pjfXQNWdt1bcn7arHWdIdl6qD5qXm0DhXQArhTr35mViZn-ZxITW4nvEi-gwZz6DdLWuWcW5kTbbzvucroVUPM-dZvzNJvMEruJvriUGl3Y2DSlB5qTLo3JqbLwujsoZfhaxfJ1eAFKd13t6mMenQ5TOwVV3Rg_yp7DfeBbnWcmwtA}"
#Check if accessToken is empty or null
if accessToken != "":
#Give necessary parameters for http request
payload={'startDate':'1/1/2020',
'endDate':'1/6/2020',
'fields':'"teamId","calls"'}
#add all necessary headers
header_param = {'Authorization': 'bearer ' + '{accessToken}','content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json, text/javascript, */*'}
# Make get http request
answer = requests.get(BASEURL + 'services/{version}/g/h' , headers = header_param, params=payload)
#print response appropriately
print (answer)
else: print('error')
My issue is that I need to be able to merge both scripts in order to be able to automate the process.
Try adding the following changes to the first part of your code, then with the access token at the bottom, pass it into the getPerformance() function:
#Added json import here
import json
import requests
url = "https://api.abcdef.com/AuthorizationServer/Token"
payload = "{\r\n \"grant_type\" : \"password\",\r\n \"username\" : \"user#aldfh.com\",\r\n \"password\" : \"kajshdgfkuyb\",\r\n \"scope\" : \"API\"\r\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
}
response = requests.request("POST", url, headers=headers, data = payload)
#Note the changes here
json = response.read()
data = json.loads(json)
accessToken = data['access_token']
Then wherever you call the getPerformanceFunction(), you want to change it to getPerformance(accessToken). You'll need to change the function definition to this too.
Based on #Cutter's response above, making the following changes worked for me:
import requests
import json
url = "https://api.abcdef.com/AuthorizationServer/Token"
payload = "{\r\n \"grant_type\" : \"password\",\r\n \"username\" : \"user#aldfh.com\",\r\n \"password\" : \"kajshdgfkuyb\",\r\n \"scope\" : \"API\"\r\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
}
response = requests.request("POST", url, headers=headers, data = payload)
testresp = response.text
data = json.loads(testresp)
#Change function definition to :
def getPerformance(data):
# api-endpoint
#Give the specified url ,accessToken
# =============================================================================
BASEURL = 'https://api-c31.ict.com/API/'
accessToken = (data["access_token"])
I'm trying to create a python (3.7) code, that will create a new room at https://bingosync.com/.
Here is my code so far:
import requests
with open('bingosync.txt', 'r') as myfile:
jsonstring = myfile.read()
url = "https://bingosync.com/"
csrfToken = requests.Session().get(url).cookies['csrftoken']
params = {'csrfmiddlewaretoken': csrfToken, 'room_name' : 'test', 'passphrase' : 'test123', 'nickname' : 'testcode', 'game_type' : '18', 'custom_json' : jsonstring }
headers = {'x-csrftoken': csrfToken}
r = requests.Session().post(url, data = params, headers = headers)
print(r.content)
My problem is that, I'm getting 403 from the request, because of invalid/missing CSRF token
As far as I understand, I need to put the token into the headers, but it doesn't matter if I input
'x-csrftoken': csrfToken
or
'csrfmiddlewaretoken' : csrfToken
It wouldn't return me anything else than 403.
I am trying to send a message via Firebase to a certain client. This is my current (test) code:
import json
import requests
import urllib
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Content-Type': 'application/json', 'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
payload = json.dumps(payload)
res = requests.post(server, headers=headers, json=payload)
return res
which produces the following error, returned by Firebase:
JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0.
The following JSON sent to Firebase seems correct to me:
{
"data": {
"type":"dataUpdate"
},
"to":"xxx"
}
which is in the format described by the Firebase documentation. Any idea why Firebase doesn't accept the given data?
When you use json=payload as a parameter to requests.post() you don't need to specify 'Content-Type': 'application/json' in the header. In addition, you are passing a string when the parameter should be payload as a dict (ie. no need for json.dumps())
Try this:
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
res = requests.post(server, headers=headers, json=payload)
return res