rahy
January 29, 2021, 3:29am
1
I’m learning to use the REST of Frappe/ERPNext using requests.
I can use full url to GET the Customer list:
https://mysite.com/api/resource/Customer?fields=["name","customer_name","customer_type"]&filters=[["Customer", "customer_type","=","Company"]]
But how to write the fields
and filters
as separate parameters in requests?
url = "https://mysite.com/api/resource/Customer"
fields = ["name","customer_name","customer_type"]
filters = [["Customer", "customer_type", "=", "Company"]]
headers = {
'Authorization': 'token xxxxxxxxx:zzzzzzzzz',
'Content-Type': 'application/x-www-form-urlencoded',
}
response = requests.request("GET", url, headers=headers, fields=fields, filters=filters)
This gives error:
(TypeError: request() got an unexpected keyword argument 'fields')
Thanks
kartik
January 29, 2021, 7:13am
2
They need to be passed as query parameters. Refer the link for example.
Passing parameters in URL section.
Quickstart — Requests 2.25.1 documentation
rahy
January 29, 2021, 9:37am
3
From the link:
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
the code will be:
url = "https://mysite.com/api/resource/Customer"
payload = {
"fields":["name","customer_name","customer_type"],
"filters":[["Customer", "customer_type", "=", "Company"]]
}
headers = {
'Authorization': 'token xxxxxxxxx:zzzzzzzzz',
'Content-Type': 'application/x-www-form-urlencoded',
}
response = requests.request("GET", url, params=payload)
that doesn’t work and print(response.url)
gives:
https://mysite.com/api/resource/Customer?fields=name&fields=customer_name&fields=customer_type&filters=Customer&filters=customer_type&filters=%3D&filters=Company
and print(response.text)
doesn’t return the list of Customer.
rmeyer
January 29, 2021, 1:42pm
4
Try this:
import json
url = "https://mysite.com/api/resource/Customer"
payload = {
"fields": json.dumps(["name", "customer_name", "customer_type"]),
"filters": json.dumps([["Customer", "customer_type", "=", "Company"]])
}
headers = {
'Authorization': 'token xxxxxxxxx:zzzzzzzzz',
'Content-Type': 'application/x-www-form-urlencoded',
}
response = requests.request("GET", url, params=payload)
Or this:
url = "https://mysite.com/api/resource/Customer"
payload = {
"fields": '["name","customer_name","customer_type"]',
"filters": '[["Customer","customer_type","=","Company"]]'
}
headers = {
'Authorization': 'token xxxxxxxxx:zzzzzzzzz',
'Content-Type': 'application/x-www-form-urlencoded',
}
response = requests.request("GET", url, params=payload)
5 Likes
rahy
January 29, 2021, 2:05pm
5
Both works. Thanks
But I prefer the 2nd one, simpler.
Is there any advantage/disadvantage of each method?
rmeyer
January 29, 2021, 6:11pm
6
With the first one you can construct a json object or list somewhere in your code, that’s easy to manipulate. With the second one you need string manipulation which works for this simple example but quickly gets tedious.