I have a df like this below. I need to use my first time python API to send data. The api doc needs body to be:
{ "StoreCode": "7144", "GlovoStoreCode": "7144_1", "ProductList": [ { "GlovoId": "10" }, { "GlovoId": "10" } ] }
where ProductList is a list of products of store.
Could please someone show me how to convert my df to json and send data to api with requests (should I use requests.put('https://my_html', 'my_jsons')
CodePudding user response:
Pandas has to_dict
method. You can try prod[['STORECODE', 'GLOVOSTORECODE', 'GLOVO_INDEX']].to_dict(orient="records")
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html
or directly to json: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html#pandas.DataFrame.to_json
To send it use requests depending on what method your api wants you to use post/put.
import requests
import json
url = "http://api_url.com/endpoint"
data = { "StoreCode": "7144", "GlovoStoreCode": "7144_1", "ProductList": [ { "GlovoId": "10" }, { "GlovoId": "10" } ] }
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
CodePudding user response:
And the next question, after I send data with requests.post how Can I get logg from API? (for example about errors?)