Created
August 10, 2018 12:09
-
-
Save lesha-co/57505d0304fa21de0d9f92c00596bfa8 to your computer and use it in GitHub Desktop.
Как вызывать апи, когда параметры — массивы или объекты
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
def transform(params): | |
params2 = {} | |
for key, value in params.items(): | |
if type(value) is list: | |
for i, v in enumerate(value): | |
new_key = '{}[{}]'.format(key, i) | |
params2[new_key] = v | |
elif type(value) is dict: | |
for k, v in value.items(): | |
new_key = '{}[{}]'.format(key, k) | |
params2[new_key] = v | |
else: | |
params2[key] = value | |
return params2 | |
def make_api_call(domain, method, params=None, transport='json'): | |
real_params = transform(params) if params else None | |
res = requests.get( | |
url='https://{domain}/rest/{method}.{transport}'.format( | |
domain=domain, | |
method=method, | |
transport=transport | |
), | |
params=real_params | |
) | |
# запрос окончится 403 ошибкой, если ни хост, ни ключ не валидны, | |
# но мы хотя бы можем посмотреть, куда он был | |
# дебажные принты: | |
print('Request target:', res.request.url) | |
print('Response status code:', res.status_code) | |
try: | |
print('Response body:', json.dumps(res.json(), ensure_ascii=False, indent=4)) | |
except ValueError as ve: | |
print('Invalid body:', ve) | |
return res | |
r = make_api_call( | |
domain='zalupa.bitrix24.ru', | |
method='crm.lead.list', | |
params={ | |
"order": {"STATUS_ID": "ASC"}, | |
"filter": {">OPPORTUNITY": 0, "!STATUS_ID": "CONVERTED"}, | |
"select": ["ID", "TITLE", "STATUS_ID", "OPPORTUNITY", "CURRENCY_ID"], | |
"auth": "KEY" | |
}, | |
transport='json' | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment