The code looks like that:
jsonlistdf = {'column1': '0000098778', 'lookupcolumn': '5187', 'column2': 'Lodon', 'column3': '8000'}
conn = http.client.HTTPSConnection("{}.api.crm4.dynamics.com".format(url))
headers = {
'Authorization': 'Bearer ' +accesstoken,
'OData-MaxVersion': '4.0',
'OData-Version': '4.0',
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
'Prefer': 'return=representation'
}
for i in jsonlistdf:
data = json.dumps(i, default=str)
response = conn.request("POST", "/api/data/v9.2/tablewithlookupcolumn", data, headers)
res = conn.getresponse()
data = res.read()
print(res.status, res.reason)
When I remove the lookupcolumn from the data, it will be posted to dataverse without any problems.
I have understood from the documentation that i need to use the GUI from the lookup column table. The lookup column table is account table. In account table there is the accountid_guid. So how should I use it and where ?
So it goes like that:
The look up table is connected with some other table so you can't directly post any messages there, what you can do is get the GUID from the other dataverse table.
Then you create a away to connect your data here is an example:
In my case the source table row GUID which needs to match with other table is "436047e5-c37a-ed11-81ad-000d3a46f784"
conn = http.client.HTTPSConnection("{}.api.crm4.dynamics.com".format(url))
headers = {
'Authorization': 'Bearer ' +accesstoken,
'OData-MaxVersion': '4.0',
'OData-Version': '4.0',
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
'Prefer': 'return=representation',
'If-Match': '*'
}
payload = "{\"kgt_loc\":\"m1,k2,uN1,k9\",\"kgt_main\":\"0000,0000,\"}"
#payload = "{\"kgt_month\":\"February\"}"
#kgt_accountsegmentid is in the url
reponse = conn.request("PATCH", "/api/data/v9.2/kgt_lookuptable(436047e5-c37a-ed11-81ad-000d3a46f784)", payload, headers)
res = conn.getresponse()
data = res.read()
print(data)
print(res.status, res.reason)
This works well to update the tables
Related
I am sending a PATCH request to my DRF server in Postman and it works perfect
However when I do the same in Python I get:
<Response [405]> http://127.0.0.1:8000/api/title/8174/
b'{"detail":"Method \\"PATCH\\" not allowed."}'
Method Not Allowed
My function that sends data:
ss_token = os.getenv('SS_TOKEN')
headers = {
'Authorization': 'Token ' + ss_token,
}
source = Source.objects.all().first()
url = source.url + str(self.ss_id) + '/'
response = requests.patch(source.url, headers=headers, data={'key':'value'})
print(response, url)
print(response.content)
print(response.reason)
return True
Do I have to send other headers to the API to make the PATCH work?
Ah looks like I made a mistake. Forgot to replace source.url with the new url variable called 'url' variable. Because that add the 'ss_id' at the url' so it becomes 'api/title/ID/' instead of just 'api/title'
url = source.url + str(self.ss_id) + '/'
response = requests.patch(url, headers=headers, data={'key':'value'})
I'm trying to create new order on PayU, via their REST api. I'm sending "get access token", and i have correct answer. Then i send 'create new order', aaaaand i ve got 103 error, error syntax.
I was trying on https://webhook.site/ , and realized why syntax is bad - i have no values in list.
Code of sending POST, when creating new order:
data = {
"notifyUrl": "https://your.eshop.com/notify",
"customerIp": "127.0.0.1",
"merchantPosId": "00000",
"description": "RTV market",
"currencyCode": "PLN",
"totalAmount": "15000",
"products": [{
"name": "Wireless mouse",
"unitPrice": "15000",
"quantity": "1"}]}
headers = {
"Content-Type": "application/json",
"Authorization": str('Bearer ' + access_token).encode()}
r = requests.post('https://webhook.site/9046f3b6-87c4-4be3-8544-8a3454412a55',
data=payload,
headers=headers)
return JsonResponse(r.json())
Webhooc show what i have posted:
customerIp=127.0.0.1¬ifyUrl=https%3A%2F%2Fyour.eshop.com%2Fnotify¤cyCode=PLN&products=name&products=unitPrice&products=quantity&description=RTV+market&merchantPosId=00000&totalAmount=15000
There is no values of 'name', 'unitprice' and 'quantity'. PayU confirmed thats the only problem.
Why? What is wrong?
Sending simple POST request to get a token is always successful.
If you want to send JSON, use the json argument of post():
r = requests.post('https://webhook.site/9046f3b6-87c4-4be3-8544-8a3454412a55',
json=payload, # Use the json argument
headers=headers)
Otherwise the data will be sent as form-encoded data, which I guess isn't what you want, given you're expecting to send the nested products list.
When you use the json argument, the content type is automatically set to application/json so you don't have to set it yourself.
headers = {
# Content-Type not required
"Authorization": str('Bearer ' + access_token).encode()
}
Further info on using requests to send JSON here
I need to bulk load contacts to particular list via Constant Contact API (http://developer.constantcontact.com/docs/contacts-api/contacts-collection.html?method=POST).
I can successfully add contacts using the same JSON string as below into the following API GUI website(https://constantcontact.mashery.com/io-docs (find Tab POST 'add contact' to collection):
update_contact = {"lists": [{"id": "1"}],"email_addresses": [{"email_address": "yasmin1.abob19955#gmail.com"}],"first_name": "Ronald","last_name": "Martone"}
However when I run the same JSON string in my python code I get error 400 with the error message from my response object as the following:
[{"error_key":"query.param.invalid","error_message":"The query parameter first_name is not supported."},
{"error_key":"query.param.invalid","error_message":"The query parameter last_name is not supported."},{"error_key":"query.param.invalid","error_message":"The query parameter lists is not supported."},{"error_key":"query.param.invalid","error_message":"The query parameter email_addresses is not supported."}]
How can two of the same API calls produce different results?and how do I get my python code to work?
code:
import requests
headers = {
'Authorization': 'Bearer X',
'X-Originating-Ip': '1',
'Content-Type': 'application/json'
}
update_contact = {"lists": [{"id": "1"}],"email_addresses": [{"email_address": "yasmin1.abob19955#gmail.com"}],"first_name": "Ronald","last_name": "Martone"}
r_2 = requests.post('https://api.constantcontact.com/v2/contacts?action_by=ACTION_BY_OWNER&api_key=x', headers=headers ,params = update_contact)
print(r_2.text)
You will need to change params to data
r_2 = requests.post('https://api.constantcontact.com/v2/contacts?action_by=ACTION_BY_OWNER&api_key=x', headers=headers ,data = update_contact)
Additionally, you can use a multipart endpoint to upload contacts as well. I have found this to be very easy especially if your contacts are in a csv file.
A sample code would look like this:
import requests as r
import csv
from datetime import datetime
url = 'https://api.constantcontact.com/v2/activities/addcontacts?api_key=<your_api_key>'
headers = {'Authorization': 'Bearer <access_token>',
'X-Originating-Ip': '<ip>',
'content-type': 'multipart/form-data'}
files = {'file_name': 'Book1.csv',
'data': ('Book1.csv', open('Book1.csv', 'rb'),
'application/vnd.ms-excel', {'Expires': '0'}),
'lists':('<insert_listIds_seperated_by_commas>')}
response = r.post(url, headers=headers, files=files)
with open('CC_Upload_Response_Data.csv', 'a', newline='') as f:
writer = csv.writer(f)
time_stamp = datetime.now().strftime('%m-%d-%Y %H:%M')
row = [response, response.text, time_stamp]
writer.writerow(row)
The headers of your csv file need to be like so: "First Name" "Last Name" "Email Address" "Custom Field 1" "Custom Field 2" and so on. You can find a complete list of column names here: http://developer.constantcontact.com/docs/bulk_activities_api/bulk-activities-import-contacts.html
The csv file that this code appends acts like a log if you are going to schedule you .py file to run nightly. The log records the response code, response text and adds a timestamp.
Mess around with it a little and get it the way you like.
I simply cannot get this to work.
header = {"Content-Type": "application/json; charset=utf8"}
params = {"api_dev_key": dev_key, "api_user_name": username, "api_user_password": password}
req = requests.post("http://pastebin.com/api/api_login.php", params = json.dumps(params), headers = header)
print(req.status_code, req.reason, req.text)
The variables (my credentials) are just strings.
The response I get:
(200, 'OK', u'Bad API request, invalid api_dev_key')
There's nothing wrong with the key, this POST works fine when I use https://www.hurl.it
You need to just use data=params:
req = requests.post("http://pastebin.com/api/api_login.php", data=params)
Is it not possible to batch query the graph using 'method/fql.query?query=...' using multiple access tokens?
I have never had trouble in the past batch querying non-fql endpoints with multiple access tokens, but with batch querying FQL calls, only the first call returns data, the rest return an empty body.
The only guess I can make is that it is access_token related, but if so I'm sort of at a loss for how to remedy..
Example:
import json
from pyfaceb import *
user1_tk = '...' #valid token (tested)
user1_qry = '...' #valid query (tested unbatched)
user1_rqst = {'method': 'POST', 'relative_url': 'method/fql.query?query=' + user1_qry, 'access_token': user1_tk}
user2_tk = '...' #valid token (tested)
user2_qry = '...' #valid query (tested unbatched)
user2_rqst = {'method': 'POST', 'relative_url': 'method/fql.query?query=' + user2_qry, 'access_token': user2_tk}
batches = [user1_rqst, user2_rqst]
fbg = FBGraph(user1_tk) # use user1_tk as fallback access token (cuz you have to specify one)
data = fbg.get_batch(batches)
print data[0]['body'] #comes back with data, but
print data[1]['body'] #comes back as an empty array.
Both data[0]['code'] and data[1]['code'] are HTTP 200 responses.
If I change the fallback access token to user2_tk, then data[0]['body'] comes back as an empty array (i.e. vice versa). Even though I'm specifying access_tokens for each request (per: https://developers.facebook.com/docs/reference/api/batch/#differentaccesstokens)
Figured it out. The acccess_token needs to be in the request body, as it is a POST:
...
user1_rqst = {
'method': 'POST',
'relative_url': 'method/fql.query?query=' + user1_qry,
'body': 'access_token=' + user1_tk
}
...
user2_rqst = {
'method': 'POST',
'relative_url': 'method/fql.query?query=' + user2_qry,
'body': 'access_token=' + user2_tk
}