Parameter for REST API request

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

They need to be passed as query parameters. Refer the link for example.
Passing parameters in URL section.
Quickstart — Requests 2.25.1 documentation

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.

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

Both works. Thanks
But I prefer the 2nd one, simpler.
Is there any advantage/disadvantage of each method?

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.